auth.go 8.0 KB

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