user.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259
  1. // Copyright 2019 github.com. All rights reserved.
  2. // Use of this source code is governed by github.com.
  3. package v1
  4. import (
  5. "cp-system-management-gateway/consts"
  6. "cp-system-management-gateway/utils"
  7. "fmt"
  8. "github.com/tidwall/gjson"
  9. "net/http"
  10. "cp-system-management-gateway/errors"
  11. param_v1 "cp-system-management-gateway/param/v1"
  12. "cp-system-management-gateway/pb"
  13. "cp-system-management-gateway/pb/v1"
  14. "time"
  15. "github.com/dgrijalva/jwt-go"
  16. "github.com/jaryhe/gopkgs/logger"
  17. "github.com/jaryhe/gopkgs/tasker/httptasker"
  18. "github.com/jaryhe/gopkgs/util"
  19. "cp-system-management-gateway/parser"
  20. "github.com/gin-gonic/gin"
  21. "github.com/jaryhe/gopkgs/jwtwrapper"
  22. "go.uber.org/zap"
  23. )
  24. // 登录
  25. // @Summary 登录
  26. // @Description 登录
  27. // @Tags 用户
  28. // @Accept json
  29. // @Produce json
  30. // @Param body body v1.LoginBody true "登录信息"
  31. // @Success 200 {object} v1.LoginResponse
  32. // @Failure 500 {object} base.HTTPError
  33. // @Router /api/v1/user/login [post]
  34. func (c *Controller) Login(ctx *gin.Context) {
  35. // 解析参数
  36. req := &param_v1.LoginRequest{}
  37. parseParamTask := func() error {
  38. err := util.ShouldBind(ctx, &req.Header, nil, nil, &req.LoginBody)
  39. if err != nil {
  40. logger.Error("func",
  41. zap.String("call", "util.ShouldBind"),
  42. zap.String("error", err.Error()))
  43. return errors.ParamsError
  44. }
  45. return nil
  46. }
  47. // 业务处理
  48. handleServiceTask := func() error {
  49. // 响应数据
  50. resp := param_v1.LoginResponse{}
  51. rpcReq := &v1.LoginRequest{
  52. Username: req.User,
  53. Password: req.Password,
  54. }
  55. rpcRsp, err := pb.System.Login(ctx, rpcReq)
  56. if err != nil {
  57. s, _ := json.MarshalToString(req)
  58. logger.Error("func",
  59. zap.String("call", "pb.Project.Login"),
  60. zap.String("params", s),
  61. zap.String("error", err.Error()))
  62. return errors.ErrorTransForm(err)
  63. }
  64. subject := map[string]interface{}{
  65. "user_name": req.User,
  66. }
  67. str, _ := json.MarshalToString(subject)
  68. // 生成token
  69. token, err := jwtwrapper.GenToken(fmt.Sprintf("%d", rpcRsp.Uid), parser.Conf.Jwt.Issuer, str,
  70. time.Duration(parser.Conf.Jwt.Seconds)*time.Second)
  71. if err != nil {
  72. logger.Error("func",
  73. zap.String("call", "util.GenJwtToken"),
  74. zap.String("args", fmt.Sprintf("%d", rpcRsp.Uid)),
  75. zap.String("error", err.Error()))
  76. return errors.SystemError
  77. }
  78. if err != nil {
  79. logger.Error("func",
  80. zap.String("call", "util.GenJwtToken"),
  81. zap.String("args", fmt.Sprintf("%d", rpcRsp.Uid)),
  82. zap.String("error", err.Error()))
  83. return errors.SystemError
  84. }
  85. resp.Data.Uid = rpcRsp.Uid
  86. resp.Data.Token = token
  87. resp.Data.User = req.User
  88. ctx.JSON(http.StatusOK, resp)
  89. return nil
  90. }
  91. // 执行任务
  92. httptasker.Exec(ctx, parseParamTask, handleServiceTask)
  93. }
  94. // token
  95. // @Summary 刷新token
  96. // @Description 刷新token
  97. // @Tags 用户
  98. // @Accept json
  99. // @Produce json
  100. // @Param token header string true "token"
  101. // @Success 200 {object} v1.TokenResponse
  102. // @Failure 500 {object} base.HTTPError
  103. // @Router /api/v1/token_refresh [put]
  104. func (c *Controller) TokenRefresh(ctx *gin.Context) {
  105. // 解析参数
  106. req := &param_v1.TokenRequest{}
  107. parseParamTask := func() error {
  108. err := util.ShouldBind(ctx, &req.Header, nil, nil, nil)
  109. if err != nil {
  110. logger.Error("func",
  111. zap.String("call", "util.ShouldBind"),
  112. zap.String("error", err.Error()))
  113. return errors.ParamsError
  114. }
  115. return nil
  116. }
  117. // 业务处理
  118. handleServiceTask := func() error {
  119. tokenObj, err := jwtwrapper.ParseToken(req.Token)
  120. if tokenObj == nil {
  121. return errors.TokenFailedError
  122. }
  123. if err != nil {
  124. switch err.(*jwt.ValidationError).Errors {
  125. case jwt.ValidationErrorExpired:
  126. return errors.TokenFailedError
  127. default:
  128. return errors.TokenFailedError
  129. }
  130. }
  131. uid := tokenObj.Id
  132. subject := tokenObj.Subject
  133. remberPass := gjson.GetBytes([]byte(subject), "rember_password").Bool()
  134. // 生成token
  135. token, err := jwtwrapper.GenToken(uid, parser.Conf.Jwt.Issuer, subject,
  136. time.Duration(parser.Conf.Jwt.Seconds)*time.Second)
  137. if err != nil {
  138. logger.Error("func",
  139. zap.String("call", "util.GenJwtToken"),
  140. zap.String("args", fmt.Sprintf("%s", uid)),
  141. zap.String("error", err.Error()))
  142. return errors.SystemError
  143. }
  144. refreshTokenTime := time.Duration(24*60*60)*time.Second
  145. if remberPass {
  146. refreshTokenTime = time.Duration(7*24*60*60)*time.Second
  147. }
  148. refreshToken, err := jwtwrapper.GenToken(uid, parser.Conf.Jwt.Issuer, subject,
  149. refreshTokenTime)
  150. if err != nil {
  151. logger.Error("func",
  152. zap.String("call", "util.GenJwtToken"),
  153. zap.String("args", fmt.Sprintf("%s", uid)),
  154. zap.String("error", err.Error()))
  155. return errors.SystemError
  156. }
  157. resp := param_v1.TokenResponse{}
  158. resp.Data = token
  159. resp.RefreshToken = refreshToken
  160. ctx.JSON(http.StatusOK, resp)
  161. return nil
  162. }
  163. // 执行任务
  164. httptasker.Exec(ctx, parseParamTask, handleServiceTask)
  165. }
  166. //
  167. // @Summary 修改系统账号密码
  168. // @Description 修改系统账号密码
  169. // @Tags 用户
  170. // @Accept json
  171. // @Produce json
  172. // @Param token header string true "token"
  173. // @Param body body v1.ResetPasswdBody true " "
  174. // @Success 200 {object} v1.ResetePasswdResponse
  175. // @Failure 500 {object} base.HTTPError
  176. // @Router /api/v1/user/password [put]
  177. func (c *Controller) ResetePasswd(ctx *gin.Context) {
  178. // 解析参数
  179. req := &param_v1.ResetePasswdRequest{}
  180. parseParamTask := func() error {
  181. err := util.ShouldBind(ctx, &req.Header, nil, nil, &req.ResetPasswdBody)
  182. if err != nil {
  183. logger.Error("func",
  184. zap.String("call", "util.ShouldBind"),
  185. zap.String("error", err.Error()))
  186. return errors.ParamsError
  187. }
  188. return nil
  189. }
  190. // 业务处理
  191. handleServiceTask := func() error {
  192. loginUid, userName, _ := utils.GetJwtIdFromCtx(ctx)
  193. // 响应数据
  194. resp := param_v1.ResetePasswdResponse{}
  195. rpcReq := &v1.ChangePasswordRequest{
  196. Uid: loginUid,
  197. Password:req.New,
  198. Old:req.Old,
  199. }
  200. _, err := pb.System.ChangePassword(ctx, rpcReq)
  201. if err != nil {
  202. s, _ := json.MarshalToString(req)
  203. logger.Error("func",
  204. zap.String("call", "pb.System.ChangePassword"),
  205. zap.String("params", s),
  206. zap.String("error", err.Error()))
  207. return errors.ErrorTransForm(err)
  208. }
  209. ctx.JSON(http.StatusOK, resp)
  210. req.New = "******"
  211. req.Old = "******"
  212. logReq := OperationLogRequest{
  213. Module:consts.OperationModuleOrganization,
  214. Action:consts.OperationActionOrganizationUserResetPassword,
  215. Origin:nil,
  216. Target:req.ResetPasswdBody,
  217. UserName:userName,
  218. Uid:loginUid,
  219. }
  220. OperationLogAdd(&logReq)
  221. return nil
  222. }
  223. // 执行任务
  224. httptasker.Exec(ctx, parseParamTask, handleServiceTask)
  225. }