From 4258661630fce9d18d29c3d3a62db1b8fe83ff3d Mon Sep 17 00:00:00 2001 From: tangxuhui <987654321@qq.com> Date: Mon, 7 Sep 2020 17:57:40 +0800 Subject: [PATCH] 日常提交保存 --- pkg/application/adminUser/command/admin_user_login.go | 14 ++++++++++++++ pkg/application/adminUser/service/admin_user.go | 4 ++-- pkg/application/unifiedUserCenter/service/employee.go | 1 - pkg/application/users/command/admin_user_login.go | 14 ++++++++++++++ pkg/application/users/service/service.go | 97 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ pkg/infrastructure/repository/pg_users_repository.go | 8 +++++++- pkg/infrastructure/serviceGateway/httplib_usercenter_service.go | 108 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ pkg/infrastructure/service_gateway/httplib_service_gateway.go | 11 ----------- pkg/infrastructure/service_gateway/httplib_usercenter_service.go | 108 ------------------------------------------------------------------------------------------------------------ pkg/port/beego/controllers/admin_login_controller.go | 67 ++++++++++++++++++++++++++++++++++++++++++++++++++----------------- pkg/port/beego/controllers/base_controller.go | 12 ++++++++++++ pkg/port/beego/routers/router.go | 2 +- 12 files changed, 305 insertions(+), 141 deletions(-) create mode 100644 pkg/application/adminUser/command/admin_user_login.go create mode 100644 pkg/application/users/command/admin_user_login.go create mode 100644 pkg/application/users/service/service.go create mode 100644 pkg/infrastructure/serviceGateway/httplib_usercenter_service.go delete mode 100644 pkg/infrastructure/service_gateway/httplib_service_gateway.go delete mode 100644 pkg/infrastructure/service_gateway/httplib_usercenter_service.go diff --git a/pkg/application/adminUser/command/admin_user_login.go b/pkg/application/adminUser/command/admin_user_login.go new file mode 100644 index 0000000..431dc5b --- /dev/null +++ b/pkg/application/adminUser/command/admin_user_login.go @@ -0,0 +1,14 @@ +package command + +import "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib" + +type LoginBySecretKeyCommand struct { + Secret string `json:"secret"` +} + +func (login LoginBySecretKeyCommand) ValidateCommand() error { + if len(login.Secret) == 0 { + return lib.ThrowError(lib.ARG_ERROR, "登录参数错误") + } + return nil +} diff --git a/pkg/application/adminUser/service/admin_user.go b/pkg/application/adminUser/service/admin_user.go index 193dbdd..a6e5661 100644 --- a/pkg/application/adminUser/service/admin_user.go +++ b/pkg/application/adminUser/service/admin_user.go @@ -257,13 +257,13 @@ func (adminUserSrv AdminUserService) UpdateAdminIsUsable(uid int64, isUsable boo adminuserDao = v } if ok, err := adminuserDao.AdminUserIsDefault(uid); err != nil { - return lib.ThrowError(lib.TRANSACTION_ERROR, err.Error()) + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error()) } else if ok { return lib.ThrowError(lib.BUSINESS_ERROR, "请勿禁用超级管理员") } err = adminuserDao.UpdateIsUsable(uid, isUsable) if err != nil { - return lib.ThrowError(lib.TRANSACTION_ERROR, err.Error()) + return lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error()) } transactionContext.CommitTransaction() return nil diff --git a/pkg/application/unifiedUserCenter/service/employee.go b/pkg/application/unifiedUserCenter/service/employee.go index eb6e68b..a836533 100644 --- a/pkg/application/unifiedUserCenter/service/employee.go +++ b/pkg/application/unifiedUserCenter/service/employee.go @@ -362,7 +362,6 @@ func (service SyncEmployeeService) ChangeSuperAdmin(cmd command.ChanceSuperAdmin if err != nil { return lib.ThrowError(lib.BUSINESS_ERROR, err.Error()) } - //提取到domain??? err = newSuperUser.Update(map[string]interface{}{ "AdminType": domain.UserIsAdmin, }) diff --git a/pkg/application/users/command/admin_user_login.go b/pkg/application/users/command/admin_user_login.go new file mode 100644 index 0000000..431dc5b --- /dev/null +++ b/pkg/application/users/command/admin_user_login.go @@ -0,0 +1,14 @@ +package command + +import "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib" + +type LoginBySecretKeyCommand struct { + Secret string `json:"secret"` +} + +func (login LoginBySecretKeyCommand) ValidateCommand() error { + if len(login.Secret) == 0 { + return lib.ThrowError(lib.ARG_ERROR, "登录参数错误") + } + return nil +} diff --git a/pkg/application/users/service/service.go b/pkg/application/users/service/service.go new file mode 100644 index 0000000..e5d1842 --- /dev/null +++ b/pkg/application/users/service/service.go @@ -0,0 +1,97 @@ +package service + +import ( + "fmt" + + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/factory" + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/users/command" + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/domain" + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/infrastructure/serviceGateway" + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib" +) + +type UsersService struct { +} + +func NewUsersService(option map[string]interface{}) *UsersService { + newUsersService := new(UsersService) + return newUsersService +} + +func (service UsersService) UserLoginBySecretKey(cmd command.LoginBySecretKeyCommand) (interface{}, error) { + var err error + if err = cmd.ValidateCommand(); err != nil { + return nil, err + } + //向统一用户中心确认密钥信息并获取用户数据 + ucenterService := serviceGateway.NewMmmUserCenterServiceGateway() + loginResp, err := ucenterService.RequestUCenterLoginBySecret(cmd.Secret) + if err != nil { + e := fmt.Sprintf("通过密钥(secret=%s)从统一用户中心获取数据失败:%s", cmd.Secret, err.Error()) + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e) + } + var ( + transactionContext, _ = factory.CreateTransactionContext(nil) + ) + if err = transactionContext.StartTransaction(); err != nil { + return nil, lib.ThrowError(lib.TRANSACTION_ERROR, err.Error()) + } + defer func() { + transactionContext.RollbackTransaction() + }() + var ( + companyRespository domain.CompanyRepository + userRespository domain.UsersRepository + companyData domain.Company + usersData domain.Users + ) + if companyRespository, err = factory.CreateCompanyRepository(map[string]interface{}{ + "transactionContext": transactionContext, + }); err != nil { + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error()) + } + if userRespository, err = factory.CreateUsersRepository(map[string]interface{}{ + "transactionContext": transactionContext, + }); err != nil { + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, err.Error()) + } + //检索本系统的公司数据判断公司权限 + companyData, err = companyRespository.FindOne(map[string]interface{}{ + "Id": loginResp.Data.Muid, + }) + if err != nil { + e := fmt.Sprintf("获取公司(id=%d)数据失败:%s", loginResp.Data.Muid, err.Error()) + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e) + } + if !companyData.EnableIsOk() { + return nil, lib.ThrowError(lib.BUSINESS_ERROR, "该公司没有操作权限") + } + //检索本系统的用户数据 + usersData, err = userRespository.FindOne(map[string]interface{}{ + "OpenId": loginResp.Data.Id, + "CompanyId": companyData.Id, + }) + if err != nil { + e := fmt.Sprintf("获取用户(OpenId=%d;CompanyId=%d)数据失败:%s", + loginResp.Data.Id, companyData.Id, err.Error()) + return nil, lib.ThrowError(lib.INTERNAL_SERVER_ERROR, e) + } + //确认用户权限 + if !usersData.IsUsable() { + return nil, lib.ThrowError(lib.BUSINESS_ERROR, "用户被禁用") + } + err = transactionContext.CommitTransaction() + //生成token + + return nil, nil +} + +//GetAdminpPofile 登录后获取用户的权限配置数据 +func (service UsersService) GetAdminpPofile() (interface{}, error) { + return nil, nil +} + +//ValidateAdminpPermission 校验用户的操作权限 +func (service UsersService) ValidateAdminpPermission() (interface{}, error) { + return nil, nil +} diff --git a/pkg/infrastructure/repository/pg_users_repository.go b/pkg/infrastructure/repository/pg_users_repository.go index 19192e3..ba1ac0c 100644 --- a/pkg/infrastructure/repository/pg_users_repository.go +++ b/pkg/infrastructure/repository/pg_users_repository.go @@ -125,9 +125,15 @@ func (reponsitory UsersRepository) FindOne(queryOptions map[string]interface{}) if v, ok := queryOptions["Id"]; ok { query = query.Where("id=?", v) } - if v, ok := queryOptions["phone"]; ok { + if v, ok := queryOptions["Phone"]; ok { query = query.Where("phone=?", v) } + if v, ok := queryOptions["CompanyId"]; ok { + query = query.Where("company_id=?", v) + } + if v, ok := queryOptions["OpenId"]; ok { + query = query.Where("open_id=?", v) + } err = query.First() if err != nil { return domain.Users{}, err diff --git a/pkg/infrastructure/serviceGateway/httplib_usercenter_service.go b/pkg/infrastructure/serviceGateway/httplib_usercenter_service.go new file mode 100644 index 0000000..86ef4d5 --- /dev/null +++ b/pkg/infrastructure/serviceGateway/httplib_usercenter_service.go @@ -0,0 +1,108 @@ +package serviceGateway + +import ( + "bytes" + "crypto/sha1" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "net/url" + "time" + + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/constant" +) + +type UCenterCommonMsg struct { + Code int `json:"code"` + Msg string `json:"msg"` +} + +func (msg UCenterCommonMsg) IsOK() error { + if msg.Code != 0 { + return fmt.Errorf("统一用户中心响应数据异常,code:%d,msg:%s", msg.Code, msg.Msg) + } + return nil +} + +type MmmUserCenterServiceGateway struct { + baseURL string +} + +func NewMmmUserCenterServiceGateway() *MmmUserCenterServiceGateway { + return &MmmUserCenterServiceGateway{ + baseURL: constant.UCENTER_HOST, + } +} + +func (gateway MmmUserCenterServiceGateway) buildHeader() http.Header { + var h = http.Header{} + nowTime := fmt.Sprint(time.Now().Unix()) + str := fmt.Sprintf("%s%s%s", nowTime, constant.UCENTER_SECRET, constant.UCENTER_CHECK_ALT) + bt := sha1.Sum([]byte(str)) + checksum := fmt.Sprintf("%x", bt) + h.Set("Content-Type", "application/json") + h.Set("appKey", constant.UCENTER_APP_KEY) + h.Set("nonce", "") + h.Set("curTime", nowTime) + h.Set("checkSum", checksum) + h.Set("Accept", "application/json") + return h +} + +func (gateway MmmUserCenterServiceGateway) httpDo(reqURL string, mathod string, bodyData interface{}) ([]byte, error) { + httpclient := http.Client{ + Timeout: 60 * time.Second, //请求超时时间60秒 + } + bt := &bytes.Buffer{} + if bodyData != nil { + enc := json.NewEncoder(bt) + enc.Encode(bodyData) + } + req, err := http.NewRequest(mathod, reqURL, bt) + if err != nil { + return nil, err + } + req.Header = gateway.buildHeader() + resp, err := httpclient.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + return body, nil +} + +type ResponseLogin struct { + UCenterCommonMsg + Data struct { + Id int64 `json:"id"` //统一用户中心的id,对应本系统中users表的open_id + Phone string `json:"phone"` //手机号 ,账号 + NickName string `json:"nickname"` //昵称 + Avatar string `json:"avatar"` //头像 + Imtoken string `json:"imtoken"` //网易云imtoken + Accid int64 `json:"accid"` //网易云id + CustomerAccount int64 `json:"customerAccount"` //客服id + CompanyId int64 `json:"companyId"` //总后台的公司id + Muid int64 `json:"muid"` //企业平台的用户id,对应本系统中users表的id + } `json:"data"` +} + +//RequestUCenterLoginBySecret 使用密钥方式登录统一用户中心 +func (gateway MmmUserCenterServiceGateway) RequestUCenterLoginBySecret(secret string) (*ResponseLogin, error) { + param := map[string]interface{}{ + "type": 3, //登录方式 固定值 + "secret": url.QueryEscape(secret), //必要的转换 + } + url := constant.UCENTER_HOST + "/auth/serverLogin" + byteData, err := gateway.httpDo(url, "post", param) + if err != nil { + return nil, err + } + respData := &ResponseLogin{} + err = json.Unmarshal(byteData, respData) + return respData, err +} diff --git a/pkg/infrastructure/service_gateway/httplib_service_gateway.go b/pkg/infrastructure/service_gateway/httplib_service_gateway.go deleted file mode 100644 index a7763a0..0000000 --- a/pkg/infrastructure/service_gateway/httplib_service_gateway.go +++ /dev/null @@ -1,11 +0,0 @@ -package service_gateway - -import ( - "time" -) - -type httplibBaseServiceGateway struct { - baseURL string - connectTimeout time.Duration - readWriteTimeout time.Duration -} diff --git a/pkg/infrastructure/service_gateway/httplib_usercenter_service.go b/pkg/infrastructure/service_gateway/httplib_usercenter_service.go deleted file mode 100644 index 562a9b8..0000000 --- a/pkg/infrastructure/service_gateway/httplib_usercenter_service.go +++ /dev/null @@ -1,108 +0,0 @@ -package service_gateway - -import ( - "bytes" - "crypto/sha1" - "encoding/json" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "time" - - "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/constant" -) - -type UCenterCommonMsg struct { - Code int `json:"code"` - Msg string `json:"msg"` -} - -func (msg UCenterCommonMsg) IsOK() error { - if msg.Code != 0 { - return fmt.Errorf("统一用户中心响应数据异常,code:%d,msg:%s", msg.Code, msg.Msg) - } - return nil -} - -type MmmUserCenterServiceGateway struct { - baseURL string -} - -func NewMmmUserCenterServiceGateway() *MmmUserCenterServiceGateway { - return &MmmUserCenterServiceGateway{ - baseURL: constant.UCENTER_HOST, - } -} - -func (gateway MmmUserCenterServiceGateway) buildHeader() http.Header { - var h = http.Header{} - nowTime := fmt.Sprint(time.Now().Unix()) - str := fmt.Sprintf("%s%s%s", nowTime, constant.UCENTER_SECRET, constant.UCENTER_CHECK_ALT) - bt := sha1.Sum([]byte(str)) - checksum := fmt.Sprintf("%x", bt) - h.Set("Content-Type", "application/json") - h.Set("appKey", constant.UCENTER_APP_KEY) - h.Set("nonce", "") - h.Set("curTime", nowTime) - h.Set("checkSum", checksum) - h.Set("Accept", "application/json") - return h -} - -func (gateway MmmUserCenterServiceGateway) httpDo(reqURL string, mathod string, bodyData interface{}) ([]byte, error) { - httpclient := http.Client{ - Timeout: 60 * time.Second, //请求超时时间60秒 - } - bt := &bytes.Buffer{} - if bodyData != nil { - enc := json.NewEncoder(bt) - enc.Encode(bodyData) - } - req, err := http.NewRequest(mathod, reqURL, bt) - if err != nil { - return nil, err - } - req.Header = gateway.buildHeader() - resp, err := httpclient.Do(req) - if err != nil { - return nil, err - } - defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) - if err != nil { - return nil, err - } - return body, nil -} - -type ResponseLogin struct { - UCenterCommonMsg - Data struct { - Id int64 `json:"id"` //统一用户中心的id,对应本系统中users表的open_id - Phone string `json:"phone"` - NickName string `json:"nickname"` //昵称 - Avatar string `json:"avatar"` //头像 - Imtoken string `json:"imtoken"` //网易云imtoken - Accid int64 `json:"accid"` //网易云id - CustomerAccount int64 `json:"customerAccount"` //客服id - CompanyId int64 `json:"companyId"` //总后台的公司id - Muid int64 `json:"muid"` //企业平台的用户id,对应本系统中users表的id - } `json:"data"` -} - -//RequestUCenterLoginBySecret 使用密钥方式登录统一用户中心 -func (gateway MmmUserCenterServiceGateway) RequestUCenterLoginBySecret(secret string) (*ResponseLogin, error) { - param := map[string]interface{}{ - "type": 3, //登录方式 固定值 - "secret": url.QueryEscape(secret), //必要的转换 - } - url := constant.UCENTER_HOST + "/auth/serverLogin" - byteData, err := gateway.httpDo(url, "post", param) - if err != nil { - return nil, err - } - respData := &ResponseLogin{} - err = json.Unmarshal(byteData, respData) - return respData, err -} diff --git a/pkg/port/beego/controllers/admin_login_controller.go b/pkg/port/beego/controllers/admin_login_controller.go index f8bbc0e..60af7bd 100644 --- a/pkg/port/beego/controllers/admin_login_controller.go +++ b/pkg/port/beego/controllers/admin_login_controller.go @@ -6,8 +6,6 @@ import ( "fmt" "time" - "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib" - "github.com/GeeTeam/gt3-golang-sdk/geetest" "github.com/astaxie/beego/logs" adminPermissionquery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminPermission/query" @@ -15,6 +13,7 @@ import ( adminuserCmd "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminUser/command" adminuserquery "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminUser/query" adminuserservice "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/application/adminUser/service" + "gitlab.fjmaimaimai.com/mmm-go/partnermg/pkg/lib" ) type AdminLoginController struct { @@ -40,6 +39,52 @@ func (c *AdminLoginController) Prepare() { } //Login 用户登录 +// func (c *AdminLoginController) Login() { +// type Paramter struct { +// Username string `json:"username"` +// Password string `json:"password"` +// } +// var ( +// param Paramter +// err error +// ) +// if err = c.BindJsonData(¶m); err != nil { +// c.ResponseError(fmt.Errorf("json解析失败:%s", err)) +// return +// } +// newAdminuserquery := adminuserquery.GetAdminUserQuery{AdminAccount: param.Username} +// newAdminUserService := adminuserservice.NewAdminUserService(nil) +// adminuser, err := newAdminUserService.GetAdminUser(&newAdminuserquery) +// if err != nil { +// logs.Error("获取用户数据失败:%s", err) +// c.ResponseError(errors.New("用户不存在")) +// return +// } +// if adminuser.Password != param.Password { +// c.ResponseError(errors.New("账号或密码错误")) +// return +// } +// if !adminuser.IsUsable { +// c.ResponseError(errors.New("用户被禁用")) +// } +// //TODO +// newJwt := lib.NewMyToken(adminuser.Id, 0) +// newToken, err := newJwt.CreateJWTToken() +// if err != nil { +// logs.Error("生成jwt数据失败:%s", err) +// c.ResponseError(errors.New("服务异常")) +// return +// } +// rspdata := map[string]interface{}{ +// "access": map[string]interface{}{ +// "accessToken": newToken, +// "expiresIn": lib.JWtExpiresSecond, +// }, +// } +// c.ResponseData(rspdata) +// return +// } + func (c *AdminLoginController) Login() { type Paramter struct { Username string `json:"username"` @@ -55,21 +100,9 @@ func (c *AdminLoginController) Login() { } newAdminuserquery := adminuserquery.GetAdminUserQuery{AdminAccount: param.Username} newAdminUserService := adminuserservice.NewAdminUserService(nil) - adminuser, err := newAdminUserService.GetAdminUser(&newAdminuserquery) - if err != nil { - logs.Error("获取用户数据失败:%s", err) - c.ResponseError(errors.New("用户不存在")) - return - } - if adminuser.Password != param.Password { - c.ResponseError(errors.New("账号或密码错误")) - return - } - if !adminuser.IsUsable { - c.ResponseError(errors.New("用户被禁用")) - } - //TODO - newJwt := lib.NewMyToken(adminuser.Id, 0) + _ = newAdminuserquery + _ = newAdminUserService + newJwt := lib.NewMyToken(0, 0) newToken, err := newJwt.CreateJWTToken() if err != nil { logs.Error("生成jwt数据失败:%s", err) diff --git a/pkg/port/beego/controllers/base_controller.go b/pkg/port/beego/controllers/base_controller.go index b89681e..cb27e4c 100644 --- a/pkg/port/beego/controllers/base_controller.go +++ b/pkg/port/beego/controllers/base_controller.go @@ -144,6 +144,7 @@ func (controller *BaseController) ValidJWTToken() bool { return false } controller.setUserId(tokenData.UID) + controller.setUserCompanyId(tokenData.CompanyId) return true } @@ -196,3 +197,14 @@ func (controller *BaseController) setUserId(id int64) { logs.Info("token:admin_user_id = ", id) controller.Ctx.Input.SetData("token:admin_user_id", id) } + +func (controller *BaseController) setUserCompanyId(id int64) { + logs.Info("token:company_id = ", id) + controller.Ctx.Input.SetData("token:company_id", id) +} + +func (controller *BaseController) GetUserCompany() int64 { + idV := controller.Ctx.Input.GetData("token:company_id") + uid, _ := strconv.ParseInt(fmt.Sprint(idV), 10, 64) + return uid +} diff --git a/pkg/port/beego/routers/router.go b/pkg/port/beego/routers/router.go index 7349e61..6fba7a5 100644 --- a/pkg/port/beego/routers/router.go +++ b/pkg/port/beego/routers/router.go @@ -11,7 +11,7 @@ func init() { beego.NSRouter("/login", &controllers.AdminLoginController{}, "POST:Login"), beego.NSRouter("/captcha-init", &controllers.AdminLoginController{}, "POST:CaptchaInit"), beego.NSRouter("/profile", &controllers.AdminLoginController{}, "POST:AdminpPofile"), - beego.NSRouter("/pwd-update", &controllers.AdminLoginController{}, "POST:PwdUpdate"), + // beego.NSRouter("/pwd-update", &controllers.AdminLoginController{}, "POST:PwdUpdate"), ), beego.NSNamespace("/admin", beego.NSRouter("/update", &controllers.AdminUserController{}, "POST:SaveAdminUser"), -- libgit2 0.24.0