gin-admin-2

思考并回答以下问题:

router

router/router.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
package router

import (
"github.com/casbin/casbin/v2"
"github.com/gin-gonic/gin"
"github.com/google/wire"

"github.com/LyricTian/gin-admin/v8/internal/app/api"
"github.com/LyricTian/gin-admin/v8/internal/app/middleware"
"github.com/LyricTian/gin-admin/v8/pkg/auth"
)

var _ IRouter = (*Router)(nil)

var RouterSet = wire.NewSet(
wire.Struct(new(Router), "*"),
wire.Bind(new(IRouter), new(*Router))
)

type IRouter interface {
Register(app *gin.Engine) error
Prefixes() []string
}

type Router struct {
Auth auth.Auther
CasbinEnforcer *casbin.SyncedEnforcer
LoginAPI *api.LoginAPI
MenuAPI *api.MenuAPI
RoleAPI *api.RoleAPI
UserAPI *api.UserAPI
} // end

func (a *Router) Register(app *gin.Engine) error {
a.RegisterAPI(app)
return nil
}

func (a *Router) Prefixes() []string {
return []string{
"/api/",
}
}

// RegisterAPI register api group router
func (a *Router) RegisterAPI(app *gin.Engine) {
g := app.Group("/api")

g.Use(middleware.UserAuthMiddleware(a.Auth,
middleware.AllowPathPrefixSkipper("/api/v1/pub/login"),
))

g.Use(middleware.CasbinMiddleware(a.CasbinEnforcer,
middleware.AllowPathPrefixSkipper("/api/v1/pub"),
))

g.Use(middleware.RateLimiterMiddleware())

v1 := g.Group("/v1")
{
pub := v1.Group("/pub")
{
gLogin := pub.Group("login")
{
gLogin.GET("captchaid", a.LoginAPI.GetCaptcha)
gLogin.GET("captcha", a.LoginAPI.ResCaptcha)
gLogin.POST("", a.LoginAPI.Login)
gLogin.POST("exit", a.LoginAPI.Logout)
}

gCurrent := pub.Group("current")
{
gCurrent.PUT("password", a.LoginAPI.UpdatePassword)
gCurrent.GET("user", a.LoginAPI.GetUserInfo)
gCurrent.GET("menutree", a.LoginAPI.QueryUserMenuTree)
}
pub.POST("/refresh-token", a.LoginAPI.RefreshToken)
}

gMenu := v1.Group("menus")
{
gMenu.GET("", a.MenuAPI.Query)
gMenu.GET(":id", a.MenuAPI.Get)
gMenu.POST("", a.MenuAPI.Create)
gMenu.PUT(":id", a.MenuAPI.Update)
gMenu.DELETE(":id", a.MenuAPI.Delete)
gMenu.PATCH(":id/enable", a.MenuAPI.Enable)
gMenu.PATCH(":id/disable", a.MenuAPI.Disable)
}
v1.GET("/menus.tree", a.MenuAPI.QueryTree)

gRole := v1.Group("roles")
{
gRole.GET("", a.RoleAPI.Query)
gRole.GET(":id", a.RoleAPI.Get)
gRole.POST("", a.RoleAPI.Create)
gRole.PUT(":id", a.RoleAPI.Update)
gRole.DELETE(":id", a.RoleAPI.Delete)
gRole.PATCH(":id/enable", a.RoleAPI.Enable)
gRole.PATCH(":id/disable", a.RoleAPI.Disable)
}
v1.GET("/roles.select", a.RoleAPI.QuerySelect)

gUser := v1.Group("users")
{
gUser.GET("", a.UserAPI.Query)
gUser.GET(":id", a.UserAPI.Get)
gUser.POST("", a.UserAPI.Create)
gUser.PUT(":id", a.UserAPI.Update)
gUser.DELETE(":id", a.UserAPI.Delete)
gUser.PATCH(":id/enable", a.UserAPI.Enable)
gUser.PATCH(":id/disable", a.UserAPI.Disable)
}
} // v1 end
}

api

api/user.api.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
package api

import (
"strings"

"github.com/gin-gonic/gin"
"github.com/google/wire"

"github.com/LyricTian/gin-admin/v8/internal/app/contextx"
"github.com/LyricTian/gin-admin/v8/internal/app/ginx"
"github.com/LyricTian/gin-admin/v8/internal/app/schema"
"github.com/LyricTian/gin-admin/v8/internal/app/service"
"github.com/LyricTian/gin-admin/v8/pkg/errors"
"github.com/LyricTian/gin-admin/v8/pkg/util/conv"
)

