auth.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. package handler
  2. import (
  3. "errors"
  4. "fmt"
  5. "gas-cylinder-api/app/admin/model"
  6. "gas-cylinder-api/common"
  7. "gas-cylinder-api/common/global"
  8. "github.com/gin-gonic/gin"
  9. "github.com/mssola/user_agent"
  10. "gogs.baozhida.cn/zoie/OAuth-core/api"
  11. "gogs.baozhida.cn/zoie/OAuth-core/pkg"
  12. jwt "gogs.baozhida.cn/zoie/OAuth-core/pkg/jwtauth"
  13. "gogs.baozhida.cn/zoie/OAuth-core/pkg/jwtauth/user"
  14. "gogs.baozhida.cn/zoie/OAuth-core/pkg/response"
  15. "gogs.baozhida.cn/zoie/OAuth-core/sdk"
  16. "gogs.baozhida.cn/zoie/OAuth-core/sdk/config"
  17. "gorm.io/gorm"
  18. "net/http"
  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. d, _ := v["dept"].(SysDept)
  25. single, _ := v["single"].(bool)
  26. return jwt.MapClaims{
  27. jwt.UUIDKey: u.Uuid,
  28. jwt.IdentityKey: u.Id,
  29. jwt.RoleIdKey: r.Id,
  30. jwt.RoleKey: r.RoleKey,
  31. jwt.UserNameKey: u.Username,
  32. jwt.DataScopeKey: r.DataScope,
  33. jwt.RoleNameKey: r.Name,
  34. jwt.SingleKey: single,
  35. jwt.DeptIdKey: u.DeptId,
  36. jwt.DeptNameKey: d.DeptName,
  37. }
  38. }
  39. return jwt.MapClaims{}
  40. }
  41. func IdentityHandler(c *gin.Context) interface{} {
  42. claims := jwt.ExtractClaims(c)
  43. return map[string]interface{}{
  44. "UUIDKey": claims["uuid"],
  45. "IdentityKey": claims["identity"],
  46. "UserName": claims["username"],
  47. "RoleName": claims["roleName"],
  48. "RoleKey": claims["roleKey"],
  49. "Id": claims["identity"],
  50. "RoleId": claims["roleId"],
  51. "DataScope": claims["dataScope"],
  52. "single": claims["single"],
  53. "DeptId": claims["deptId"],
  54. "Name": claims["deptName"],
  55. }
  56. }
  57. // Authenticator 登录认证
  58. // Update 登录认证
  59. // @Summary 登录认证
  60. // @Description 登录认证
  61. // @Tags 登录
  62. // @Accept application/json
  63. // @Product application/json
  64. // @Param data body Login true "body"
  65. // @Success 200 {object} response.Response "{"code": 200, "data": [...]}"
  66. // @Router /api/login [post]
  67. func Authenticator(c *gin.Context) (interface{}, error) {
  68. log := api.GetRequestLogger(c)
  69. ormDB, err := pkg.GetOrm(c)
  70. if err != nil {
  71. log.Errorf("get db error, %s", err.Error())
  72. response.Error(c, 500, err, "数据库连接获取失败")
  73. return nil, jwt.ErrFailedAuthentication
  74. }
  75. var loginVals Login
  76. var status = "2"
  77. var msg = "登录成功"
  78. var username = ""
  79. defer func() {
  80. LoginLogToDB(c, status, msg, username)
  81. }()
  82. if err = c.ShouldBind(&loginVals); err != nil {
  83. username = loginVals.Username
  84. msg = "数据解析失败"
  85. status = "1"
  86. return nil, jwt.ErrFailedAuthentication
  87. }
  88. //if config.ApplicationConfig.Mode != "dev" {
  89. // if !captcha.Verify(loginVals.UUID, loginVals.Code, true) {
  90. // username = loginVals.Username
  91. // msg = "验证码错误"
  92. // status = "1"
  93. //
  94. // return nil, jwt.ErrInvalidVerificationCode
  95. // }
  96. //}
  97. var u SysUser
  98. var role SysRole
  99. var dept SysDept
  100. var e error
  101. if loginVals.Type == 1 {
  102. u, role, dept, e = loginVals.GetUser(ormDB)
  103. if e != nil {
  104. msg = e.Error()
  105. status = "1"
  106. log.Warnf("%s login failed!", username)
  107. return nil, jwt.ErrFailedAuthentication
  108. }
  109. }
  110. if loginVals.Type == 2 {
  111. u, role, dept, e = loginVals.GetUserByCode(ormDB)
  112. if e != nil {
  113. msg = e.Error()
  114. status = "1"
  115. log.Warnf("%s login failed!", username)
  116. return nil, jwt.ErrFailedSmsVerifyCode
  117. }
  118. }
  119. username = loginVals.Username
  120. single, err := GetSingleLogin(c)
  121. if err != nil {
  122. return nil, err
  123. }
  124. err = sdk.Runtime.GetCacheAdapter().Del(model.GetEnterDeptCacheKey(u.Id))
  125. err = sdk.Runtime.GetCacheAdapter().Del(model.GetEnterDeptNameCacheKey(u.Id))
  126. return map[string]interface{}{"user": u, "role": role, "dept": dept, "single": single, "mobile": loginVals.Mobile}, nil
  127. }
  128. // LoginLogToDB Write log to database
  129. func LoginLogToDB(c *gin.Context, status string, msg string, username string) {
  130. if !config.LoggerConfig.EnabledDB {
  131. return
  132. }
  133. log := api.GetRequestLogger(c)
  134. l := make(map[string]interface{})
  135. ua := user_agent.New(c.Request.UserAgent())
  136. l["ipaddr"] = common.GetClientIP(c)
  137. l["loginTime"] = pkg.GetCurrentTime()
  138. l["status"] = status
  139. l["remark"] = c.Request.UserAgent()
  140. browserName, browserVersion := ua.Browser()
  141. l["browser"] = browserName + " " + browserVersion
  142. l["os"] = ua.OS()
  143. l["platform"] = ua.Platform()
  144. l["username"] = username
  145. l["msg"] = msg
  146. q := sdk.Runtime.GetMemoryQueue(c.Request.Host)
  147. message, err := sdk.Runtime.GetStreamMessage("", global.LoginLog, l)
  148. if err != nil {
  149. log.Errorf("GetStreamMessage error, %s", err.Error())
  150. //日志报错错误,不中断请求
  151. } else {
  152. err = q.Append(message)
  153. if err != nil {
  154. log.Errorf("Append message error, %s", err.Error())
  155. }
  156. }
  157. }
  158. // LogOut 退出登录
  159. // @Summary 退出登录
  160. // @Description 退出登录
  161. // @Description LoginHandler can be used by clients to get a jwt token.
  162. // @Description Reply will be of the form {"token": "TOKEN"}.
  163. // @Tags 登录
  164. // @Accept application/json
  165. // @Product application/json
  166. // @Success 200 {string} string "{"code": 200, "msg": "成功退出系统"}"
  167. // @Router /logout [post]
  168. // @Security Bearer
  169. func LogOut(c *gin.Context) {
  170. LoginLogToDB(c, "2", "退出成功", user.GetUserName(c))
  171. c.JSON(http.StatusOK, gin.H{
  172. "code": 200,
  173. "msg": "退出成功",
  174. })
  175. }
  176. func Authorizator(data interface{}, c *gin.Context) bool {
  177. if v, ok := data.(map[string]interface{}); ok {
  178. u, _ := v["user"].(model.SysUser)
  179. r, _ := v["role"].(model.SysRole)
  180. d, _ := v["dept"].(model.SysDept)
  181. single, _ := v["single"].(bool)
  182. c.Set("uuid", u.Uuid)
  183. c.Set("identity", u.Id)
  184. c.Set("userName", u.Username)
  185. c.Set("roleName", r.Name)
  186. c.Set("roleKey", r.RoleKey)
  187. c.Set("userId", u.Id)
  188. c.Set("roleId", r.Id)
  189. c.Set("single", single)
  190. c.Set("dataScope", r.DataScope)
  191. c.Set("deptId", u.DeptId)
  192. c.Set("deptName", d.Name)
  193. return true
  194. }
  195. return false
  196. }
  197. func Unauthorized(c *gin.Context, code int, message string) {
  198. c.JSON(http.StatusOK, gin.H{
  199. "code": code,
  200. "msg": message,
  201. })
  202. }
  203. // 保存token到redis
  204. func SaveNewestToken(c *gin.Context, userId int64, token string, expire int64) error {
  205. key := fmt.Sprintf("%s:%d", "bzd.oauth.token", userId)
  206. return sdk.Runtime.GetCacheAdapter().Set(key, token, int(expire))
  207. }
  208. // redis从redis获取token
  209. func GetNewestToken(c *gin.Context, userId int64) (string, error) {
  210. key := fmt.Sprintf("%s:%d", "bzd.oauth.token", userId)
  211. return sdk.Runtime.GetCacheAdapter().Get(key)
  212. }
  213. func GetSingleLogin(c *gin.Context) (bool, error) {
  214. log := api.GetRequestLogger(c)
  215. ormDB, err := pkg.GetOrm(c)
  216. if err != nil {
  217. log.Errorf("get db error, %s", err.Error())
  218. response.Error(c, 500, err, "数据库连接获取失败")
  219. return false, err
  220. }
  221. //result := map[string]interface{}{}
  222. var result string
  223. err = ormDB.Table("sys_config").Select("config_value").Where("config_key = ? ", "sys_single_login").Scan(&result).Error
  224. if err != nil {
  225. log.Errorf("get sys_config error, %s", err.Error())
  226. if errors.Is(err, gorm.ErrRecordNotFound) {
  227. // 默认为非单一登录
  228. return false, nil
  229. }
  230. return false, err
  231. }
  232. if result == "是" {
  233. return true, nil
  234. }
  235. return false, nil
  236. }