auth.go 8.1 KB

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