var UserSet = wire.NewSet(wire.Struct(new(UserAPI), "*"))

type UserAPI struct {
UserSrv *service.UserSrv
}

func (a *UserAPI) Query(c *gin.Context) {
ctx := c.Request.Context()
var params schema.UserQueryParam
if err := ginx.ParseQuery(c, &params); err != nil {
ginx.ResError(c, err)
return
}
if v := c.Query("roleIDs"); v != "" {
params.RoleIDs = conv.ParseStringSliceToUint64(strings.Split(v, ","))
}

params.Pagination = true
result, err := a.UserSrv.QueryShow(ctx, params)
if err != nil {
ginx.ResError(c, err)
return
}
ginx.ResPage(c, result.Data, result.PageResult)
}

func (a *UserAPI) Get(c *gin.Context) {
ctx := c.Request.Context()
item, err := a.UserSrv.Get(ctx, ginx.ParseParamID(c, "id"))
if err != nil {
ginx.ResError(c, err)
return
}
ginx.ResSuccess(c, item.CleanSecure())
}

func (a *UserAPI) Create(c *gin.Context) {
ctx := c.Request.Context()
var item schema.User
if err := ginx.ParseJSON(c, &item); err != nil {
ginx.ResError(c, err)
return
} else if item.Password == "" {
ginx.ResError(c, errors.New400Response("password not empty"))
return
}

item.Creator = contextx.FromUserID(ctx)
result, err := a.UserSrv.Create(ctx, item)
if err != nil {
ginx.ResError(c, err)
return
}
ginx.ResSuccess(c, result)
}

func (a *UserAPI) Update(c *gin.Context) {
ctx := c.Request.Context()
var item schema.User
if err := ginx.ParseJSON(c, &item); err != nil {
ginx.ResError(c, err)
return
}

err := a.UserSrv.Update(ctx, ginx.ParseParamID(c, "id"), item)
if err != nil {
ginx.ResError(c, err)
return
}
ginx.ResOK(c)
}

func (a *UserAPI) Delete(c *gin.Context) {
ctx := c.Request.Context()
err := a.UserSrv.Delete(ctx, ginx.ParseParamID(c, "id"))
if err != nil {
ginx.ResError(c, err)
return
}
ginx.ResOK(c)
}

func (a *UserAPI) Enable(c *gin.Context) {
ctx := c.Request.Context()
err := a.UserSrv.UpdateStatus(ctx, ginx.ParseParamID(c, "id"), 1)
if err != nil {
ginx.ResError(c, err)
return
}
ginx.ResOK(c)
}

func (a *UserAPI) Disable(c *gin.Context) {
ctx := c.Request.Context()
err := a.UserSrv.UpdateStatus(ctx, ginx.ParseParamID(c, "id"), 2)
if err != nil {
ginx.ResError(c, err)
return
}
ginx.ResOK(c)
}

service

service/user.srv.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package service

import (
"context"
"strconv"

"github.com/casbin/casbin/v2"
"github.com/google/wire"

"github.com/LyricTian/gin-admin/v8/internal/app/dao"
"github.com/LyricTian/gin-admin/v8/internal/app/schema"
"github.com/LyricTian/gin-admin/v8/pkg/errors"
"github.com/LyricTian/gin-admin/v8/pkg/util/hash"
"github.com/LyricTian/gin-admin/v8/pkg/util/snowflake"
)

var UserSet = wire.NewSet(wire.Struct(new(UserSrv), "*"))

type UserSrv struct {
Enforcer *casbin.SyncedEnforcer
TransRepo *dao.TransRepo
UserRepo *dao.UserRepo
UserRoleRepo *dao.UserRoleRepo
RoleRepo *dao.RoleRepo
}

func (a *UserSrv) Query(ctx context.Context, params schema.UserQueryParam, opts ...schema.UserQueryOptions) (*schema.UserQueryResult, error) {
return a.UserRepo.Query(ctx, params, opts...)
}

func (a *UserSrv) QueryShow(ctx context.Context, params schema.UserQueryParam, opts ...schema.UserQueryOptions) (*schema.UserShowQueryResult, error) {
result, err := a.UserRepo.Query(ctx, params, opts...)
if err != nil {
return nil, err
} else if result == nil {
return nil, nil
}

userRoleResult, err := a.UserRoleRepo.Query(ctx, schema.UserRoleQueryParam{
UserIDs: result.Data.ToIDs(),
})
if err != nil {
return nil, err
}

roleResult, err := a.RoleRepo.Query(ctx, schema.RoleQueryParam{
IDs: userRoleResult.Data.ToRoleIDs(),
})
if err != nil {
return nil, err
}

return result.ToShowResult(userRoleResult.Data.ToUserIDMap(), roleResult.Data.ToMap()), nil
}

