auth.go 7.7 KB

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