feat: 添加角色类型常量及用户主角色获取方法

This commit is contained in:
unclesam committed 2026-07-08 08:19:51 +08:00
1 parent c5977ce354
commit 20ad8115da
14 files changed
+123 -64

No files matched your search

+3 -2
View File
@@ -5,6 +5,7 @@ import (
"EnGin/internal/ent" "EnGin/internal/ent"
"EnGin/internal/ent/role" "EnGin/internal/ent/role"
"EnGin/internal/global" "EnGin/internal/global"
"EnGin/internal/utils/ctype"
"EnGin/internal/utils/pwd" "EnGin/internal/utils/pwd"
"bufio" "bufio"
"context" "context"
@@ -52,14 +53,14 @@ var userCreateCmd = &cobra.Command{
// 尝试查询 admin 角色 // 尝试查询 admin 角色
adminRole, err := db.Client.Role.Query(). adminRole, err := db.Client.Role.Query().
Where(role.CodeEQ("admin")). Where(role.CodeEQ(ctype.Admin)).
Only(ctx) Only(ctx)
if err != nil { if err != nil {
if ent.IsNotFound(err) { if ent.IsNotFound(err) {
// 如果不存在 admin 角色,自动创建 // 如果不存在 admin 角色,自动创建
adminRole, err = db.Client.Role.Create(). adminRole, err = db.Client.Role.Create().
SetCode("admin"). SetCode(ctype.Admin).
SetName("超级管理员"). SetName("超级管理员").
Save(ctx) Save(ctx)
if err != nil { if err != nil {
+1 -1
View File
@@ -11,7 +11,7 @@ var (
// RolesColumns holds the columns for the "roles" table. // RolesColumns holds the columns for the "roles" table.
RolesColumns = []*schema.Column{ RolesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true}, {Name: "id", Type: field.TypeInt, Increment: true},
{Name: "code", Type: field.TypeString, Unique: true}, {Name: "code", Type: field.TypeInt, Unique: true},
{Name: "name", Type: field.TypeString}, {Name: "name", Type: field.TypeString},
} }
// RolesTable holds the schema information for the "roles" table. // RolesTable holds the schema information for the "roles" table.
+43 -7
View File
@@ -35,7 +35,8 @@ type RoleMutation struct {
op Op op Op
typ string typ string
id *int id *int
code *string code *int
addcode *int
name *string name *string
clearedFields map[string]struct{} clearedFields map[string]struct{}
users map[int]struct{} users map[int]struct{}
@@ -145,12 +146,13 @@ func (m *RoleMutation) IDs(ctx context.Context) ([]int, error) {
} }
// SetCode sets the "code" field. // SetCode sets the "code" field.
func (m *RoleMutation) SetCode(s string) { func (m *RoleMutation) SetCode(i int) {
m.code = &s m.code = &i
m.addcode = nil
} }
// Code returns the value of the "code" field in the mutation. // Code returns the value of the "code" field in the mutation.
func (m *RoleMutation) Code() (r string, exists bool) { func (m *RoleMutation) Code() (r int, exists bool) {
v := m.code v := m.code
if v == nil { if v == nil {
return return
@@ -161,7 +163,7 @@ func (m *RoleMutation) Code() (r string, exists bool) {
// OldCode returns the old "code" field's value of the Role entity. // OldCode returns the old "code" field's value of the Role entity.
// If the Role object wasn't provided to the builder, the object is fetched from the database. // If the Role object wasn't provided to the builder, the object is fetched from the database.
// An error is returned if the mutation operation is not UpdateOne, or the database query fails. // An error is returned if the mutation operation is not UpdateOne, or the database query fails.
func (m *RoleMutation) OldCode(ctx context.Context) (v string, err error) { func (m *RoleMutation) OldCode(ctx context.Context) (v int, err error) {
if !m.op.Is(OpUpdateOne) { if !m.op.Is(OpUpdateOne) {
return v, errors.New("OldCode is only allowed on UpdateOne operations") return v, errors.New("OldCode is only allowed on UpdateOne operations")
} }
@@ -175,9 +177,28 @@ func (m *RoleMutation) OldCode(ctx context.Context) (v string, err error) {
return oldValue.Code, nil return oldValue.Code, nil
} }
// AddCode adds i to the "code" field.
func (m *RoleMutation) AddCode(i int) {
if m.addcode != nil {
*m.addcode += i
} else {
m.addcode = &i
}
}
// AddedCode returns the value that was added to the "code" field in this mutation.
func (m *RoleMutation) AddedCode() (r int, exists bool) {
v := m.addcode
if v == nil {
return
}
return *v, true
}
// ResetCode resets all changes to the "code" field. // ResetCode resets all changes to the "code" field.
func (m *RoleMutation) ResetCode() { func (m *RoleMutation) ResetCode() {
m.code = nil m.code = nil
m.addcode = nil
} }
// SetName sets the "name" field. // SetName sets the "name" field.
@@ -346,7 +367,7 @@ func (m *RoleMutation) OldField(ctx context.Context, name string) (ent.Value, er
func (m *RoleMutation) SetField(name string, value ent.Value) error { func (m *RoleMutation) SetField(name string, value ent.Value) error {
switch name { switch name {
case role.FieldCode: case role.FieldCode:
v, ok := value.(string) v, ok := value.(int)
if !ok { if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name) return fmt.Errorf("unexpected type %T for field %s", value, name)
} }
@@ -366,13 +387,21 @@ func (m *RoleMutation) SetField(name string, value ent.Value) error {
// AddedFields returns all numeric fields that were incremented/decremented during // AddedFields returns all numeric fields that were incremented/decremented during
// this mutation. // this mutation.
func (m *RoleMutation) AddedFields() []string { func (m *RoleMutation) AddedFields() []string {
return nil var fields []string
if m.addcode != nil {
fields = append(fields, role.FieldCode)
}
return fields
} }
// AddedField returns the numeric value that was incremented/decremented on a field // AddedField returns the numeric value that was incremented/decremented on a field
// with the given name. The second boolean return value indicates that this field // with the given name. The second boolean return value indicates that this field
// was not set, or was not defined in the schema. // was not set, or was not defined in the schema.
func (m *RoleMutation) AddedField(name string) (ent.Value, bool) { func (m *RoleMutation) AddedField(name string) (ent.Value, bool) {
switch name {
case role.FieldCode:
return m.AddedCode()
}
return nil, false return nil, false
} }
@@ -381,6 +410,13 @@ func (m *RoleMutation) AddedField(name string) (ent.Value, bool) {
// type. // type.
func (m *RoleMutation) AddField(name string, value ent.Value) error { func (m *RoleMutation) AddField(name string, value ent.Value) error {
switch name { switch name {
case role.FieldCode:
v, ok := value.(int)
if !ok {
return fmt.Errorf("unexpected type %T for field %s", value, name)
}
m.AddCode(v)
return nil
} }
return fmt.Errorf("unknown Role numeric field %s", name) return fmt.Errorf("unknown Role numeric field %s", name)
} }
+6 -6
View File
@@ -17,7 +17,7 @@ type Role struct {
// ID of the ent. // ID of the ent.
ID int `json:"id,omitempty"` ID int `json:"id,omitempty"`
// Code holds the value of the "code" field. // Code holds the value of the "code" field.
Code string `json:"code,omitempty"` Code int `json:"code,omitempty"`
// Name holds the value of the "name" field. // Name holds the value of the "name" field.
Name string `json:"name,omitempty"` Name string `json:"name,omitempty"`
// Edges holds the relations/edges for other nodes in the graph. // Edges holds the relations/edges for other nodes in the graph.
@@ -49,9 +49,9 @@ func (*Role) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns)) values := make([]any, len(columns))
for i := range columns { for i := range columns {
switch columns[i] { switch columns[i] {
case role.FieldID: case role.FieldID, role.FieldCode:
values[i] = new(sql.NullInt64) values[i] = new(sql.NullInt64)
case role.FieldCode, role.FieldName: case role.FieldName:
values[i] = new(sql.NullString) values[i] = new(sql.NullString)
default: default:
values[i] = new(sql.UnknownType) values[i] = new(sql.UnknownType)
@@ -75,10 +75,10 @@ func (_m *Role) assignValues(columns []string, values []any) error {
} }
_m.ID = int(value.Int64) _m.ID = int(value.Int64)
case role.FieldCode: case role.FieldCode:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field code", values[i]) return fmt.Errorf("unexpected type %T for field code", values[i])
} else if value.Valid { } else if value.Valid {
_m.Code = value.String _m.Code = int(value.Int64)
} }
case role.FieldName: case role.FieldName:
if value, ok := values[i].(*sql.NullString); !ok { if value, ok := values[i].(*sql.NullString); !ok {
@@ -128,7 +128,7 @@ func (_m *Role) String() string {
builder.WriteString("Role(") builder.WriteString("Role(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("code=") builder.WriteString("code=")
builder.WriteString(_m.Code) builder.WriteString(fmt.Sprintf("%v", _m.Code))
builder.WriteString(", ") builder.WriteString(", ")
builder.WriteString("name=") builder.WriteString("name=")
builder.WriteString(_m.Name) builder.WriteString(_m.Name)
+1 -1
View File
@@ -52,7 +52,7 @@ func ValidColumn(column string) bool {
var ( var (
// CodeValidator is a validator for the "code" field. It is called by the builders before save. // CodeValidator is a validator for the "code" field. It is called by the builders before save.
CodeValidator func(string) error CodeValidator func(int) error
// NameValidator is a validator for the "name" field. It is called by the builders before save. // NameValidator is a validator for the "name" field. It is called by the builders before save.
NameValidator func(string) error NameValidator func(string) error
) )
+9 -34
View File
@@ -55,7 +55,7 @@ func IDLTE(id int) predicate.Role {
} }
// Code applies equality check predicate on the "code" field. It's identical to CodeEQ. // Code applies equality check predicate on the "code" field. It's identical to CodeEQ.
func Code(v string) predicate.Role { func Code(v int) predicate.Role {
return predicate.Role(sql.FieldEQ(FieldCode, v)) return predicate.Role(sql.FieldEQ(FieldCode, v))
} }
@@ -65,70 +65,45 @@ func Name(v string) predicate.Role {
} }
// CodeEQ applies the EQ predicate on the "code" field. // CodeEQ applies the EQ predicate on the "code" field.
func CodeEQ(v string) predicate.Role { func CodeEQ(v int) predicate.Role {
return predicate.Role(sql.FieldEQ(FieldCode, v)) return predicate.Role(sql.FieldEQ(FieldCode, v))
} }
// CodeNEQ applies the NEQ predicate on the "code" field. // CodeNEQ applies the NEQ predicate on the "code" field.
func CodeNEQ(v string) predicate.Role { func CodeNEQ(v int) predicate.Role {
return predicate.Role(sql.FieldNEQ(FieldCode, v)) return predicate.Role(sql.FieldNEQ(FieldCode, v))
} }
// CodeIn applies the In predicate on the "code" field. // CodeIn applies the In predicate on the "code" field.
func CodeIn(vs ...string) predicate.Role { func CodeIn(vs ...int) predicate.Role {
return predicate.Role(sql.FieldIn(FieldCode, vs...)) return predicate.Role(sql.FieldIn(FieldCode, vs...))
} }
// CodeNotIn applies the NotIn predicate on the "code" field. // CodeNotIn applies the NotIn predicate on the "code" field.
func CodeNotIn(vs ...string) predicate.Role { func CodeNotIn(vs ...int) predicate.Role {
return predicate.Role(sql.FieldNotIn(FieldCode, vs...)) return predicate.Role(sql.FieldNotIn(FieldCode, vs...))
} }
// CodeGT applies the GT predicate on the "code" field. // CodeGT applies the GT predicate on the "code" field.
func CodeGT(v string) predicate.Role { func CodeGT(v int) predicate.Role {
return predicate.Role(sql.FieldGT(FieldCode, v)) return predicate.Role(sql.FieldGT(FieldCode, v))
} }
// CodeGTE applies the GTE predicate on the "code" field. // CodeGTE applies the GTE predicate on the "code" field.
func CodeGTE(v string) predicate.Role { func CodeGTE(v int) predicate.Role {
return predicate.Role(sql.FieldGTE(FieldCode, v)) return predicate.Role(sql.FieldGTE(FieldCode, v))
} }
// CodeLT applies the LT predicate on the "code" field. // CodeLT applies the LT predicate on the "code" field.
func CodeLT(v string) predicate.Role { func CodeLT(v int) predicate.Role {
return predicate.Role(sql.FieldLT(FieldCode, v)) return predicate.Role(sql.FieldLT(FieldCode, v))
} }
// CodeLTE applies the LTE predicate on the "code" field. // CodeLTE applies the LTE predicate on the "code" field.
func CodeLTE(v string) predicate.Role { func CodeLTE(v int) predicate.Role {
return predicate.Role(sql.FieldLTE(FieldCode, v)) return predicate.Role(sql.FieldLTE(FieldCode, v))
} }
// CodeContains applies the Contains predicate on the "code" field.
func CodeContains(v string) predicate.Role {
return predicate.Role(sql.FieldContains(FieldCode, v))
}
// CodeHasPrefix applies the HasPrefix predicate on the "code" field.
func CodeHasPrefix(v string) predicate.Role {
return predicate.Role(sql.FieldHasPrefix(FieldCode, v))
}
// CodeHasSuffix applies the HasSuffix predicate on the "code" field.
func CodeHasSuffix(v string) predicate.Role {
return predicate.Role(sql.FieldHasSuffix(FieldCode, v))
}
// CodeEqualFold applies the EqualFold predicate on the "code" field.
func CodeEqualFold(v string) predicate.Role {
return predicate.Role(sql.FieldEqualFold(FieldCode, v))
}
// CodeContainsFold applies the ContainsFold predicate on the "code" field.
func CodeContainsFold(v string) predicate.Role {
return predicate.Role(sql.FieldContainsFold(FieldCode, v))
}
// NameEQ applies the EQ predicate on the "name" field. // NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Role { func NameEQ(v string) predicate.Role {
return predicate.Role(sql.FieldEQ(FieldName, v)) return predicate.Role(sql.FieldEQ(FieldName, v))
+2 -2
View File
@@ -21,7 +21,7 @@ type RoleCreate struct {
} }
// SetCode sets the "code" field. // SetCode sets the "code" field.
func (_c *RoleCreate) SetCode(v string) *RoleCreate { func (_c *RoleCreate) SetCode(v int) *RoleCreate {
_c.mutation.SetCode(v) _c.mutation.SetCode(v)
return _c return _c
} }
@@ -124,7 +124,7 @@ func (_c *RoleCreate) createSpec() (*Role, *sqlgraph.CreateSpec) {
_spec = sqlgraph.NewCreateSpec(role.Table, sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt)) _spec = sqlgraph.NewCreateSpec(role.Table, sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt))
) )
if value, ok := _c.mutation.Code(); ok { if value, ok := _c.mutation.Code(); ok {
_spec.SetField(role.FieldCode, field.TypeString, value) _spec.SetField(role.FieldCode, field.TypeInt, value)
_node.Code = value _node.Code = value
} }
if value, ok := _c.mutation.Name(); ok { if value, ok := _c.mutation.Name(); ok {
+2 -2
View File
@@ -299,7 +299,7 @@ func (_q *RoleQuery) WithUsers(opts ...func(*UserQuery)) *RoleQuery {
// Example: // Example:
// //
// var v []struct { // var v []struct {
// Code string `json:"code,omitempty"` // Code int `json:"code,omitempty"`
// Count int `json:"count,omitempty"` // Count int `json:"count,omitempty"`
// } // }
// //
@@ -322,7 +322,7 @@ func (_q *RoleQuery) GroupBy(field string, fields ...string) *RoleGroupBy {
// Example: // Example:
// //
// var v []struct { // var v []struct {
// Code string `json:"code,omitempty"` // Code int `json:"code,omitempty"`
// } // }
// //
// client.Role.Query(). // client.Role.Query().
+26 -6
View File
@@ -29,19 +29,26 @@ func (_u *RoleUpdate) Where(ps ...predicate.Role) *RoleUpdate {
} }
// SetCode sets the "code" field. // SetCode sets the "code" field.
func (_u *RoleUpdate) SetCode(v string) *RoleUpdate { func (_u *RoleUpdate) SetCode(v int) *RoleUpdate {
_u.mutation.ResetCode()
_u.mutation.SetCode(v) _u.mutation.SetCode(v)
return _u return _u
} }
// SetNillableCode sets the "code" field if the given value is not nil. // SetNillableCode sets the "code" field if the given value is not nil.
func (_u *RoleUpdate) SetNillableCode(v *string) *RoleUpdate { func (_u *RoleUpdate) SetNillableCode(v *int) *RoleUpdate {
if v != nil { if v != nil {
_u.SetCode(*v) _u.SetCode(*v)
} }
return _u return _u
} }
// AddCode adds value to the "code" field.
func (_u *RoleUpdate) AddCode(v int) *RoleUpdate {
_u.mutation.AddCode(v)
return _u
}
// SetName sets the "name" field. // SetName sets the "name" field.
func (_u *RoleUpdate) SetName(v string) *RoleUpdate { func (_u *RoleUpdate) SetName(v string) *RoleUpdate {
_u.mutation.SetName(v) _u.mutation.SetName(v)
@@ -152,7 +159,10 @@ func (_u *RoleUpdate) sqlSave(ctx context.Context) (_node int, err error) {
} }
} }
if value, ok := _u.mutation.Code(); ok { if value, ok := _u.mutation.Code(); ok {
_spec.SetField(role.FieldCode, field.TypeString, value) _spec.SetField(role.FieldCode, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedCode(); ok {
_spec.AddField(role.FieldCode, field.TypeInt, value)
} }
if value, ok := _u.mutation.Name(); ok { if value, ok := _u.mutation.Name(); ok {
_spec.SetField(role.FieldName, field.TypeString, value) _spec.SetField(role.FieldName, field.TypeString, value)
@@ -223,19 +233,26 @@ type RoleUpdateOne struct {
} }
// SetCode sets the "code" field. // SetCode sets the "code" field.
func (_u *RoleUpdateOne) SetCode(v string) *RoleUpdateOne { func (_u *RoleUpdateOne) SetCode(v int) *RoleUpdateOne {
_u.mutation.ResetCode()
_u.mutation.SetCode(v) _u.mutation.SetCode(v)
return _u return _u
} }
// SetNillableCode sets the "code" field if the given value is not nil. // SetNillableCode sets the "code" field if the given value is not nil.
func (_u *RoleUpdateOne) SetNillableCode(v *string) *RoleUpdateOne { func (_u *RoleUpdateOne) SetNillableCode(v *int) *RoleUpdateOne {
if v != nil { if v != nil {
_u.SetCode(*v) _u.SetCode(*v)
} }
return _u return _u
} }
// AddCode adds value to the "code" field.
func (_u *RoleUpdateOne) AddCode(v int) *RoleUpdateOne {
_u.mutation.AddCode(v)
return _u
}
// SetName sets the "name" field. // SetName sets the "name" field.
func (_u *RoleUpdateOne) SetName(v string) *RoleUpdateOne { func (_u *RoleUpdateOne) SetName(v string) *RoleUpdateOne {
_u.mutation.SetName(v) _u.mutation.SetName(v)
@@ -376,7 +393,10 @@ func (_u *RoleUpdateOne) sqlSave(ctx context.Context) (_node *Role, err error) {
} }
} }
if value, ok := _u.mutation.Code(); ok { if value, ok := _u.mutation.Code(); ok {
_spec.SetField(role.FieldCode, field.TypeString, value) _spec.SetField(role.FieldCode, field.TypeInt, value)
}
if value, ok := _u.mutation.AddedCode(); ok {
_spec.AddField(role.FieldCode, field.TypeInt, value)
} }
if value, ok := _u.mutation.Name(); ok { if value, ok := _u.mutation.Name(); ok {
_spec.SetField(role.FieldName, field.TypeString, value) _spec.SetField(role.FieldName, field.TypeString, value)
+1 -1
View File
@@ -18,7 +18,7 @@ func init() {
// roleDescCode is the schema descriptor for code field. // roleDescCode is the schema descriptor for code field.
roleDescCode := roleFields[0].Descriptor() roleDescCode := roleFields[0].Descriptor()
// role.CodeValidator is a validator for the "code" field. It is called by the builders before save. // role.CodeValidator is a validator for the "code" field. It is called by the builders before save.
role.CodeValidator = roleDescCode.Validators[0].(func(string) error) role.CodeValidator = roleDescCode.Validators[0].(func(int) error)
// roleDescName is the schema descriptor for name field. // roleDescName is the schema descriptor for name field.
roleDescName := roleFields[1].Descriptor() roleDescName := roleFields[1].Descriptor()
// role.NameValidator is a validator for the "name" field. It is called by the builders before save. // role.NameValidator is a validator for the "name" field. It is called by the builders before save.
+1 -1
View File
@@ -12,7 +12,7 @@ type Role struct {
func (Role) Fields() []ent.Field { func (Role) Fields() []ent.Field {
return []ent.Field{ return []ent.Field{
field.String("code").Unique().NotEmpty(), field.Int("code").Unique().Positive(),
field.String("name").NotEmpty(), field.String("name").NotEmpty(),
} }
} }
+18
View File
@@ -0,0 +1,18 @@
package ent
// GetPrimaryRole 获取用户主角色(权限最高的角色)
func (u *User) GetPrimaryRole() *Role {
// 如果没有预加载角色,或者角色列表为空,直接返回 nil
if u.Edges.Roles == nil || len(u.Edges.Roles) == 0 {
return nil
}
primary := u.Edges.Roles[0]
for _, r := range u.Edges.Roles {
if r.Code < primary.Code {
primary = r
}
}
return primary
}
+2 -1
View File
@@ -5,6 +5,7 @@ import (
"EnGin/internal/ent/user" "EnGin/internal/ent/user"
"EnGin/internal/global" "EnGin/internal/global"
"EnGin/internal/service/redis_ser" "EnGin/internal/service/redis_ser"
"EnGin/internal/utils/ctype"
"EnGin/internal/utils/jwts" "EnGin/internal/utils/jwts"
"EnGin/internal/utils/res" "EnGin/internal/utils/res"
"fmt" "fmt"
@@ -63,7 +64,7 @@ func AuthAdmin(c *gin.Context) {
// 遍历用户的角色列表,检查是否有 "admin" 角色代码 // 遍历用户的角色列表,检查是否有 "admin" 角色代码
isAdmin := false isAdmin := false
for _, role := range u.Edges.Roles { for _, role := range u.Edges.Roles {
if role.Code == "admin" { if role.Code == ctype.Admin {
isAdmin = true isAdmin = true
break break
} }
+8
View File
@@ -0,0 +1,8 @@
package ctype
const (
Admin = iota + 1
Manager
User
guest
)