auth.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package handler
  2. import (
  3. "fmt"
  4. "net/http"
  5. "git.cestong.com.cn/cecf/config-center-server/app/admin/models"
  6. "git.cestong.com.cn/cecf/config-center-server/common"
  7. gaConfig "git.cestong.com.cn/cecf/config-center-server/config"
  8. "github.com/gin-gonic/gin"
  9. "github.com/go-admin-team/go-admin-core/sdk"
  10. "github.com/go-admin-team/go-admin-core/sdk/api"
  11. "github.com/go-admin-team/go-admin-core/sdk/config"
  12. "github.com/go-admin-team/go-admin-core/sdk/pkg"
  13. "github.com/go-admin-team/go-admin-core/sdk/pkg/captcha"
  14. jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
  15. "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth/user"
  16. "github.com/go-admin-team/go-admin-core/sdk/pkg/response"
  17. "github.com/mssola/user_agent"
  18. "git.cestong.com.cn/cecf/config-center-server/common/global"
  19. )
  20. func PayloadFunc(data interface{}) jwt.MapClaims {
  21. if v, ok := data.(map[string]interface{}); ok {
  22. u, _ := v["user"].(SysUser)
  23. r, _ := v["role"].(SysRole)
  24. return jwt.MapClaims{
  25. jwt.IdentityKey: u.UserId,
  26. jwt.RoleIdKey: r.RoleId,
  27. jwt.RoleKey: r.RoleKey,
  28. jwt.NiceKey: u.Username,
  29. jwt.DataScopeKey: r.DataScope,
  30. jwt.RoleNameKey: r.RoleName,
  31. }
  32. }
  33. return jwt.MapClaims{}
  34. }
  35. func IdentityHandler(c *gin.Context) interface{} {
  36. claims := jwt.ExtractClaims(c)
  37. return map[string]interface{}{
  38. "IdentityKey": claims["identity"],
  39. "UserName": claims["nice"],
  40. "RoleKey": claims["rolekey"],
  41. "UserId": claims["identity"],
  42. "RoleIds": claims["roleid"],
  43. "DataScope": claims["datascope"],
  44. }
  45. }
  46. // Authenticator 获取token
  47. // @Summary 登陆
  48. // @Description 获取token
  49. // @Description LoginHandler can be used by clients to get a jwt token.
  50. // @Description Payload needs to be json in the form of {"username": "USERNAME", "password": "PASSWORD"}.
  51. // @Description Reply will be of the form {"token": "TOKEN"}.
  52. // @Description dev mode:It should be noted that all fields cannot be empty, and a value of 0 can be passed in addition to the account password
  53. // @Description 注意:开发模式:需要注意全部字段不能为空,账号密码外可以传入0值
  54. // @Tags 登陆
  55. // @Accept application/json
  56. // @Product application/json
  57. // @Param account body Login true "account"
  58. // @Success 200 {string} string "{"code": 200, "expire": "2019-08-07T12:45:48+08:00", "token": ".eyJleHAiOjE1NjUxNTMxNDgsImlkIjoiYWRtaW4iLCJvcmlnX2lhdCI6MTU2NTE0OTU0OH0.-zvzHvbg0A" }"
  59. // @Router /api/v1/login [post]
  60. func Authenticator(c *gin.Context) (interface{}, error) {
  61. log := api.GetRequestLogger(c)
  62. db, err := pkg.GetOrm(c)
  63. if err != nil {
  64. log.Errorf("get db error, %s", err.Error())
  65. response.Error(c, 500, err, "数据库连接获取失败")
  66. return nil, jwt.ErrFailedAuthentication
  67. }
  68. var loginVals Login
  69. var status = "2"
  70. var msg = "登录成功"
  71. var username = ""
  72. defer func() {
  73. LoginLogToDB(c, status, msg, username)
  74. }()
  75. if err = c.ShouldBind(&loginVals); err != nil {
  76. username = loginVals.Username
  77. msg = "数据解析失败"
  78. status = "1"
  79. return nil, jwt.ErrMissingLoginValues
  80. }
  81. if config.ApplicationConfig.Mode != "dev" {
  82. if !captcha.Verify(loginVals.UUID, loginVals.Code, true) {
  83. username = loginVals.Username
  84. msg = "验证码错误"
  85. status = "1"
  86. return nil, jwt.ErrInvalidVerificationode
  87. }
  88. }
  89. user, role, e := loginVals.GetUser(db)
  90. if e == nil {
  91. username = loginVals.Username
  92. return map[string]interface{}{"user": user, "role": role}, nil
  93. } else {
  94. msg = "登录失败"
  95. status = "1"
  96. log.Warnf("%s login failed!", loginVals.Username)
  97. }
  98. return nil, jwt.ErrFailedAuthentication
  99. }
  100. // LoginLogToDB Write log to database
  101. func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
  102. if !config.LoggerConfig.EnabledDB {
  103. return
  104. }
  105. log := api.GetRequestLogger(c)
  106. l := make(map[string]interface{})
  107. ua := user_agent.New(c.Request.UserAgent())
  108. l["ipaddr"] = common.GetClientIP(c)
  109. fmt.Println("gaConfig.ExtConfig.AMap.Key", gaConfig.ExtConfig.AMap.Key)
  110. l["loginLocation"] = pkg.GetLocation(common.GetClientIP(c), gaConfig.ExtConfig.AMap.Key)
  111. l["loginTime"] = pkg.GetCurrentTime()
  112. l["status"] = status
  113. l["remark"] = c.Request.UserAgent()
  114. browserName, browserVersion := ua.Browser()
  115. l["browser"] = browserName + " " + browserVersion
  116. l["os"] = ua.OS()
  117. l["platform"] = ua.Platform()
  118. l["username"] = username
  119. l["msg"] = msg
  120. q := sdk.Runtime.GetMemoryQueue(c.Request.Host)
  121. message, err := sdk.Runtime.GetStreamMessage("", global.LoginLog, l)
  122. if err != nil {
  123. log.Errorf("GetStreamMessage error, %s", err.Error())
  124. //日志报错错误,不中断请求
  125. } else {
  126. err = q.Append(message)
  127. if err != nil {
  128. log.Errorf("Append message error, %s", err.Error())
  129. }
  130. }
  131. }
  132. // LogOut
  133. // @Summary 退出登录
  134. // @Description 获取token
  135. // LoginHandler can be used by clients to get a jwt token.
  136. // Reply will be of the form {"token": "TOKEN"}.
  137. // @Accept application/json
  138. // @Product application/json
  139. // @Success 200 {string} string "{"code": 200, "msg": "成功退出系统" }"
  140. // @Router /logout [post]
  141. // @Security Bearer
  142. func LogOut(c *gin.Context) {
  143. LoginLogToDB(c, "2", "退出成功", user.GetUserName(c))
  144. c.JSON(http.StatusOK, gin.H{
  145. "code": 200,
  146. "msg": "退出成功",
  147. })
  148. }
  149. func Authorizator(data interface{}, c *gin.Context) bool {
  150. if v, ok := data.(map[string]interface{}); ok {
  151. u, _ := v["user"].(models.SysUser)
  152. r, _ := v["role"].(models.SysRole)
  153. c.Set("role", r.RoleName)
  154. c.Set("roleIds", r.RoleId)
  155. c.Set("userId", u.UserId)
  156. c.Set("userName", u.Username)
  157. c.Set("dataScope", r.DataScope)
  158. return true
  159. }
  160. return false
  161. }
  162. func Unauthorized(c *gin.Context, code int, message string) {
  163. c.JSON(http.StatusOK, gin.H{
  164. "code": code,
  165. "msg": message,
  166. })
  167. }