func (a *UserSrv) Get(ctx context.Context, id uint64, opts ...schema.UserQueryOptions) (*schema.User, error) {
item, err := a.UserRepo.Get(ctx, id, opts...)
if err != nil {
return nil, err
} else if item == nil {
return nil, errors.ErrNotFound
}

userRoleResult, err := a.UserRoleRepo.Query(ctx, schema.UserRoleQueryParam{
UserID: id,
})
if err != nil {
return nil, err
}
item.UserRoles = userRoleResult.Data

return item, nil
}

func (a *UserSrv) Create(ctx context.Context, item schema.User) (*schema.IDResult, error) {
err := a.checkUserName(ctx, item)
if err != nil {
return nil, err
}

item.Password = hash.SHA1String(item.Password)
item.ID = snowflake.MustID()
err = a.TransRepo.Exec(ctx, func(ctx context.Context) error {
for _, urItem := range item.UserRoles {
urItem.ID = snowflake.MustID()
urItem.UserID = item.ID
err := a.UserRoleRepo.Create(ctx, *urItem)
if err != nil {
return err
}
}

return a.UserRepo.Create(ctx, item)
})
if err != nil {
return nil, err
}

for _, urItem := range item.UserRoles {
a.Enforcer.AddRoleForUser(strconv.FormatUint(urItem.UserID, 10), strconv.FormatUint(urItem.RoleID, 10))
}

return schema.NewIDResult(item.ID), nil
}

func (a *UserSrv) checkUserName(ctx context.Context, item schema.User) error {
if item.UserName == schema.GetRootUser().UserName {
return errors.New400Response("user_name has been exists")
}

result, err := a.UserRepo.Query(ctx, schema.UserQueryParam{
PaginationParam: schema.PaginationParam{OnlyCount: true},
UserName: item.UserName,
})
if err != nil {
return err
} else if result.PageResult.Total > 0 {
return errors.New400Response("user_name has been exists")
}
return nil
}

func (a *UserSrv) Update(ctx context.Context, id uint64, item schema.User) error {
oldItem, err := a.Get(ctx, id)
if err != nil {
return err
} else if oldItem == nil {
return errors.ErrNotFound
} else if oldItem.UserName != item.UserName {
err := a.checkUserName(ctx, item)
if err != nil {
return err
}
}

if item.Password != "" {
item.Password = hash.SHA1String(item.Password)
} else {
item.Password = oldItem.Password
}

item.ID = oldItem.ID
item.Creator = oldItem.Creator
item.CreatedAt = oldItem.CreatedAt

addUserRoles, delUserRoles := a.compareUserRoles(ctx, oldItem.UserRoles, item.UserRoles)
err = a.TransRepo.Exec(ctx, func(ctx context.Context) error {
for _, aitem := range addUserRoles {
aitem.ID = snowflake.MustID()
aitem.UserID = id
err := a.UserRoleRepo.Create(ctx, *aitem)
if err != nil {
return err
}
}

for _, ritem := range delUserRoles {
err := a.UserRoleRepo.Delete(ctx, ritem.ID)
if err != nil {
return err
}
}

return a.UserRepo.Update(ctx, id, item)
})
if err != nil {
return err
}

for _, aitem := range addUserRoles {
a.Enforcer.AddRoleForUser(strconv.FormatUint(id, 10), strconv.FormatUint(aitem.RoleID, 10))
}

for _, ritem := range delUserRoles {
a.Enforcer.DeleteRoleForUser(strconv.FormatUint(id, 10), strconv.FormatUint(ritem.RoleID, 10))
}

return nil
}

func (a *UserSrv) compareUserRoles(ctx context.Context, oldUserRoles, newUserRoles schema.UserRoles) (addList, delList schema.UserRoles) {
mOldUserRoles := oldUserRoles.ToMap()
mNewUserRoles := newUserRoles.ToMap()

for k, item := range mNewUserRoles {
if _, ok := mOldUserRoles[k]; ok {
delete(mOldUserRoles, k)
continue
}
addList = append(addList, item)
}

for _, item := range mOldUserRoles {
delList = append(delList, item)
}
return
}

func (a *UserSrv) Delete(ctx context.Context, id uint64) error {
oldItem, err := a.UserRepo.Get(ctx, id)
if err != nil {
return err
} else if oldItem == nil {
return errors.ErrNotFound
}

err = a.TransRepo.Exec(ctx, func(ctx context.Context) error {
err := a.UserRoleRepo.DeleteByUserID(ctx, id)
if err != nil {
return err
}

return a.UserRepo.Delete(ctx, id)
})
if err != nil {
return err
}

a.Enforcer.DeleteUser(strconv.FormatUint(id, 10))
return nil
}

