user.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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-organization-management-gateway/consts"
  6. "cp-organization-management-gateway/utils"
  7. "fmt"
  8. "github.com/tidwall/gjson"
  9. "net/http"
  10. "cp-organization-management-gateway/errors"
  11. param_v1 "cp-organization-management-gateway/param/v1"
  12. "cp-organization-management-gateway/pb"
  13. "cp-organization-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-organization-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.ManagementLoginRequest{
  52. Username: req.User,
  53. Password: req.Password,
  54. Key:req.Key,
  55. }
  56. rpcRsp, err := pb.Organization.ManagementLogin(ctx, rpcReq)
  57. if err != nil {
  58. s, _ := json.MarshalToString(req)
  59. logger.Error("func",
  60. zap.String("call", "pb.Organization.ManagementLogin"),
  61. zap.String("params", s),
  62. zap.String("error", err.Error()))
  63. return errors.ErrorTransForm(err)
  64. }
  65. subject := map[string]interface{}{
  66. "user_name": req.User,
  67. "end_time": rpcRsp.EndTime,
  68. "organization_code":rpcRsp.OrganizationCode,
  69. "permissions":rpcRsp.Permissions,
  70. "is_super":rpcRsp.IsSuper,
  71. }
  72. str, _ := json.MarshalToString(subject)
  73. // 生成token
  74. token, err := jwtwrapper.GenToken(fmt.Sprintf("%d", rpcRsp.Uid), parser.Conf.Jwt.Issuer, str,
  75. time.Duration(parser.Conf.Jwt.Seconds)*time.Second)
  76. if err != nil {
  77. logger.Error("func",
  78. zap.String("call", "util.GenJwtToken"),
  79. zap.String("args", fmt.Sprintf("%d", rpcRsp.Uid)),
  80. zap.String("error", err.Error()))
  81. return errors.SystemError
  82. }
  83. refreshTokenTime := time.Duration(24*60*60)*time.Second
  84. refreshToken, err := jwtwrapper.GenToken(fmt.Sprintf("%d", rpcRsp.Uid), parser.Conf.Jwt.Issuer, str,
  85. refreshTokenTime)
  86. if err != nil {
  87. logger.Error("func",
  88. zap.String("call", "util.GenJwtToken"),
  89. zap.String("args", fmt.Sprintf("%d", rpcRsp.Uid)),
  90. zap.String("error", err.Error()))
  91. return errors.SystemError
  92. }
  93. resp.Data.Uid = rpcRsp.Uid
  94. resp.Data.Token = token
  95. resp.Data.User = req.User
  96. resp.Data.Organization = rpcRsp.OrganizationName
  97. resp.Data.RefreshToken = refreshToken
  98. ctx.JSON(http.StatusOK, resp)
  99. return nil
  100. }
  101. // 执行任务
  102. httptasker.Exec(ctx, parseParamTask, handleServiceTask)
  103. }
  104. // token
  105. // @Summary 刷新token
  106. // @Description 刷新token
  107. // @Tags 用户
  108. // @Accept json
  109. // @Produce json
  110. // @Param token header string true "token"
  111. // @Success 200 {object} v1.TokenResponse
  112. // @Failure 500 {object} base.HTTPError
  113. // @Router /api/v1/token_refresh [put]
  114. func (c *Controller) TokenRefresh(ctx *gin.Context) {
  115. // 解析参数
  116. req := &param_v1.TokenRequest{}
  117. parseParamTask := func() error {
  118. err := util.ShouldBind(ctx, &req.Header, nil, nil, nil)
  119. if err != nil {
  120. logger.Error("func",
  121. zap.String("call", "util.ShouldBind"),
  122. zap.String("error", err.Error()))
  123. return errors.ParamsError
  124. }
  125. return nil
  126. }
  127. // 业务处理
  128. handleServiceTask := func() error {
  129. tokenObj, err := jwtwrapper.ParseToken(req.Token)
  130. if tokenObj == nil {
  131. return errors.TokenFailedError
  132. }
  133. if err != nil {
  134. switch err.(*jwt.ValidationError).Errors {
  135. case jwt.ValidationErrorExpired:
  136. return errors.TokenFailedError
  137. default:
  138. return errors.TokenFailedError
  139. }
  140. }
  141. uid := tokenObj.Id
  142. subject := tokenObj.Subject
  143. remberPass := gjson.GetBytes([]byte(subject), "rember_password").Bool()
  144. // 生成token
  145. token, err := jwtwrapper.GenToken(uid, parser.Conf.Jwt.Issuer, subject,
  146. time.Duration(parser.Conf.Jwt.Seconds)*time.Second)
  147. if err != nil {
  148. logger.Error("func",
  149. zap.String("call", "util.GenJwtToken"),
  150. zap.String("args", fmt.Sprintf("%s", uid)),
  151. zap.String("error", err.Error()))
  152. return errors.SystemError
  153. }
  154. refreshTokenTime := time.Duration(24*60*60)*time.Second
  155. if remberPass {
  156. refreshTokenTime = time.Duration(7*24*60*60)*time.Second
  157. }
  158. refreshToken, err := jwtwrapper.GenToken(uid, parser.Conf.Jwt.Issuer, subject,
  159. refreshTokenTime)
  160. if err != nil {
  161. logger.Error("func",
  162. zap.String("call", "util.GenJwtToken"),
  163. zap.String("args", fmt.Sprintf("%s", uid)),
  164. zap.String("error", err.Error()))
  165. return errors.SystemError
  166. }
  167. resp := param_v1.TokenResponse{}
  168. resp.Data = token
  169. resp.RefreshToken = refreshToken
  170. ctx.JSON(http.StatusOK, resp)
  171. return nil
  172. }
  173. // 执行任务
  174. httptasker.Exec(ctx, parseParamTask, handleServiceTask)
  175. }
  176. //
  177. // @Summary 创建用户
  178. // @Description 创建用户
  179. // @Tags 系统管理-用户管理
  180. // @Accept json
  181. // @Produce json
  182. // @Param token header string true "token"
  183. // @Param body body v1.UserCreateBody true " "
  184. // @Success 200 {object} v1.UserCreateResponse
  185. // @Failure 500 {object} base.HTTPError
  186. // @Router /api/v1/system/user [post]
  187. func (c *Controller) UserCreate(ctx *gin.Context) {
  188. // 解析参数
  189. req := &param_v1.UserCreateRequest{}
  190. parseParamTask := func() error {
  191. err := util.ShouldBind(ctx, &req.Header, nil, nil, &req.UserCreateBody)
  192. if err != nil {
  193. logger.Error("func",
  194. zap.String("call", "util.ShouldBind"),
  195. zap.String("error", err.Error()))
  196. return errors.ParamsError
  197. }
  198. return nil
  199. }
  200. // 业务处理
  201. handleServiceTask := func() error {
  202. // 响应数据
  203. tokenInfo, err := utils.GetTokeInfo(ctx)
  204. if err != nil {
  205. return err
  206. }
  207. resp := param_v1.UserCreateResponse{}
  208. rpcReq := &v1.CreateManagementUserRequest{
  209. OrganizationCode:tokenInfo.OrganizationCode,
  210. Uid:tokenInfo.Uid,
  211. Name:req.Name,
  212. Username:req.Username,
  213. Zones:req.Zones,
  214. Email:req.Email,
  215. Phone:req.Phone,
  216. Password:req.Password,
  217. GroupId:req.GroupId,
  218. }
  219. rpcRsp, err := pb.Organization.CreateManagementUser(ctx, rpcReq)
  220. if err != nil {
  221. s, _ := json.MarshalToString(req)
  222. logger.Error("func",
  223. zap.String("call", "pb.Organization.CreateManagementUser"),
  224. zap.String("params", s),
  225. zap.String("error", err.Error()))
  226. return errors.ErrorTransForm(err)
  227. }
  228. resp.Data = *rpcRsp
  229. ctx.JSON(http.StatusOK, resp)
  230. logReq := OperationLogRequest{
  231. Module:consts.OperationModuleUser,
  232. Action:consts.OperationActionUserAdd,
  233. Origin:nil,
  234. Target:req.UserCreateBody,
  235. UserName:tokenInfo.Username,
  236. Uid:tokenInfo.Uid,
  237. OrganizationCode:tokenInfo.OrganizationCode,
  238. }
  239. OperationLogAdd(&logReq)
  240. return nil
  241. }
  242. // 执行任务
  243. httptasker.Exec(ctx, parseParamTask, handleServiceTask)
  244. }
  245. //
  246. // @Summary 修改用户
  247. // @Description 修改用户
  248. // @Tags 系统管理-用户管理
  249. // @Accept json
  250. // @Produce json
  251. // @Param token header string true "token"
  252. // @Param body body v1.UserUpdateBody true " "
  253. // @Success 200 {object} v1.UserUpdateResponse
  254. // @Failure 500 {object} base.HTTPError
  255. // @Router /api/v1/system/user [put]
  256. func (c *Controller) UserUpdate(ctx *gin.Context) {
  257. // 解析参数
  258. req := &param_v1.UserUpdateRequest{}
  259. parseParamTask := func() error {
  260. err := util.ShouldBind(ctx, &req.Header, nil, nil, &req.UserUpdateBody)
  261. if err != nil {
  262. logger.Error("func",
  263. zap.String("call", "util.ShouldBind"),
  264. zap.String("error", err.Error()))
  265. return errors.ParamsError
  266. }
  267. return nil
  268. }
  269. // 业务处理
  270. handleServiceTask := func() error {
  271. // 响应数据
  272. tokenInfo, err := utils.GetTokeInfo(ctx)
  273. if err != nil {
  274. return err
  275. }
  276. resp := param_v1.UserUpdateResponse{}
  277. rpcReq := &v1.UserUpdateRequest{
  278. OrganizationCode:tokenInfo.OrganizationCode,
  279. Uid:tokenInfo.Uid,
  280. Name:req.Name,
  281. Username:req.Username,
  282. Zones:req.Zones,
  283. Email:req.Email,
  284. Phone:req.Phone,
  285. Password:req.Password,
  286. GroupId:req.GroupId,
  287. Id:req.Id,
  288. }
  289. rpcRsp, err := pb.Organization.UserUpdate(ctx, rpcReq)
  290. if err != nil {
  291. s, _ := json.MarshalToString(req)
  292. logger.Error("func",
  293. zap.String("call", "pb.Organization.UserUpdate"),
  294. zap.String("params", s),
  295. zap.String("error", err.Error()))
  296. return errors.ErrorTransForm(err)
  297. }
  298. logReq := OperationLogRequest{
  299. Module:consts.OperationModuleUser,
  300. Action:consts.OperationActionUserUpdate,
  301. Origin:rpcRsp.Origin,
  302. Target:req.UserUpdateBody,
  303. UserName:tokenInfo.Username,
  304. Uid:tokenInfo.Uid,
  305. OrganizationCode:tokenInfo.OrganizationCode,
  306. }
  307. OperationLogAdd(&logReq)
  308. ctx.JSON(http.StatusOK, resp)
  309. return nil
  310. }
  311. // 执行任务
  312. httptasker.Exec(ctx, parseParamTask, handleServiceTask)
  313. }
  314. //
  315. // @Summary 删除用户
  316. // @Description 删除用户
  317. // @Tags 系统管理-用户管理
  318. // @Accept json
  319. // @Produce json
  320. // @Param token header string true "token"
  321. // @Param id path int64 true " "
  322. // @Success 200 {object} v1.UserDelResponse
  323. // @Failure 500 {object} base.HTTPError
  324. // @Router /api/v1/system/user/{id} [delete]
  325. func (c *Controller) UserDel(ctx *gin.Context) {
  326. // 解析参数
  327. req := &param_v1.UserDelRequest{}
  328. parseParamTask := func() error {
  329. err := util.ShouldBind(ctx, &req.Header, &req.UserDelPath, nil, nil)
  330. if err != nil {
  331. logger.Error("func",
  332. zap.String("call", "util.ShouldBind"),
  333. zap.String("error", err.Error()))
  334. return errors.ParamsError
  335. }
  336. return nil
  337. }
  338. // 业务处理
  339. handleServiceTask := func() error {
  340. // 响应数据
  341. tokenInfo, err := utils.GetTokeInfo(ctx)
  342. if err != nil {
  343. return err
  344. }
  345. resp := param_v1.UserDelResponse{}
  346. rpcReq := &v1.UserDelRequest{
  347. OrganizationCode:tokenInfo.OrganizationCode,
  348. Uid:tokenInfo.Uid,
  349. Id:req.Id,
  350. }
  351. rpcRsp, err := pb.Organization.UserDel(ctx, rpcReq)
  352. if err != nil {
  353. s, _ := json.MarshalToString(req)
  354. logger.Error("func",
  355. zap.String("call", "pb.Organization.UserDel"),
  356. zap.String("params", s),
  357. zap.String("error", err.Error()))
  358. return errors.ErrorTransForm(err)
  359. }
  360. ctx.JSON(http.StatusOK, resp)
  361. logReq := OperationLogRequest{
  362. Module:consts.OperationModuleUser,
  363. Action:consts.OperationActionUserDel,
  364. Origin:rpcRsp,
  365. Target:req.UserDelPath,
  366. UserName:tokenInfo.Username,
  367. Uid:tokenInfo.Uid,
  368. OrganizationCode:tokenInfo.OrganizationCode,
  369. }
  370. OperationLogAdd(&logReq)
  371. return nil
  372. }
  373. // 执行任务
  374. httptasker.Exec(ctx, parseParamTask, handleServiceTask)
  375. }
  376. //
  377. // @Summary 用户列表
  378. // @Description 用户列表
  379. // @Tags 系统管理-用户管理
  380. // @Accept json
  381. // @Produce json
  382. // @Param token header string true "token"
  383. // @Param page query int64 false " "
  384. // @Param page_size query int64 false " "
  385. // @Param name query string false "姓名或账户名 "
  386. // @Param zone query string false "区域 "
  387. // @Success 200 {object} v1.UserListResponse
  388. // @Failure 500 {object} base.HTTPError
  389. // @Router /api/v1/system/user/list [get]
  390. func (c *Controller) UserList(ctx *gin.Context) {
  391. // 解析参数
  392. req := &param_v1.UserListRequest{}
  393. parseParamTask := func() error {
  394. err := util.ShouldBind(ctx, &req.Header, nil, &req.UserListQuery, nil)
  395. if err != nil {
  396. logger.Error("func",
  397. zap.String("call", "util.ShouldBind"),
  398. zap.String("error", err.Error()))
  399. return errors.ParamsError
  400. }
  401. return nil
  402. }
  403. // 业务处理
  404. handleServiceTask := func() error {
  405. // 响应数据
  406. tokenInfo, err := utils.GetTokeInfo(ctx)
  407. if err != nil {
  408. return err
  409. }
  410. resp := param_v1.UserListResponse{}
  411. rpcReq := &v1.UserListRequest{
  412. Organization:tokenInfo.OrganizationCode,
  413. Uid:tokenInfo.Uid,
  414. PageSize:req.PageSize,
  415. Page:req.Page,
  416. Filter:req.Name,
  417. Zone:req.Zone,
  418. }
  419. rpcResp, err := pb.Organization.UserList(ctx, rpcReq)
  420. if err != nil {
  421. s, _ := json.MarshalToString(req)
  422. logger.Error("func",
  423. zap.String("call", "pb.Organization.UserList"),
  424. zap.String("params", s),
  425. zap.String("error", err.Error()))
  426. return errors.ErrorTransForm(err)
  427. }
  428. if rpcResp.List == nil {
  429. rpcResp.List = make([]*v1.UserItem, 0)
  430. }
  431. resp.Data = *rpcResp
  432. ctx.JSON(http.StatusOK, resp)
  433. return nil
  434. }
  435. // 执行任务
  436. httptasker.Exec(ctx, parseParamTask, handleServiceTask)
  437. }
  438. func handleZoneSelectList(list []*v1.ZoneItemSelect) ([]*v1.ZoneItemSelect) {
  439. if len(list) == 0 {
  440. list = make([]*v1.ZoneItemSelect, 0)
  441. return list
  442. }
  443. for i, v := range list {
  444. list[i].Childs = handleZoneSelectList(v.Childs)
  445. }
  446. return list
  447. }
  448. //
  449. // @Summary 用户详情
  450. // @Description 用户详情
  451. // @Tags 系统管理-用户管理
  452. // @Accept json
  453. // @Produce json
  454. // @Param token header string true "token"
  455. // @Param id path int64 true " "
  456. // @Success 200 {object} v1.UserInfoResponse
  457. // @Failure 500 {object} base.HTTPError
  458. // @Router /api/v1/system/user/info/{id} [get]
  459. func (c *Controller) UserInfo(ctx *gin.Context) {
  460. // 解析参数
  461. req := &param_v1.UserInfoRequest{}
  462. parseParamTask := func() error {
  463. err := util.ShouldBind(ctx, &req.Header, &req.UserInfoPath, nil, nil)
  464. if err != nil {
  465. logger.Error("func",
  466. zap.String("call", "util.ShouldBind"),
  467. zap.String("error", err.Error()))
  468. return errors.ParamsError
  469. }
  470. return nil
  471. }
  472. // 业务处理
  473. handleServiceTask := func() error {
  474. // 响应数据
  475. tokenInfo, err := utils.GetTokeInfo(ctx)
  476. if err != nil {
  477. return err
  478. }
  479. resp := param_v1.UserInfoResponse{}
  480. rpcReq := &v1.UserInfoRequest{
  481. OrganizationCode:tokenInfo.OrganizationCode,
  482. Uid:tokenInfo.Uid,
  483. Id:req.Id,
  484. }
  485. rpcResp, err := pb.Organization.UserInfo(ctx, rpcReq)
  486. if err != nil {
  487. s, _ := json.MarshalToString(req)
  488. logger.Error("func",
  489. zap.String("call", "pb.Organization.UserInfo"),
  490. zap.String("params", s),
  491. zap.String("error", err.Error()))
  492. return errors.ErrorTransForm(err)
  493. }
  494. resp.Data = *rpcResp
  495. resp.Data.ZoneList = handleZoneSelectList(resp.Data.ZoneList)
  496. resp.Data.NodeList = handleRbacList(resp.Data.NodeList)
  497. ctx.JSON(http.StatusOK, resp)
  498. return nil
  499. }
  500. // 执行任务
  501. httptasker.Exec(ctx, parseParamTask, handleServiceTask)
  502. }