diff --git a/cmd/server/user.go b/cmd/server/user.go index ba82222..ae176b5 100644 --- a/cmd/server/user.go +++ b/cmd/server/user.go @@ -5,6 +5,7 @@ import ( "EnGin/internal/ent" "EnGin/internal/ent/role" "EnGin/internal/global" + "EnGin/internal/utils/ctype" "EnGin/internal/utils/pwd" "bufio" "context" @@ -52,14 +53,14 @@ var userCreateCmd = &cobra.Command{ // 尝试查询 admin 角色 adminRole, err := db.Client.Role.Query(). - Where(role.CodeEQ("admin")). + Where(role.CodeEQ(ctype.Admin)). Only(ctx) if err != nil { if ent.IsNotFound(err) { // 如果不存在 admin 角色,自动创建 adminRole, err = db.Client.Role.Create(). - SetCode("admin"). + SetCode(ctype.Admin). SetName("超级管理员"). Save(ctx) if err != nil { diff --git a/internal/ent/migrate/schema.go b/internal/ent/migrate/schema.go index 6bb0b77..0b91e20 100644 --- a/internal/ent/migrate/schema.go +++ b/internal/ent/migrate/schema.go @@ -11,7 +11,7 @@ var ( // RolesColumns holds the columns for the "roles" table. RolesColumns = []*schema.Column{ {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}, } // RolesTable holds the schema information for the "roles" table. diff --git a/internal/ent/mutation.go b/internal/ent/mutation.go index 349d030..54ee08d 100644 --- a/internal/ent/mutation.go +++ b/internal/ent/mutation.go @@ -35,7 +35,8 @@ type RoleMutation struct { op Op typ string id *int - code *string + code *int + addcode *int name *string clearedFields map[string]struct{} users map[int]struct{} @@ -145,12 +146,13 @@ func (m *RoleMutation) IDs(ctx context.Context) ([]int, error) { } // SetCode sets the "code" field. -func (m *RoleMutation) SetCode(s string) { - m.code = &s +func (m *RoleMutation) SetCode(i int) { + m.code = &i + m.addcode = nil } // 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 if v == nil { 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. // 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. -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) { 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 } +// 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. func (m *RoleMutation) ResetCode() { m.code = nil + m.addcode = nil } // 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 { switch name { case role.FieldCode: - v, ok := value.(string) + v, ok := value.(int) if !ok { 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 // this mutation. 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 // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. func (m *RoleMutation) AddedField(name string) (ent.Value, bool) { + switch name { + case role.FieldCode: + return m.AddedCode() + } return nil, false } @@ -381,6 +410,13 @@ func (m *RoleMutation) AddedField(name string) (ent.Value, bool) { // type. func (m *RoleMutation) AddField(name string, value ent.Value) error { 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) } diff --git a/internal/ent/role.go b/internal/ent/role.go index 5e5c87c..bb56e34 100644 --- a/internal/ent/role.go +++ b/internal/ent/role.go @@ -17,7 +17,7 @@ type Role struct { // ID of the ent. ID int `json:"id,omitempty"` // 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 string `json:"name,omitempty"` // 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)) for i := range columns { switch columns[i] { - case role.FieldID: + case role.FieldID, role.FieldCode: values[i] = new(sql.NullInt64) - case role.FieldCode, role.FieldName: + case role.FieldName: values[i] = new(sql.NullString) default: values[i] = new(sql.UnknownType) @@ -75,10 +75,10 @@ func (_m *Role) assignValues(columns []string, values []any) error { } _m.ID = int(value.Int64) 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]) } else if value.Valid { - _m.Code = value.String + _m.Code = int(value.Int64) } case role.FieldName: if value, ok := values[i].(*sql.NullString); !ok { @@ -128,7 +128,7 @@ func (_m *Role) String() string { builder.WriteString("Role(") builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID)) builder.WriteString("code=") - builder.WriteString(_m.Code) + builder.WriteString(fmt.Sprintf("%v", _m.Code)) builder.WriteString(", ") builder.WriteString("name=") builder.WriteString(_m.Name) diff --git a/internal/ent/role/role.go b/internal/ent/role/role.go index ae4a0a4..d53afd5 100644 --- a/internal/ent/role/role.go +++ b/internal/ent/role/role.go @@ -52,7 +52,7 @@ func ValidColumn(column string) bool { var ( // 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 func(string) error ) diff --git a/internal/ent/role/where.go b/internal/ent/role/where.go index e5f3342..aea8422 100644 --- a/internal/ent/role/where.go +++ b/internal/ent/role/where.go @@ -55,7 +55,7 @@ func IDLTE(id int) predicate.Role { } // 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)) } @@ -65,70 +65,45 @@ func Name(v string) predicate.Role { } // 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)) } // 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)) } // 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...)) } // 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...)) } // 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)) } // 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)) } // 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)) } // 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)) } -// 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. func NameEQ(v string) predicate.Role { return predicate.Role(sql.FieldEQ(FieldName, v)) diff --git a/internal/ent/role_create.go b/internal/ent/role_create.go index 6faf160..7760f31 100644 --- a/internal/ent/role_create.go +++ b/internal/ent/role_create.go @@ -21,7 +21,7 @@ type RoleCreate struct { } // SetCode sets the "code" field. -func (_c *RoleCreate) SetCode(v string) *RoleCreate { +func (_c *RoleCreate) SetCode(v int) *RoleCreate { _c.mutation.SetCode(v) return _c } @@ -124,7 +124,7 @@ func (_c *RoleCreate) createSpec() (*Role, *sqlgraph.CreateSpec) { _spec = sqlgraph.NewCreateSpec(role.Table, sqlgraph.NewFieldSpec(role.FieldID, field.TypeInt)) ) if value, ok := _c.mutation.Code(); ok { - _spec.SetField(role.FieldCode, field.TypeString, value) + _spec.SetField(role.FieldCode, field.TypeInt, value) _node.Code = value } if value, ok := _c.mutation.Name(); ok { diff --git a/internal/ent/role_query.go b/internal/ent/role_query.go index b895339..b40263b 100644 --- a/internal/ent/role_query.go +++ b/internal/ent/role_query.go @@ -299,7 +299,7 @@ func (_q *RoleQuery) WithUsers(opts ...func(*UserQuery)) *RoleQuery { // Example: // // var v []struct { -// Code string `json:"code,omitempty"` +// Code int `json:"code,omitempty"` // Count int `json:"count,omitempty"` // } // @@ -322,7 +322,7 @@ func (_q *RoleQuery) GroupBy(field string, fields ...string) *RoleGroupBy { // Example: // // var v []struct { -// Code string `json:"code,omitempty"` +// Code int `json:"code,omitempty"` // } // // client.Role.Query(). diff --git a/internal/ent/role_update.go b/internal/ent/role_update.go index 9809207..d0e073e 100644 --- a/internal/ent/role_update.go +++ b/internal/ent/role_update.go @@ -29,19 +29,26 @@ func (_u *RoleUpdate) Where(ps ...predicate.Role) *RoleUpdate { } // 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) return _u } // 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 { _u.SetCode(*v) } 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. func (_u *RoleUpdate) SetName(v string) *RoleUpdate { _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 { - _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 { _spec.SetField(role.FieldName, field.TypeString, value) @@ -223,19 +233,26 @@ type RoleUpdateOne struct { } // 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) return _u } // 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 { _u.SetCode(*v) } 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. func (_u *RoleUpdateOne) SetName(v string) *RoleUpdateOne { _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 { - _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 { _spec.SetField(role.FieldName, field.TypeString, value) diff --git a/internal/ent/runtime.go b/internal/ent/runtime.go index 4e171cd..b8f60b7 100644 --- a/internal/ent/runtime.go +++ b/internal/ent/runtime.go @@ -18,7 +18,7 @@ func init() { // roleDescCode is the schema descriptor for code field. roleDescCode := roleFields[0].Descriptor() // 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 := roleFields[1].Descriptor() // role.NameValidator is a validator for the "name" field. It is called by the builders before save. diff --git a/internal/ent/schema/role.go b/internal/ent/schema/role.go index d596b7a..bcf7427 100644 --- a/internal/ent/schema/role.go +++ b/internal/ent/schema/role.go @@ -12,7 +12,7 @@ type Role struct { func (Role) Fields() []ent.Field { return []ent.Field{ - field.String("code").Unique().NotEmpty(), + field.Int("code").Unique().Positive(), field.String("name").NotEmpty(), } } diff --git a/internal/ent/user_custom.go b/internal/ent/user_custom.go new file mode 100644 index 0000000..ef88af4 --- /dev/null +++ b/internal/ent/user_custom.go @@ -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 +} diff --git a/internal/middleware/auth.go b/internal/middleware/auth.go index 0203723..40c636a 100644 --- a/internal/middleware/auth.go +++ b/internal/middleware/auth.go @@ -5,6 +5,7 @@ import ( "EnGin/internal/ent/user" "EnGin/internal/global" "EnGin/internal/service/redis_ser" + "EnGin/internal/utils/ctype" "EnGin/internal/utils/jwts" "EnGin/internal/utils/res" "fmt" @@ -63,7 +64,7 @@ func AuthAdmin(c *gin.Context) { // 遍历用户的角色列表,检查是否有 "admin" 角色代码 isAdmin := false for _, role := range u.Edges.Roles { - if role.Code == "admin" { + if role.Code == ctype.Admin { isAdmin = true break } diff --git a/internal/utils/ctype/role_type.go b/internal/utils/ctype/role_type.go new file mode 100644 index 0000000..cb908dd --- /dev/null +++ b/internal/utils/ctype/role_type.go @@ -0,0 +1,8 @@ +package ctype + +const ( + Admin = iota + 1 + Manager + User + guest +)