You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
OneAuth/api/middleware/org.go

49 lines
1.1 KiB
Go

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// Copyright (C) 2024 veypi <i@veypi.com>
// 2025-03-04 16:08:06
// Distributed under terms of the MIT license.
package middleware
import (
"github.com/veypi/vbase/cfg"
"github.com/veypi/vbase/models"
"github.com/veypi/vigo"
)
// OrgContext 组织上下文中间件
// 从header或query参数中获取org_id并验证用户是否为该组织成员
func OrgContext() func(*vigo.X) error {
return func(x *vigo.X) error {
orgID := x.Request.Header.Get("X-Org-ID")
if orgID == "" {
orgID = x.Request.URL.Query().Get("org_id")
}
if orgID == "" {
// 没有指定组织,跳过
return nil
}
userID := ""
if uid, ok := x.Get("user_id").(string); ok {
userID = uid
}
if userID == "" {
return vigo.ErrNotAuthorized
}
// 验证用户是否为组织成员
var member models.OrgMember
if err := cfg.DB().Where("org_id = ? AND user_id = ? AND status = ?",
orgID, userID, models.MemberStatusActive).First(&member).Error; err != nil {
return vigo.ErrForbidden.WithString("you are not a member of this organization")
}
x.Set("org_id", orgID)
x.Set("org_roles", member.RoleIDs)
return nil
}
}