func (a *UserSrv) UpdateStatus(ctx context.Context, id uint64, status int) error {
oldItem, err := a.Get(ctx, id)
if err != nil {
return err
} else if oldItem == nil {
return errors.ErrNotFound
} else if oldItem.Status == status {
return nil
}

err = a.UserRepo.UpdateStatus(ctx, id, status)
if err != nil {
return err
}

if status == 1 {
for _, uritem := range oldItem.UserRoles {
a.Enforcer.AddRoleForUser(strconv.FormatUint(id, 10), strconv.FormatUint(uritem.RoleID, 10))
}
} else {
a.Enforcer.DeleteUser(strconv.FormatUint(id, 10))
}

return nil
}

dao

dao/user/user.repo.go

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package user

import (
"context"

"github.com/google/wire"
"gorm.io/gorm"

"github.com/LyricTian/gin-admin/v8/internal/app/dao/util"
"github.com/LyricTian/gin-admin/v8/internal/app/schema"
"github.com/LyricTian/gin-admin/v8/pkg/errors"
)

var UserSet = wire.NewSet(wire.Struct(new(UserRepo), "*"))

type UserRepo struct {
DB *gorm.DB
}

func (a *UserRepo) getQueryOption(opts ...schema.UserQueryOptions) schema.UserQueryOptions {
var opt schema.UserQueryOptions
if len(opts) > 0 {
opt = opts[0]
}
return opt
}

func (a *UserRepo) Query(ctx context.Context, params schema.UserQueryParam, opts ...schema.UserQueryOptions) (*schema.UserQueryResult, error) {
opt := a.getQueryOption(opts...)

db := GetUserDB(ctx, a.DB)
if v := params.UserName; v != "" {
db = db.Where("user_name=?", v)
}
if v := params.Status; v > 0 {
db = db.Where("status=?", v)
}
if v := params.RoleIDs; len(v) > 0 {
subQuery := GetUserRoleDB(ctx, a.DB).
Select("user_id").
Where("role_id IN (?)", v)
db = db.Where("id IN (?)", subQuery)
}
if v := params.QueryValue; v != "" {
v = "%" + v + "%"
db = db.Where("user_name LIKE ? OR real_name LIKE ?", v, v)
}

if len(opt.SelectFields) > 0 {
db = db.Select(opt.SelectFields)
}

if len(opt.OrderFields) > 0 {
db = db.Order(util.ParseOrder(opt.OrderFields))
}

var list Users
pr, err := util.WrapPageQuery(ctx, db, params.PaginationParam, &list)
if err != nil {
return nil, errors.WithStack(err)
}

qr := &schema.UserQueryResult{
PageResult: pr,
Data: list.ToSchemaUsers(),
}
return qr, nil
}

func (a *UserRepo) Get(ctx context.Context, id uint64, opts ...schema.UserQueryOptions) (*schema.User, error) {
var item User
ok, err := util.FindOne(ctx, GetUserDB(ctx, a.DB).Where("id=?", id), &item)
if err != nil {
return nil, errors.WithStack(err)
} else if !ok {
return nil, nil
}

return item.ToSchemaUser(), nil
}

func (a *UserRepo) Create(ctx context.Context, item schema.User) error {
sitem := SchemaUser(item)
result := GetUserDB(ctx, a.DB).Create(sitem.ToUser())
return errors.WithStack(result.Error)
}

func (a *UserRepo) Update(ctx context.Context, id uint64, item schema.User) error {
eitem := SchemaUser(item).ToUser()
result := GetUserDB(ctx, a.DB).Where("id=?", id).Updates(eitem)
return errors.WithStack(result.Error)
}

func (a *UserRepo) Delete(ctx context.Context, id uint64) error {
result := GetUserDB(ctx, a.DB).Where("id=?", id).Delete(User{})
return errors.WithStack(result.Error)
}

func (a *UserRepo) UpdateStatus(ctx context.Context, id uint64, status int) error {
result := GetUserDB(ctx, a.DB).Where("id=?", id).Update("status", status)
return errors.WithStack(result.Error)
}

func (a *UserRepo) UpdatePassword(ctx context.Context, id uint64, password string) error {
result := GetUserDB(ctx, a.DB).Where("id=?", id).Update("password", password)
return errors.WithStack(result.Error)
}

0%