auth.go 5.5 KB

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