// Copyright 2019 github.com. All rights reserved. // Use of this source code is governed by github.com. package v1 import ( "cp-organization-management-gateway/consts" "cp-organization-management-gateway/utils" "fmt" "github.com/tidwall/gjson" "net/http" "cp-organization-management-gateway/errors" param_v1 "cp-organization-management-gateway/param/v1" "cp-organization-management-gateway/pb" "cp-organization-management-gateway/pb/v1" "time" "github.com/dgrijalva/jwt-go" "github.com/jaryhe/gopkgs/logger" "github.com/jaryhe/gopkgs/tasker/httptasker" "github.com/jaryhe/gopkgs/util" "cp-organization-management-gateway/parser" "github.com/gin-gonic/gin" "github.com/jaryhe/gopkgs/jwtwrapper" "go.uber.org/zap" ) // 登录 // @Summary 登录 // @Description 登录 // @Tags 用户 // @Accept json // @Produce json // @Param body body v1.LoginBody true "登录信息" // @Success 200 {object} v1.LoginResponse // @Failure 500 {object} base.HTTPError // @Router /api/v1/user/login [post] func (c *Controller) Login(ctx *gin.Context) { // 解析参数 req := ¶m_v1.LoginRequest{} parseParamTask := func() error { err := util.ShouldBind(ctx, &req.Header, nil, nil, &req.LoginBody) if err != nil { logger.Error("func", zap.String("call", "util.ShouldBind"), zap.String("error", err.Error())) return errors.ParamsError } return nil } // 业务处理 handleServiceTask := func() error { // 响应数据 resp := param_v1.LoginResponse{} rpcReq := &v1.ManagementLoginRequest{ Username: req.User, Password: req.Password, Key:req.Key, } rpcRsp, err := pb.Organization.ManagementLogin(ctx, rpcReq) if err != nil { s, _ := json.MarshalToString(req) logger.Error("func", zap.String("call", "pb.Organization.ManagementLogin"), zap.String("params", s), zap.String("error", err.Error())) return errors.ErrorTransForm(err) } subject := map[string]interface{}{ "user_name": req.User, "end_time": rpcRsp.EndTime, "organization_code":rpcRsp.OrganizationCode, "permissions":rpcRsp.Permissions, "is_super":rpcRsp.IsSuper, } str, _ := json.MarshalToString(subject) // 生成token token, err := jwtwrapper.GenToken(fmt.Sprintf("%d", rpcRsp.Uid), parser.Conf.Jwt.Issuer, str, time.Duration(parser.Conf.Jwt.Seconds)*time.Second) if err != nil { logger.Error("func", zap.String("call", "util.GenJwtToken"), zap.String("args", fmt.Sprintf("%d", rpcRsp.Uid)), zap.String("error", err.Error())) return errors.SystemError } refreshTokenTime := time.Duration(24*60*60)*time.Second refreshToken, err := jwtwrapper.GenToken(fmt.Sprintf("%d", rpcRsp.Uid), parser.Conf.Jwt.Issuer, str, refreshTokenTime) if err != nil { logger.Error("func", zap.String("call", "util.GenJwtToken"), zap.String("args", fmt.Sprintf("%d", rpcRsp.Uid)), zap.String("error", err.Error())) return errors.SystemError } resp.Data.Uid = rpcRsp.Uid resp.Data.Token = token resp.Data.User = req.User resp.Data.Organization = rpcRsp.OrganizationName resp.Data.RefreshToken = refreshToken ctx.JSON(http.StatusOK, resp) return nil } // 执行任务 httptasker.Exec(ctx, parseParamTask, handleServiceTask) } // token // @Summary 刷新token // @Description 刷新token // @Tags 用户 // @Accept json // @Produce json // @Param token header string true "token" // @Success 200 {object} v1.TokenResponse // @Failure 500 {object} base.HTTPError // @Router /api/v1/token_refresh [put] func (c *Controller) TokenRefresh(ctx *gin.Context) { // 解析参数 req := ¶m_v1.TokenRequest{} parseParamTask := func() error { err := util.ShouldBind(ctx, &req.Header, nil, nil, nil) if err != nil { logger.Error("func", zap.String("call", "util.ShouldBind"), zap.String("error", err.Error())) return errors.ParamsError } return nil } // 业务处理 handleServiceTask := func() error { tokenObj, err := jwtwrapper.ParseToken(req.Token) if tokenObj == nil { return errors.TokenFailedError } if err != nil { switch err.(*jwt.ValidationError).Errors { case jwt.ValidationErrorExpired: return errors.TokenFailedError default: return errors.TokenFailedError } } uid := tokenObj.Id subject := tokenObj.Subject remberPass := gjson.GetBytes([]byte(subject), "rember_password").Bool() // 生成token token, err := jwtwrapper.GenToken(uid, parser.Conf.Jwt.Issuer, subject, time.Duration(parser.Conf.Jwt.Seconds)*time.Second) if err != nil { logger.Error("func", zap.String("call", "util.GenJwtToken"), zap.String("args", fmt.Sprintf("%s", uid)), zap.String("error", err.Error())) return errors.SystemError } refreshTokenTime := time.Duration(24*60*60)*time.Second if remberPass { refreshTokenTime = time.Duration(7*24*60*60)*time.Second } refreshToken, err := jwtwrapper.GenToken(uid, parser.Conf.Jwt.Issuer, subject, refreshTokenTime) if err != nil { logger.Error("func", zap.String("call", "util.GenJwtToken"), zap.String("args", fmt.Sprintf("%s", uid)), zap.String("error", err.Error())) return errors.SystemError } resp := param_v1.TokenResponse{} resp.Data = token resp.RefreshToken = refreshToken ctx.JSON(http.StatusOK, resp) return nil } // 执行任务 httptasker.Exec(ctx, parseParamTask, handleServiceTask) } // // @Summary 创建用户 // @Description 创建用户 // @Tags 系统管理-用户管理 // @Accept json // @Produce json // @Param token header string true "token" // @Param body body v1.UserCreateBody true " " // @Success 200 {object} v1.UserCreateResponse // @Failure 500 {object} base.HTTPError // @Router /api/v1/system/user [post] func (c *Controller) UserCreate(ctx *gin.Context) { // 解析参数 req := ¶m_v1.UserCreateRequest{} parseParamTask := func() error { err := util.ShouldBind(ctx, &req.Header, nil, nil, &req.UserCreateBody) if err != nil { logger.Error("func", zap.String("call", "util.ShouldBind"), zap.String("error", err.Error())) return errors.ParamsError } return nil } // 业务处理 handleServiceTask := func() error { // 响应数据 tokenInfo, err := utils.GetTokeInfo(ctx) if err != nil { return err } resp := param_v1.UserCreateResponse{} rpcReq := &v1.CreateManagementUserRequest{ OrganizationCode:tokenInfo.OrganizationCode, Uid:tokenInfo.Uid, Name:req.Name, Username:req.Username, Zones:req.Zones, Email:req.Email, Phone:req.Phone, Password:req.Password, GroupId:req.GroupId, } rpcRsp, err := pb.Organization.CreateManagementUser(ctx, rpcReq) if err != nil { s, _ := json.MarshalToString(req) logger.Error("func", zap.String("call", "pb.Organization.CreateManagementUser"), zap.String("params", s), zap.String("error", err.Error())) return errors.ErrorTransForm(err) } resp.Data = *rpcRsp ctx.JSON(http.StatusOK, resp) logReq := OperationLogRequest{ Module:consts.OperationModuleUser, Action:consts.OperationActionUserAdd, Origin:nil, Target:req.UserCreateBody, UserName:tokenInfo.Username, Uid:tokenInfo.Uid, OrganizationCode:tokenInfo.OrganizationCode, } OperationLogAdd(&logReq) return nil } // 执行任务 httptasker.Exec(ctx, parseParamTask, handleServiceTask) } // // @Summary 修改用户 // @Description 修改用户 // @Tags 系统管理-用户管理 // @Accept json // @Produce json // @Param token header string true "token" // @Param body body v1.UserUpdateBody true " " // @Success 200 {object} v1.UserUpdateResponse // @Failure 500 {object} base.HTTPError // @Router /api/v1/system/user [put] func (c *Controller) UserUpdate(ctx *gin.Context) { // 解析参数 req := ¶m_v1.UserUpdateRequest{} parseParamTask := func() error { err := util.ShouldBind(ctx, &req.Header, nil, nil, &req.UserUpdateBody) if err != nil { logger.Error("func", zap.String("call", "util.ShouldBind"), zap.String("error", err.Error())) return errors.ParamsError } return nil } // 业务处理 handleServiceTask := func() error { // 响应数据 tokenInfo, err := utils.GetTokeInfo(ctx) if err != nil { return err } resp := param_v1.UserUpdateResponse{} rpcReq := &v1.UserUpdateRequest{ OrganizationCode:tokenInfo.OrganizationCode, Uid:tokenInfo.Uid, Name:req.Name, Username:req.Username, Zones:req.Zones, Email:req.Email, Phone:req.Phone, Password:req.Password, GroupId:req.GroupId, Id:req.Id, } rpcRsp, err := pb.Organization.UserUpdate(ctx, rpcReq) if err != nil { s, _ := json.MarshalToString(req) logger.Error("func", zap.String("call", "pb.Organization.UserUpdate"), zap.String("params", s), zap.String("error", err.Error())) return errors.ErrorTransForm(err) } logReq := OperationLogRequest{ Module:consts.OperationModuleUser, Action:consts.OperationActionUserUpdate, Origin:rpcRsp.Origin, Target:req.UserUpdateBody, UserName:tokenInfo.Username, Uid:tokenInfo.Uid, OrganizationCode:tokenInfo.OrganizationCode, } OperationLogAdd(&logReq) ctx.JSON(http.StatusOK, resp) return nil } // 执行任务 httptasker.Exec(ctx, parseParamTask, handleServiceTask) } // // @Summary 删除用户 // @Description 删除用户 // @Tags 系统管理-用户管理 // @Accept json // @Produce json // @Param token header string true "token" // @Param id path int64 true " " // @Success 200 {object} v1.UserDelResponse // @Failure 500 {object} base.HTTPError // @Router /api/v1/system/user/{id} [delete] func (c *Controller) UserDel(ctx *gin.Context) { // 解析参数 req := ¶m_v1.UserDelRequest{} parseParamTask := func() error { err := util.ShouldBind(ctx, &req.Header, &req.UserDelPath, nil, nil) if err != nil { logger.Error("func", zap.String("call", "util.ShouldBind"), zap.String("error", err.Error())) return errors.ParamsError } return nil } // 业务处理 handleServiceTask := func() error { // 响应数据 tokenInfo, err := utils.GetTokeInfo(ctx) if err != nil { return err } resp := param_v1.UserDelResponse{} rpcReq := &v1.UserDelRequest{ OrganizationCode:tokenInfo.OrganizationCode, Uid:tokenInfo.Uid, Id:req.Id, } rpcRsp, err := pb.Organization.UserDel(ctx, rpcReq) if err != nil { s, _ := json.MarshalToString(req) logger.Error("func", zap.String("call", "pb.Organization.UserDel"), zap.String("params", s), zap.String("error", err.Error())) return errors.ErrorTransForm(err) } ctx.JSON(http.StatusOK, resp) logReq := OperationLogRequest{ Module:consts.OperationModuleUser, Action:consts.OperationActionUserDel, Origin:rpcRsp, Target:req.UserDelPath, UserName:tokenInfo.Username, Uid:tokenInfo.Uid, OrganizationCode:tokenInfo.OrganizationCode, } OperationLogAdd(&logReq) return nil } // 执行任务 httptasker.Exec(ctx, parseParamTask, handleServiceTask) } // // @Summary 用户列表 // @Description 用户列表 // @Tags 系统管理-用户管理 // @Accept json // @Produce json // @Param token header string true "token" // @Param page query int64 false " " // @Param page_size query int64 false " " // @Param name query string false "姓名或账户名 " // @Param zone query string false "区域 " // @Success 200 {object} v1.UserListResponse // @Failure 500 {object} base.HTTPError // @Router /api/v1/system/user/list [get] func (c *Controller) UserList(ctx *gin.Context) { // 解析参数 req := ¶m_v1.UserListRequest{} parseParamTask := func() error { err := util.ShouldBind(ctx, &req.Header, nil, &req.UserListQuery, nil) if err != nil { logger.Error("func", zap.String("call", "util.ShouldBind"), zap.String("error", err.Error())) return errors.ParamsError } return nil } // 业务处理 handleServiceTask := func() error { // 响应数据 tokenInfo, err := utils.GetTokeInfo(ctx) if err != nil { return err } resp := param_v1.UserListResponse{} rpcReq := &v1.UserListRequest{ Organization:tokenInfo.OrganizationCode, Uid:tokenInfo.Uid, PageSize:req.PageSize, Page:req.Page, Filter:req.Name, Zone:req.Zone, } rpcResp, err := pb.Organization.UserList(ctx, rpcReq) if err != nil { s, _ := json.MarshalToString(req) logger.Error("func", zap.String("call", "pb.Organization.UserList"), zap.String("params", s), zap.String("error", err.Error())) return errors.ErrorTransForm(err) } if rpcResp.List == nil { rpcResp.List = make([]*v1.UserItem, 0) } resp.Data = *rpcResp ctx.JSON(http.StatusOK, resp) return nil } // 执行任务 httptasker.Exec(ctx, parseParamTask, handleServiceTask) } func handleZoneSelectList(list []*v1.ZoneItemSelect) ([]*v1.ZoneItemSelect) { if len(list) == 0 { list = make([]*v1.ZoneItemSelect, 0) return list } for i, v := range list { list[i].Childs = handleZoneSelectList(v.Childs) } return list } // // @Summary 用户详情 // @Description 用户详情 // @Tags 系统管理-用户管理 // @Accept json // @Produce json // @Param token header string true "token" // @Param id path int64 true " " // @Success 200 {object} v1.UserInfoResponse // @Failure 500 {object} base.HTTPError // @Router /api/v1/system/user/info/{id} [get] func (c *Controller) UserInfo(ctx *gin.Context) { // 解析参数 req := ¶m_v1.UserInfoRequest{} parseParamTask := func() error { err := util.ShouldBind(ctx, &req.Header, &req.UserInfoPath, nil, nil) if err != nil { logger.Error("func", zap.String("call", "util.ShouldBind"), zap.String("error", err.Error())) return errors.ParamsError } return nil } // 业务处理 handleServiceTask := func() error { // 响应数据 tokenInfo, err := utils.GetTokeInfo(ctx) if err != nil { return err } resp := param_v1.UserInfoResponse{} rpcReq := &v1.UserInfoRequest{ OrganizationCode:tokenInfo.OrganizationCode, Uid:tokenInfo.Uid, Id:req.Id, } rpcResp, err := pb.Organization.UserInfo(ctx, rpcReq) if err != nil { s, _ := json.MarshalToString(req) logger.Error("func", zap.String("call", "pb.Organization.UserInfo"), zap.String("params", s), zap.String("error", err.Error())) return errors.ErrorTransForm(err) } resp.Data = *rpcResp resp.Data.ZoneList = handleZoneSelectList(resp.Data.ZoneList) resp.Data.NodeList = handleRbacList(resp.Data.NodeList) ctx.JSON(http.StatusOK, resp) return nil } // 执行任务 httptasker.Exec(ctx, parseParamTask, handleServiceTask) }