forked from LyricTian/gin-admin
/
c_login.go
109 lines (92 loc) · 2.58 KB
/
c_login.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
package ctl
import (
"fmt"
"net/http"
"github.com/LyricTian/gin-admin/src/bll"
"github.com/LyricTian/gin-admin/src/logger"
"github.com/LyricTian/gin-admin/src/schema"
"github.com/LyricTian/gin-admin/src/util"
"github.com/LyricTian/gin-admin/src/web/context"
"github.com/gin-gonic/gin"
"github.com/go-session/gin-session"
)
// Login 登录管理
type Login struct {
LoginBll *bll.Login `inject:""`
}
// Login 用户登录
func (a *Login) Login(ctx *context.Context) {
var item schema.LoginParam
if err := ctx.ParseJSON(&item); err != nil {
ctx.ResBadRequest(err)
return
}
nctx := ctx.NewContext()
userInfo, err := a.LoginBll.Verify(nctx, item.UserName, item.Password)
if err != nil {
logger.LoginWithContext(nctx).Errorf("登录发生错误:%s", err.Error())
status := "error"
if err == bll.ErrInvalidPassword ||
err == bll.ErrInvalidUserName ||
err == bll.ErrUserDisable {
status = "fail"
}
ctx.ResSuccess(gin.H{"status": status})
return
}
// 更新会话
store, err := ginsession.Refresh(ctx.Context)
if err != nil {
logger.LoginWithContext(nctx).Errorf("登录发生错误:%s", err.Error())
ctx.ResSuccess(gin.H{"status": "error"})
return
}
store.Set(util.SessionKeyUserID, userInfo.RecordID)
err = store.Save()
if err != nil {
logger.LoginWithContext(nctx).Errorf("登录发生错误:%s", err.Error())
ctx.ResSuccess(gin.H{"status": "error"})
return
}
logger.LoginWithContext(nctx).Infof("登入系统")
ctx.ResOK()
}
// Logout 用户登出
func (a *Login) Logout(ctx *context.Context) {
nctx := ctx.NewContext()
userID := ctx.GetUserID()
if userID != "" {
store := ginsession.FromContext(ctx.Context)
err := store.Flush()
if err != nil {
logger.LoginWithContext(nctx).Errorf("登出发生错误:%s", err.Error())
ctx.ResInternalServerError(err)
return
}
logger.LoginWithContext(nctx).Infof("登出系统")
}
ctx.ResOK()
}
// GetCurrentUserInfo 获取当前用户信息
func (a *Login) GetCurrentUserInfo(ctx *context.Context) {
userID := ctx.GetUserID()
info, err := a.LoginBll.GetCurrentUserInfo(ctx.NewContext(), userID)
if err != nil {
ctx.ResInternalServerError(err)
return
}
ctx.ResSuccess(info)
}
// QueryCurrentUserMenus 查询当前用户菜单
func (a *Login) QueryCurrentUserMenus(ctx *context.Context) {
userID := ctx.GetUserID()
menus, err := a.LoginBll.QueryCurrentUserMenus(ctx.NewContext(), userID)
if err != nil {
ctx.ResInternalServerError(err)
return
} else if len(menus) == 0 {
ctx.ResError(fmt.Errorf("用户未授权"), http.StatusUnauthorized, 9998)
return
}
ctx.ResList(menus)
}