auth.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173
  1. package handler
  2. import (
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. "github.com/mojocn/base64Captcha"
  6. "github.com/mssola/user_agent"
  7. "device-manage/app/admin/models"
  8. "device-manage/common/global"
  9. jwt "device-manage/pkg/jwtauth"
  10. "device-manage/tools"
  11. "device-manage/tools/config"
  12. )
  13. var store = base64Captcha.DefaultMemStore
  14. func PayloadFunc(data interface{}) jwt.MapClaims {
  15. if v, ok := data.(map[string]interface{}); ok {
  16. u, _ := v["user"].(models.SysUser)
  17. r, _ := v["role"].(models.SysRole)
  18. return jwt.MapClaims{
  19. jwt.IdentityKey: u.UserId,
  20. jwt.RoleIdKey: r.RoleId,
  21. jwt.RoleKey: r.RoleKey,
  22. jwt.NiceKey: u.Username,
  23. jwt.DataScopeKey: r.DataScope,
  24. jwt.RoleNameKey: r.RoleName,
  25. }
  26. }
  27. return jwt.MapClaims{}
  28. }
  29. func IdentityHandler(c *gin.Context) interface{} {
  30. claims := jwt.ExtractClaims(c)
  31. return map[string]interface{}{
  32. "IdentityKey": claims["identity"],
  33. "UserName": claims["nice"],
  34. "RoleKey": claims["rolekey"],
  35. "UserId": claims["identity"],
  36. "RoleIds": claims["roleid"],
  37. "DataScope": claims["datascope"],
  38. }
  39. }
  40. // @Summary 登陆
  41. // @Description 获取token
  42. // @Description LoginHandler can be used by clients to get a jwt token.
  43. // @Description Payload needs to be json in the form of {"username": "USERNAME", "password": "PASSWORD"}.
  44. // @Description Reply will be of the form {"token": "TOKEN"}.
  45. // @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
  46. // @Description 注意:开发模式:需要注意全部字段不能为空,账号密码外可以传入0值
  47. // @Accept application/json
  48. // @Product application/json
  49. // @Param account body models.Login true "account"
  50. // @Success 200 {string} string "{"code": 200, "expire": "2019-08-07T12:45:48+08:00", "token": ".eyJleHAiOjE1NjUxNTMxNDgsImlkIjoiYWRtaW4iLCJvcmlnX2lhdCI6MTU2NTE0OTU0OH0.-zvzHvbg0A" }"
  51. // @Router /login [post]
  52. func Authenticator(c *gin.Context) (interface{}, error) {
  53. var loginVals models.Login
  54. var status = "0"
  55. var msg = "登录成功"
  56. var username = ""
  57. if err := c.ShouldBind(&loginVals); err != nil {
  58. username = loginVals.Username
  59. msg = "数据解析失败"
  60. status = "1"
  61. LoginLogToDB(c, status, msg, username)
  62. return nil, jwt.ErrMissingLoginValues
  63. }
  64. if config.ApplicationConfig.Mode != "dev" {
  65. if !store.Verify(loginVals.UUID, loginVals.Code, true) {
  66. username = loginVals.Username
  67. msg = "验证码错误"
  68. status = "1"
  69. LoginLogToDB(c, status, msg, username)
  70. return nil, jwt.ErrInvalidVerificationode
  71. }
  72. }
  73. user, role, e := loginVals.GetUser()
  74. if e == nil {
  75. username = loginVals.Username
  76. LoginLogToDB(c, status, msg, username)
  77. return map[string]interface{}{"user": user, "role": role}, nil
  78. } else {
  79. msg = "登录失败"
  80. status = "1"
  81. LoginLogToDB(c, status, msg, username)
  82. global.RequestLogger.Println(e.Error())
  83. }
  84. return nil, jwt.ErrFailedAuthentication
  85. }
  86. // Write log to database
  87. func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
  88. if config.LoggerConfig.EnabledDB {
  89. var loginlog models.LoginLog
  90. ua := user_agent.New(c.Request.UserAgent())
  91. loginlog.Ipaddr = c.ClientIP()
  92. loginlog.Username = username
  93. location := tools.GetLocation(c.ClientIP())
  94. loginlog.LoginLocation = location
  95. loginlog.LoginTime = tools.GetCurrentTime()
  96. loginlog.Status = status
  97. loginlog.Remark = c.Request.UserAgent()
  98. browserName, browserVersion := ua.Browser()
  99. loginlog.Browser = browserName + " " + browserVersion
  100. loginlog.Os = ua.OS()
  101. loginlog.Msg = msg
  102. loginlog.Platform = ua.Platform()
  103. _, _ = loginlog.Create()
  104. }
  105. }
  106. // @Summary 退出登录
  107. // @Description 获取token
  108. // LoginHandler can be used by clients to get a jwt token.
  109. // Reply will be of the form {"token": "TOKEN"}.
  110. // @Accept application/json
  111. // @Product application/json
  112. // @Success 200 {string} string "{"code": 200, "msg": "成功退出系统" }"
  113. // @Router /logout [post]
  114. // @Security Bearer
  115. func LogOut(c *gin.Context) {
  116. var loginlog models.LoginLog
  117. ua := user_agent.New(c.Request.UserAgent())
  118. loginlog.Ipaddr = c.ClientIP()
  119. location := tools.GetLocation(c.ClientIP())
  120. loginlog.LoginLocation = location
  121. loginlog.LoginTime = tools.GetCurrentTime()
  122. loginlog.Status = "0"
  123. loginlog.Remark = c.Request.UserAgent()
  124. browserName, browserVersion := ua.Browser()
  125. loginlog.Browser = browserName + " " + browserVersion
  126. loginlog.Os = ua.OS()
  127. loginlog.Platform = ua.Platform()
  128. loginlog.Username = tools.GetUserName(c)
  129. loginlog.Msg = "退出成功"
  130. loginlog.Create()
  131. c.JSON(http.StatusOK, gin.H{
  132. "code": 200,
  133. "msg": "退出成功",
  134. })
  135. }
  136. func Authorizator(data interface{}, c *gin.Context) bool {
  137. if v, ok := data.(map[string]interface{}); ok {
  138. u, _ := v["user"].(models.SysUser)
  139. r, _ := v["role"].(models.SysRole)
  140. c.Set("role", r.RoleName)
  141. c.Set("roleIds", r.RoleId)
  142. c.Set("userId", u.UserId)
  143. c.Set("userName", u.UserName)
  144. c.Set("dataScope", r.DataScope)
  145. return true
  146. }
  147. return false
  148. }
  149. func Unauthorized(c *gin.Context, code int, message string) {
  150. c.JSON(http.StatusOK, gin.H{
  151. "code": code,
  152. "msg": message,
  153. })
  154. }