用户加密机制设计初步完成

This commit is contained in:
veypi
2021-10-21 18:09:40 +08:00
parent cd7029c298
commit 82b64a4bb2
40 changed files with 1027 additions and 322 deletions
+66
View File
@@ -0,0 +1,66 @@
package auth
import (
"OneAuth/models"
"gorm.io/gorm"
)
// 定义oa系统权限
type Resource = string
const (
User Resource = "user"
APP Resource = "app"
Res Resource = "resource"
Role Resource = "role"
Auth Resource = "auth"
)
func BindUserRole(tx *gorm.DB, userID uint, roleID uint) error {
r := &models.Role{}
r.ID = roleID
err := tx.Where(r).First(r).Error
if err != nil {
return err
}
ur := &models.UserRole{}
ur.RoleID = roleID
if r.IsUnique {
err = tx.Where(ur).Update("user_id", userID).Error
} else {
ur.UserID = userID
err = tx.Where(ur).FirstOrCreate(ur).Error
}
return err
}
func BindUserAuth(tx *gorm.DB, userID uint, resID uint, level models.AuthLevel, ruid string) error {
return bind(tx, userID, resID, level, ruid, false)
}
func BindRoleAuth(tx *gorm.DB, roleID uint, resID uint, level models.AuthLevel, ruid string) error {
return bind(tx, roleID, resID, level, ruid, true)
}
func bind(tx *gorm.DB, id uint, resID uint, level models.AuthLevel, ruid string, isRole bool) error {
r := &models.Resource{}
r.ID = resID
err := tx.Where(r).First(r).Error
if err != nil {
return err
}
au := &models.Auth{
AppID: r.AppID,
ResourceID: resID,
RID: r.Name,
RUID: ruid,
Level: level,
}
if isRole {
au.RoleID = &id
} else {
au.UserID = &id
}
return tx.Where(au).FirstOrCreate(au).Error
}
-43
View File
@@ -1,43 +0,0 @@
package auth
import (
"OneAuth/cfg"
"OneAuth/libs/oerr"
"OneAuth/models"
"github.com/veypi/OneBD"
"github.com/veypi/OneBD/rfc"
)
type UserHandler struct {
Payload *models.PayLoad
ignoreMethod map[rfc.Method]bool
}
func (a *UserHandler) Init(m OneBD.Meta) error {
if a.ignoreMethod != nil && a.ignoreMethod[m.Method()] {
return nil
}
a.Payload = new(models.PayLoad)
token := m.GetHeader("auth_token")
if token == "" {
return oerr.NotLogin
}
ok, err := models.ParseToken(token, cfg.CFG.Key, a.Payload)
if ok {
return nil
}
return oerr.NotLogin.Attach(err)
}
func (a *UserHandler) Ignore(methods ...rfc.Method) {
if a.ignoreMethod == nil {
a.ignoreMethod = make(map[rfc.Method]bool)
}
for _, m := range methods {
a.ignoreMethod[m] = true
}
}
func (a *UserHandler) GetAuth(ResourceID string, ResourceUUID ...string) models.AuthLevel {
return a.Payload.GetAuth(ResourceID, ResourceUUID...)
}
-27
View File
@@ -1,27 +0,0 @@
package auth
import (
"OneAuth/models"
"github.com/veypi/utils"
"sync"
)
var keyCache = sync.Map{}
func GetUserKey(uid uint, app *models.App) string {
if app.ID == 1 {
key, _ := keyCache.LoadOrStore(uid, utils.RandSeq(16))
return key.(string)
}
// TODO: 获取其他应用user_key
return ""
}
func RefreshUserKey(uid uint, app *models.App) string {
if app.ID == 1 {
key := utils.RandSeq(16)
keyCache.Store(uid, key)
return key
}
return ""
}