作者 yangfu

Merge branch 'dev' of http://gitlab.fjmaimaimai.com/mmm-go/oppmg into dev

@@ -7,6 +7,8 @@ ENV APP_DIR $GOPATH/src/oppmg @@ -7,6 +7,8 @@ ENV APP_DIR $GOPATH/src/oppmg
7 # RUN CGO_ENABLED=0 go install -a std 7 # RUN CGO_ENABLED=0 go install -a std
8 8
9 RUN mkdir -p $APP_DIR 9 RUN mkdir -p $APP_DIR
  10 +RUN /bin/cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime \
  11 + && echo 'Asia/Shanghai' > /etc/timezone
10 # Set the entrypoint 12 # Set the entrypoint
11 #ENTRYPOINT (cd $APP_DIR && ./\src\oppmg) 13 #ENTRYPOINT (cd $APP_DIR && ./\src\oppmg)
12 ADD . $APP_DIR 14 ADD . $APP_DIR
1 机会导向项目 1 机会导向项目
  2 +开发地址
  3 + http://mmm-oppmg-dev.fjmaimaimai.com
@@ -20,6 +20,9 @@ type MyConfig struct { @@ -20,6 +20,9 @@ type MyConfig struct {
20 UcenterBaseUrl string 20 UcenterBaseUrl string
21 UcenterSecret string 21 UcenterSecret string
22 UcenterAppKey string 22 UcenterAppKey string
  23 + FileSavePath string
  24 + FileHost string
  25 + FileHostPath string
23 } 26 }
24 27
25 //MConfig 28 //MConfig
@@ -48,6 +51,9 @@ func RestMyConfig() *MyConfig { @@ -48,6 +51,9 @@ func RestMyConfig() *MyConfig {
48 UcenterBaseUrl: beego.AppConfig.String("ucenter_base_url"), 51 UcenterBaseUrl: beego.AppConfig.String("ucenter_base_url"),
49 UcenterSecret: beego.AppConfig.String("ucenter_secret"), 52 UcenterSecret: beego.AppConfig.String("ucenter_secret"),
50 UcenterAppKey: beego.AppConfig.String("ucenter_app_key"), 53 UcenterAppKey: beego.AppConfig.String("ucenter_app_key"),
  54 + FileSavePath: beego.AppConfig.String("file_save_path"),
  55 + FileHost: beego.AppConfig.String("file_host"),
  56 + FileHostPath: beego.AppConfig.String("file_host_path"),
51 } 57 }
52 return MConfig 58 return MConfig
53 } 59 }
@@ -9,9 +9,11 @@ copyrequestbody = true @@ -9,9 +9,11 @@ copyrequestbody = true
9 #开启应用内文档 9 #开启应用内文档
10 EnableDocs = false 10 EnableDocs = false
11 11
  12 +
12 include "dev.conf" 13 include "dev.conf"
13 include "prod.conf" 14 include "prod.conf"
14 include "local.conf" 15 include "local.conf"
  16 +include "test.conf"
15 17
16 18
17 19
@@ -31,6 +31,11 @@ ucenter_check_alt = "rsF0pL!6DwjBO735" @@ -31,6 +31,11 @@ ucenter_check_alt = "rsF0pL!6DwjBO735"
31 ucenter_base_url = "http://suplus-ucenter-dev.fjmaimaimai.com" 31 ucenter_base_url = "http://suplus-ucenter-dev.fjmaimaimai.com"
32 ucenter_app_key = "39aefef9e22744a3b2d2d3791824ae7b" 32 ucenter_app_key = "39aefef9e22744a3b2d2d3791824ae7b"
33 ucenter_secret = "cykbjnfqgctn" 33 ucenter_secret = "cykbjnfqgctn"
  34 +
  35 +# 上传文件保存路径
  36 +file_save_path = "/var/www/opp/file"
  37 +file_host = "http://mmm-opp-dev.fjmaimaimai.com"
  38 +file_host_path = "/file/opp"
34 # 审批流程修改 消息发布 39 # 审批流程修改 消息发布
35 message_publish = "audit_change" 40 message_publish = "audit_change"
36 #---自定义配置 结束---- 41 #---自定义配置 结束----
  1 +[test]
  2 +config_name = "test"
  3 +#----beego的默认配置 开始---
  4 +#端口号
  5 +httpport = 8080
  6 +#开启应用内监控
  7 +EnableAdmin = false
  8 +AdminPort = 8088
  9 +#---beego的默认配置 结束---
  10 +
  11 +#---自定义配置 开始----
  12 +##数据库连接
  13 +# sqlconn ="${MYSQL_CONN||root:sutianxia2015@tcp(115.29.205.99:3306)/opportunity?charset=utf8&loc=Asia%2FShanghai}"
  14 +mysql_user = "${MYSQL_USER||root}"
  15 +mysql_password = "${MYSQL_PASSWORD||sutianxia2015}"
  16 +mysql_host = "${MYSQL_HOST||115.29.205.99}"
  17 +mysql_port = "${MYSQL_PORT||3306}"
  18 +mysql_db_name = "${MYSQL_DB_NAME||opportunity}"
  19 +##redis相关配置
  20 +redis_add = "${REDIS_HOST||127.0.0.1}"
  21 +redis_add_port = "${REDIS_PORT||6379}"
  22 +redis_auth = ""
  23 +##log相关配置
  24 +##out_put:"console","file"
  25 +log_output = "file"
  26 +log_filename = "${aliyun_logs_access||./log/ability.log}"
  27 +log_level = "${LOG_LEVEL||debug}"
  28 +
  29 +##统一用户中心相关配置
  30 +ucenter_check_alt = "rsF0pL!6DwjBO735"
  31 +ucenter_base_url = "http://suplus-ucenter-test.fjmaimaimai.com"
  32 +ucenter_app_key = "39aefef9e22744a3b2d2d3791824ae7b"
  33 +ucenter_secret = "cykbjnfqgctn"
  34 +
  35 +# 上传文件保存路径
  36 +file_save_path = "/var/www/opp/file"
  37 +file_host = "http://mmm-opp-dev.fjmaimaimai.com"
  38 +file_host_path = "/file/opp"
  39 +# 审批流程修改 消息发布
  40 +message_publish = "audit_change"
  41 +#---自定义配置 结束----
@@ -2,10 +2,15 @@ package controllers @@ -2,10 +2,15 @@ package controllers
2 2
3 import ( 3 import (
4 "encoding/json" 4 "encoding/json"
  5 + "fmt"
5 "oppmg/common/log" 6 "oppmg/common/log"
6 "oppmg/protocol" 7 "oppmg/protocol"
7 serveauth "oppmg/services/auth" 8 serveauth "oppmg/services/auth"
8 "oppmg/storage/redisdata" 9 "oppmg/storage/redisdata"
  10 + "strconv"
  11 + "time"
  12 +
  13 + "github.com/GeeTeam/gt3-golang-sdk/geetest"
9 ) 14 )
10 15
11 type AuthController struct { 16 type AuthController struct {
@@ -67,7 +72,10 @@ func (c *AuthController) Login() { @@ -67,7 +72,10 @@ func (c *AuthController) Login() {
67 if err != nil { 72 if err != nil {
68 log.Error("token 信息记录redis失败") 73 log.Error("token 信息记录redis失败")
69 } 74 }
70 - msg = protocol.NewReturnResponse(logintoken, nil) 75 + data := map[string]interface{}{
  76 + "access": logintoken,
  77 + }
  78 + msg = protocol.NewReturnResponse(data, nil)
71 return 79 return
72 } 80 }
73 81
@@ -113,6 +121,72 @@ func (c *AuthController) Me() { @@ -113,6 +121,72 @@ func (c *AuthController) Me() {
113 userid := c.GetUserId() 121 userid := c.GetUserId()
114 companyid := c.GetCompanyId() 122 companyid := c.GetCompanyId()
115 userinfo, err := serveauth.UserBaseInfo(userid, companyid) 123 userinfo, err := serveauth.UserBaseInfo(userid, companyid)
116 - msg = protocol.NewReturnResponse(userinfo, err) 124 + if err != nil {
  125 + log.Error("获取用户数据失败")
  126 + }
  127 + menus, err := serveauth.GetUserHasMenu(userid, companyid)
  128 + if err != nil {
  129 + log.Error("获取用户菜单")
  130 + }
  131 + companys, err := serveauth.UserHasCompanys(userid)
  132 + if err != nil {
  133 + log.Error("获取用户的公司")
  134 + }
  135 + data := map[string]interface{}{
  136 + "user": userinfo,
  137 + "menus": menus,
  138 + "companys": companys,
  139 + }
  140 + msg = protocol.NewReturnResponse(data, nil)
  141 + return
  142 +}
  143 +
  144 +const (
  145 + captchaID = "48a6ebac4ebc6642d68c217fca33eb4d"
  146 + privateKey = "4f1c085290bec5afdc54df73535fc361"
  147 +)
  148 +
  149 +func (c *AuthController) RegisterGeetest() {
  150 + geetest := geetest.NewGeetestLib(captchaID, privateKey, 2*time.Second)
  151 + status, responseBt := geetest.PreProcess("", "")
  152 + c.SetSession("geetest_status", status)
  153 + c.Ctx.Output.Body(responseBt)
  154 + return
  155 +}
  156 +
  157 +func (c *AuthController) ValidateGeetest() {
  158 + type Parameter struct {
  159 + GeetestChallenge string `form:"geetest_challenge"`
  160 + GeetestValidate string `form:"geetest_validate"`
  161 + GeetestSeccode string `form:"geetest_seccode"`
  162 + }
  163 +
  164 + var (
  165 + param Parameter
  166 + geetestRes bool
  167 + status int
  168 + )
  169 + err := c.ParseForm(&param)
  170 + if err != nil {
  171 + log.Error("解析表单数据失败;%s", err)
  172 + }
  173 + val := c.GetSession("geetest_status")
  174 + status, _ = strconv.Atoi(fmt.Sprint(val))
  175 + geetest := geetest.NewGeetestLib(captchaID, privateKey, 2*time.Second)
  176 + if status == 1 {
  177 + geetestRes = geetest.SuccessValidate(param.GeetestChallenge, param.GeetestValidate, param.GeetestSeccode, "", "")
  178 + } else {
  179 + geetestRes = geetest.FailbackValidate(param.GeetestChallenge, param.GeetestValidate, param.GeetestSeccode)
  180 + }
  181 + res := make(map[string]interface{})
  182 + if geetestRes {
  183 + res["code"] = 0
  184 + res["msg"] = "Success"
  185 + } else {
  186 + res["code"] = -100
  187 + res["msg"] = "Failed"
  188 + }
  189 + responseBt, _ := json.Marshal(res)
  190 + c.Ctx.Output.Body(responseBt)
117 return 191 return
118 } 192 }
@@ -20,14 +20,14 @@ type BaseController struct { @@ -20,14 +20,14 @@ type BaseController struct {
20 20
21 //Prepare 实现beego.ControllerInterface 的接口 21 //Prepare 实现beego.ControllerInterface 的接口
22 func (this *BaseController) Prepare() { 22 func (this *BaseController) Prepare() {
23 - this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")  
24 - this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "*")  
25 - if this.Ctx.Input.Method() == "OPTIONS" {  
26 - this.Ctx.ResponseWriter.WriteHeader(204)  
27 - this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")  
28 - //this.Ctx.WriteString("")  
29 - return  
30 - } 23 + // this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "*")
  24 + // this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "*")
  25 + // if this.Ctx.Input.Method() == "OPTIONS" {
  26 + // this.Ctx.ResponseWriter.WriteHeader(204)
  27 + // this.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
  28 + // //this.Ctx.WriteString("")
  29 + // return
  30 + // }
31 p := this.Ctx.Input.GetData("RouterPattern") 31 p := this.Ctx.Input.GetData("RouterPattern")
32 fmt.Println("====>r:", p) 32 fmt.Println("====>r:", p)
33 } 33 }
@@ -324,7 +324,7 @@ func (c *CompanyController) UserAllowForbid() { @@ -324,7 +324,7 @@ func (c *CompanyController) UserAllowForbid() {
324 c.ResposeJson(msg) 324 c.ResposeJson(msg)
325 }() 325 }()
326 type Parameter struct { 326 type Parameter struct {
327 - UserCompanyIds []int64 `json:"ids"` 327 + UserCompanyIds []int64 `json:"user_company_ids"`
328 Status int `json:"status"` // [1:执行禁用操作][2:执行启用操作] 328 Status int `json:"status"` // [1:执行禁用操作][2:执行启用操作]
329 } 329 }
330 var param Parameter 330 var param Parameter
@@ -385,17 +385,37 @@ func (c *CompanyController) InitCompany() { @@ -385,17 +385,37 @@ func (c *CompanyController) InitCompany() {
385 msg = protocol.BadRequestParam("1") 385 msg = protocol.BadRequestParam("1")
386 return 386 return
387 } 387 }
  388 + if param.CompanyId <= 0 {
  389 + log.Error("公司id为0")
  390 + msg = protocol.BadRequestParam("1")
  391 + return
  392 + }
  393 +
388 var ( 394 var (
389 err error 395 err error
390 ) 396 )
391 if ok := param.IsEnable(); ok { 397 if ok := param.IsEnable(); ok {
  398 + if len(param.CompanyName) == 0 {
  399 + log.Error("公司名称空")
  400 + msg = protocol.BadRequestParam("1")
  401 + return
  402 + }
  403 + if len(param.AdminAccount) == 0 {
  404 + log.Error("人员账号空")
  405 + msg = protocol.BadRequestParam("1")
  406 + return
  407 + }
  408 + if len(param.AdminName) == 0 {
  409 + log.Error("人员名称空")
  410 + msg = protocol.BadRequestParam("1")
  411 + return
  412 + }
392 err = servecompany.InitCompanyInfo(param) 413 err = servecompany.InitCompanyInfo(param)
393 } else if ok := param.IsForbid(); ok { 414 } else if ok := param.IsForbid(); ok {
394 err = servecompany.ForbidCompany(param.CompanyId) 415 err = servecompany.ForbidCompany(param.CompanyId)
395 } else { 416 } else {
396 err = protocol.NewErrWithMessage("1") 417 err = protocol.NewErrWithMessage("1")
397 } 418 }
398 -  
399 msg = protocol.NewReturnResponse(nil, err) 419 msg = protocol.NewReturnResponse(nil, err)
400 return 420 return
401 } 421 }
@@ -420,6 +440,42 @@ func (c *CompanyController) GetCompanyForUCenter() { @@ -420,6 +440,42 @@ func (c *CompanyController) GetCompanyForUCenter() {
420 return 440 return
421 } 441 }
422 442
  443 +//获取用户详情
  444 +//@router /user/info
  445 +func (c *CompanyController) UserDetail() {
  446 + var msg *protocol.ResponseMessage
  447 + defer func() {
  448 + c.ResposeJson(msg)
  449 + }()
  450 + type Parameter struct {
  451 + UserCompanyId int64 `json:"user_company_id"`
  452 + }
  453 + var param Parameter
  454 + if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {
  455 + log.Error("json 解析失败 err:%s", err)
  456 + msg = protocol.BadRequestParam("1")
  457 + return
  458 + }
  459 + userdata, _ := servecompany.GetUserData(param.UserCompanyId)
  460 + departs := servecompany.GetUserDepartment(param.UserCompanyId)
  461 + positions := servecompany.GetUserPosition(param.UserCompanyId)
  462 + roles := servecompany.GetUserRole(param.UserCompanyId)
  463 + type ResponseUserDetail struct {
  464 + protocol.UserInfoBase
  465 + Departs []protocol.DepartmentBase `json:"departs"`
  466 + Positions []protocol.PositionBase `json:"positions"`
  467 + Roles []protocol.RoleBase `json:"roles"`
  468 + }
  469 + data := ResponseUserDetail{
  470 + UserInfoBase: userdata,
  471 + Departs: departs,
  472 + Positions: positions,
  473 + Roles: roles,
  474 + }
  475 + msg = protocol.NewReturnResponse(data, nil)
  476 + return
  477 +}
  478 +
423 //DepartmentUser 获取部门下成员 479 //DepartmentUser 获取部门下成员
424 //@router /department/user [post] 480 //@router /department/user [post]
425 func (c *CompanyController) DepartmentUser() { 481 func (c *CompanyController) DepartmentUser() {
@@ -469,15 +525,6 @@ func (c *CompanyController) CurrentCompanyInfo() { @@ -469,15 +525,6 @@ func (c *CompanyController) CurrentCompanyInfo() {
469 defer func() { 525 defer func() {
470 c.ResposeJson(msg) 526 c.ResposeJson(msg)
471 }() 527 }()
472 - // type Parameter struct {  
473 - // Logo string `json:"string"`  
474 - // }  
475 - // var param Parameter  
476 - // if err := json.Unmarshal(c.Ctx.Input.RequestBody, &param); err != nil {  
477 - // log.Error("json 解析失败 err:%s", err)  
478 - // msg = protocol.BadRequestParam("1")  
479 - // return  
480 - // }  
481 companyid := c.GetCompanyId() 528 companyid := c.GetCompanyId()
482 companybase, err := servecompany.CompanyBaseInfo(companyid) 529 companybase, err := servecompany.CompanyBaseInfo(companyid)
483 msg = protocol.NewReturnResponse(companybase, err) 530 msg = protocol.NewReturnResponse(companybase, err)
  1 +package controllers
  2 +
  3 +import (
  4 + "fmt"
  5 + "io"
  6 + "mime/multipart"
  7 + "oppmg/common/config"
  8 + "oppmg/common/log"
  9 + "oppmg/protocol"
  10 + "oppmg/utils"
  11 + "os"
  12 + "path"
  13 + "path/filepath"
  14 + "time"
  15 +)
  16 +
  17 +//UploadController 文件上传
  18 +type UploadController struct {
  19 + BaseController
  20 +}
  21 +
  22 +type ResponseUploadImage struct {
  23 + Urls []string `json:"url"`
  24 +}
  25 +
  26 +//UploadImage 图片上传
  27 +//@router /image
  28 +func (c *UploadController) UploadImage() {
  29 + var msg *protocol.ResponseMessage
  30 + defer func() {
  31 + c.ResposeJson(msg)
  32 + }()
  33 + filehead, err := c.GetFiles("file")
  34 + if err != nil {
  35 + log.Error("获取上传文件失败:%s", err)
  36 + }
  37 + var rsp ResponseUploadImage
  38 + for i := range filehead {
  39 + hostpath, err := saveFile(filehead[i], "image")
  40 + if err != nil {
  41 + msg = protocol.BadRequestParam("1")
  42 + return
  43 + }
  44 + rsp.Urls = append(rsp.Urls, hostpath)
  45 + }
  46 + msg = protocol.NewReturnResponse(rsp, nil)
  47 + return
  48 +}
  49 +
  50 +func saveFile(fileData *multipart.FileHeader, fileType string) (hostpath string, err error) {
  51 + savepath := filepath.Join(config.MConfig.FileSavePath, fileType)
  52 + os.MkdirAll(savepath, 0777)
  53 + file, err := fileData.Open()
  54 + defer file.Close()
  55 + if err != nil {
  56 + log.Error("文件获取失败%s", err)
  57 + return "", err
  58 + }
  59 + subfix := path.Ext(fileData.Filename)
  60 + mfileName := fmt.Sprint(utils.GenerateIDBySonyflake())
  61 + mfileName = fmt.Sprintf("%d_%s%s", time.Now().Unix(), mfileName, subfix)
  62 + dst, err := os.Create(filepath.Join(savepath, mfileName))
  63 + defer dst.Close()
  64 + if err != nil {
  65 + log.Error("目录访问失败:%s", err)
  66 +
  67 + return "", err
  68 + }
  69 + if _, err := io.Copy(dst, file); err != nil {
  70 + log.Error("文件保存失败:%s", err)
  71 + return "", err
  72 + }
  73 + hostpath = config.MConfig.FileHost + filepath.Join(config.MConfig.FileHostPath, fileType, mfileName)
  74 + return hostpath, nil
  75 +}
1 #!/bin/bash 1 #!/bin/bash
2 export PATH=/root/local/bin:$PATH 2 export PATH=/root/local/bin:$PATH
3 -kubectl -n mmm-suplus-test get pods | grep -q opp 3 +kubectl -n mmm-suplus-test get pods | grep -q mmm-oppmg
4 if [ "$?" == "1" ];then 4 if [ "$?" == "1" ];then
5 - kubectl create -f /tmp/test/opp/opp.yaml --record  
6 - kubectl -n mmm-suplus-test get svc | grep -q opp 5 + kubectl create -f /tmp/test/mmm-go-oppmg/oppmg.yaml --record
  6 + kubectl -n mmm-suplus-test get svc | grep -q mmm-oppmg
7 if [ "$?" == "0" ];then 7 if [ "$?" == "0" ];then
8 - echo "opp service install success!" 8 + echo "mmm-oppmg service install success!"
9 else 9 else
10 - echo "opp service install fail!" 10 + echo "mmm-oppmg service install fail!"
11 fi 11 fi
12 - kubectl -n mmm-suplus-test get pods | grep -q opp 12 + kubectl -n mmm-suplus-test get pods | grep -q mmm-oppmg
13 if [ "$?" == "0" ];then 13 if [ "$?" == "0" ];then
14 - echo "opp deployment install success!" 14 + echo "mmm-oppmg deployment install success!"
15 else 15 else
16 - echo "opp deployment install fail!" 16 + echo "mmm-oppmg deployment install fail!"
17 fi 17 fi
18 else 18 else
19 - kubectl delete -f /tmp/test/opp/opp.yaml  
20 - kubectl -n mmm-suplus-test get svc | grep -q opp 19 + kubectl delete -f /tmp/test/mmm-go-oppmg/oppmg.yaml
  20 + kubectl -n mmm-suplus-test get svc | grep -q mmm-oppmg
21 while [ "$?" == "0" ] 21 while [ "$?" == "0" ]
22 do 22 do
23 - kubectl -n mmm-suplus-test get svc | grep -q opp 23 + kubectl -n mmm-suplus-test get svc | grep -q mmm-oppmg
24 done 24 done
25 - kubectl -n mmm-suplus-test get pods | grep -q opp 25 + kubectl -n mmm-suplus-test get pods | grep -q mmm-oppmg
26 while [ "$?" == "0" ] 26 while [ "$?" == "0" ]
27 do 27 do
28 - kubectl -n mmm-suplus-test get pods | grep -q opp 28 + kubectl -n mmm-suplus-test get pods | grep -q mmm-oppmg
29 done 29 done
30 - kubectl create -f /tmp/test/opp/opp.yaml --record  
31 - kubectl -n mmm-suplus-test get svc | grep -q opp 30 + kubectl create -f /tmp/test/mmm-go-oppmg/oppmg.yaml --record
  31 + kubectl -n mmm-suplus-test get svc | grep -q mmm-oppmg
32 if [ "$?" == "0" ];then 32 if [ "$?" == "0" ];then
33 - echo "opp service update success!" 33 + echo "mmm-oppmg service update success!"
34 else 34 else
35 - echo "opp service update fail!" 35 + echo "mmm-oppmg service update fail!"
36 fi 36 fi
37 - kubectl -n mmm-suplus-test get pods | grep -q opp 37 + kubectl -n mmm-suplus-test get pods | grep -q mmm-oppmg
38 if [ "$?" == "0" ];then 38 if [ "$?" == "0" ];then
39 - echo "opp deployment update success!" 39 + echo "mmm-oppmg deployment update success!"
40 else 40 else
41 - echo "opp deployment update fail!" 41 + echo "mmm-oppmg deployment update fail!"
42 fi 42 fi
43 fi 43 fi
1 apiVersion: v1 1 apiVersion: v1
2 kind: Service 2 kind: Service
3 metadata: 3 metadata:
4 - name: opp 4 + name: mmm-oppmg
5 namespace: mmm-suplus-test 5 namespace: mmm-suplus-test
6 labels: 6 labels:
7 - k8s-app: opp 7 + k8s-app: mmm-oppmg
8 spec: 8 spec:
9 ports: 9 ports:
10 - - name: "http"  
11 - port: 80  
12 - targetPort: 8082 10 + - name: "http"
  11 + port: 80
  12 + targetPort: 8080
13 selector: 13 selector:
14 - k8s-app: opp 14 + k8s-app: mmm-oppmg
15 --- 15 ---
16 apiVersion: extensions/v1beta1 16 apiVersion: extensions/v1beta1
17 kind: Deployment 17 kind: Deployment
18 metadata: 18 metadata:
19 - name: opp 19 + name: mmm-oppmg
20 namespace: mmm-suplus-test 20 namespace: mmm-suplus-test
21 labels: 21 labels:
22 - k8s-app: opp 22 + k8s-app: mmm-oppmg
23 spec: 23 spec:
24 replicas: 1 24 replicas: 1
25 template: 25 template:
26 metadata: 26 metadata:
27 labels: 27 labels:
28 - k8s-app: opp 28 + k8s-app: mmm-oppmg
29 spec: 29 spec:
30 affinity: 30 affinity:
31 nodeAffinity: 31 nodeAffinity:
@@ -43,54 +43,60 @@ spec: @@ -43,54 +43,60 @@ spec:
43 - cn-hangzhou.i-bp1euf5u1ph9kbhtndhb 43 - cn-hangzhou.i-bp1euf5u1ph9kbhtndhb
44 - cn-hangzhou.i-bp1hyp5oips9cdwxxgxy 44 - cn-hangzhou.i-bp1hyp5oips9cdwxxgxy
45 containers: 45 containers:
46 - - name: opp  
47 - image: 192.168.0.243:5000/mmm/opp:test  
48 - imagePullPolicy: Always  
49 - ports:  
50 - - containerPort: 8082  
51 - volumeMounts:  
52 - - mountPath: /opt/logs  
53 - name: accesslogs  
54 - env:  
55 - - name: ENTERPRISE_SERVICE_HOST  
56 - valueFrom:  
57 - configMapKeyRef:  
58 - name: suplus-config  
59 - key: service.enterprise  
60 - - name: MYSQL_HOST  
61 - valueFrom:  
62 - configMapKeyRef:  
63 - name: suplus-config  
64 - key: mysql.host  
65 - - name: MYSQL_PORT  
66 - valueFrom:  
67 - configMapKeyRef:  
68 - name: suplus-config  
69 - key: mysql.port  
70 - - name: MYSQL_USER  
71 - valueFrom:  
72 - configMapKeyRef:  
73 - name: suplus-config  
74 - key: mysql.user  
75 - - name: MYSQL_PASSWORD  
76 - valueFrom:  
77 - configMapKeyRef:  
78 - name: suplus-config  
79 - key: mysql.password  
80 - - name: MYSQL_DB_NAME  
81 - value: "opp_test"  
82 - - name: LOG_LEVEL  
83 - value: "debug"  
84 - - name: ERROR_BASE_CODE  
85 - value: "9"  
86 - - name: ERROR_BASE_CODE_MULTIPLE  
87 - value: "1000"  
88 - - name: RUN_MODE  
89 - value: "prod"  
90 - - name: aliyun_logs_suplus  
91 - value: "stdout"  
92 - - name: aliyun_logs_access  
93 - value: "/opt/logs/app.log" 46 + - name: mmm-oppmg
  47 + image: 192.168.0.243:5000/mmm/mmm-oppmg:dev
  48 + imagePullPolicy: Always
  49 + volumeMounts:
  50 + - mountPath: /opt/logs
  51 + name: accesslogs
  52 + - mountPath: /var/www/oppmg/file
  53 + name: mmmjihuitest2-pvc1
  54 + ports:
  55 + - containerPort: 8080
  56 + env:
  57 + - name: MYSQL_HOST
  58 + valueFrom:
  59 + configMapKeyRef:
  60 + name: suplus-config
  61 + key: mysql.host
  62 + - name: MYSQL_PORT
  63 + valueFrom:
  64 + configMapKeyRef:
  65 + name: suplus-config
  66 + key: mysql.port
  67 + - name: REDIS_HOST
  68 + valueFrom:
  69 + configMapKeyRef:
  70 + name: suplus-config
  71 + key: redis.ip
  72 + - name: REDIS_PORT
  73 + valueFrom:
  74 + configMapKeyRef:
  75 + name: suplus-config
  76 + key: redis.port
  77 + - name: MYSQL_USER
  78 + valueFrom:
  79 + configMapKeyRef:
  80 + name: suplus-config
  81 + key: mysql.user
  82 + - name: MYSQL_PASSWORD
  83 + valueFrom:
  84 + configMapKeyRef:
  85 + name: suplus-config
  86 + key: mysql.password
  87 + - name: MYSQL_DB_NAME
  88 + value: "opportunity_test"
  89 + - name: RUN_MODE
  90 + value: "test"
  91 + - name: LOG_LEVEL
  92 + value: "debug"
  93 + - name: aliyun_logs_suplusfile
  94 + value: "stdout"
  95 + - name: aliyun_logs_access
  96 + value: " /opt/logs/app.log"
94 volumes: 97 volumes:
95 - - name: accesslogs  
96 - emptyDir: {}  
  98 + - name: accesslogs
  99 + emptyDir: {}
  100 + - name: mmmjihuitest2-pvc1
  101 + persistentVolumeClaim:
  102 + claimName: mmmjihuitest2-pvc
@@ -4,6 +4,7 @@ go 1.13 @@ -4,6 +4,7 @@ go 1.13
4 4
5 require ( 5 require (
6 github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2 6 github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2
  7 + github.com/GeeTeam/gt3-golang-sdk v0.0.0-20190704102600-e89c6d964c8f
7 github.com/astaxie/beego v1.11.1 8 github.com/astaxie/beego v1.11.1
8 github.com/dgrijalva/jwt-go v3.2.0+incompatible 9 github.com/dgrijalva/jwt-go v3.2.0+incompatible
9 github.com/go-redis/redis v6.15.6+incompatible 10 github.com/go-redis/redis v6.15.6+incompatible
1 github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2 h1:StMrA6UQ5Cm6206DxXGuV/NMqSIOIDoMXMYt8JPe1lE= 1 github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2 h1:StMrA6UQ5Cm6206DxXGuV/NMqSIOIDoMXMYt8JPe1lE=
2 github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2/go.mod h1:EfRHD2k+Kd7ijnqlwOrH1IifwgWB9yYJ0pdXtBZmlpU= 2 github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2/go.mod h1:EfRHD2k+Kd7ijnqlwOrH1IifwgWB9yYJ0pdXtBZmlpU=
  3 +github.com/GeeTeam/gt3-golang-sdk v0.0.0-20190704102600-e89c6d964c8f h1:FpIAcTBZpoM5uD2+zKbTyT+6Oz0efWw4ZWnr8FtdQ+g=
  4 +github.com/GeeTeam/gt3-golang-sdk v0.0.0-20190704102600-e89c6d964c8f/go.mod h1:vqCh/LExdPmL5SULXE/9DHbuE4t3iLkzRYoNGxEvg/o=
3 github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0= 5 github.com/Knetic/govaluate v3.0.0+incompatible/go.mod h1:r7JcOSlj0wfOMncg0iLm8Leh48TZaKVeNIfJntJ2wa0=
4 github.com/astaxie/beego v1.11.1 h1:6DESefxW5oMcRLFRKi53/6exzup/IR6N4EzzS1n6CnQ= 6 github.com/astaxie/beego v1.11.1 h1:6DESefxW5oMcRLFRKi53/6exzup/IR6N4EzzS1n6CnQ=
5 github.com/astaxie/beego v1.11.1/go.mod h1:i69hVzgauOPSw5qeyF4GVZhn7Od0yG5bbCGzmhbWxgQ= 7 github.com/astaxie/beego v1.11.1/go.mod h1:i69hVzgauOPSw5qeyF4GVZhn7Od0yG5bbCGzmhbWxgQ=
@@ -12,10 +12,14 @@ import ( @@ -12,10 +12,14 @@ import (
12 _ "github.com/go-sql-driver/mysql" 12 _ "github.com/go-sql-driver/mysql"
13 ) 13 )
14 14
15 -func main() { 15 +func init() {
  16 + beego.BConfig.WebConfig.Session.SessionOn = true
16 common.ResetCommonConfig() 17 common.ResetCommonConfig()
17 log.Debug("加载配置%s", config.MConfig.ConfigName) 18 log.Debug("加载配置%s", config.MConfig.ConfigName)
18 orm.RegisterDataBase("default", "mysql", config.MConfig.SqlConn) 19 orm.RegisterDataBase("default", "mysql", config.MConfig.SqlConn)
  20 +}
  21 +
  22 +func main() {
19 // orm.Debug = true 23 // orm.Debug = true
20 // if beego.BConfig.RunMode == "dev" { 24 // if beego.BConfig.RunMode == "dev" {
21 // beego.BConfig.WebConfig.DirectoryIndex = true 25 // beego.BConfig.WebConfig.DirectoryIndex = true
@@ -6,6 +6,7 @@ import ( @@ -6,6 +6,7 @@ import (
6 "oppmg/protocol" 6 "oppmg/protocol"
7 serveauth "oppmg/services/auth" 7 serveauth "oppmg/services/auth"
8 "oppmg/storage/redisdata" 8 "oppmg/storage/redisdata"
  9 + "strings"
9 10
10 "github.com/astaxie/beego" 11 "github.com/astaxie/beego"
11 12
@@ -38,11 +39,17 @@ var AuthToken = func(ctx *context.Context) { @@ -38,11 +39,17 @@ var AuthToken = func(ctx *context.Context) {
38 mtoken *serveauth.MyToken 39 mtoken *serveauth.MyToken
39 ) 40 )
40 accesstoken := ctx.Input.Header(protocol.HeaderAccessToken) 41 accesstoken := ctx.Input.Header(protocol.HeaderAccessToken)
41 - // refreshToken := ctx.Input.Header(protocol.HeaderRefreshToken)  
42 - mtoken, err = serveauth.ValidJWTToken(accesstoken) 42 + //解出需要的jwt串 例:头【Authorization】:Bearer 123token456
  43 + s := strings.Split(accesstoken, "\u0020")
  44 + // strings.TrimSpace()
  45 + if len(s) > 0 {
  46 + accesstoken = s[len(s)-1]
  47 + }
  48 + fmt.Println("===>", accesstoken)
43 if accesstoken == "123456" && beego.BConfig.RunMode != "prod" { 49 if accesstoken == "123456" && beego.BConfig.RunMode != "prod" {
44 return 50 return
45 } 51 }
  52 + mtoken, err = serveauth.ValidJWTToken(accesstoken)
46 if err == nil { 53 if err == nil {
47 storetoken, err = redisdata.GetLoginToken(mtoken.UID) 54 storetoken, err = redisdata.GetLoginToken(mtoken.UID)
48 if err != nil { 55 if err != nil {
@@ -84,7 +91,7 @@ var AllowOption = func(ctx *context.Context) { @@ -84,7 +91,7 @@ var AllowOption = func(ctx *context.Context) {
84 AllowHeaders: []string{"Origin", "Accept", "Content-Type", "Authorization", 91 AllowHeaders: []string{"Origin", "Accept", "Content-Type", "Authorization",
85 "x-mmm-cid", "x-mmm-uid", "x-mmm-accesstoken", "x-mmm-refreshtoken", "x-requested-with"}, //允许的头部信息 92 "x-mmm-cid", "x-mmm-uid", "x-mmm-accesstoken", "x-mmm-refreshtoken", "x-requested-with"}, //允许的头部信息
86 ExposeHeaders: []string{"Content-Length"}, //允许暴露的头信息 93 ExposeHeaders: []string{"Content-Length"}, //允许暴露的头信息
87 - AllowCredentials: false, //不允许共享AuthTuffic证书 94 + AllowCredentials: true, //不允许共享AuthTuffic证书
88 AllowAllOrigins: true, //允许的请求来源 95 AllowAllOrigins: true, //允许的请求来源
89 }) 96 })
90 f(ctx) 97 f(ctx)
@@ -13,6 +13,7 @@ type UserCompany struct { @@ -13,6 +13,7 @@ type UserCompany struct {
13 Id int64 `orm:"column(id);auto" description:"唯一标识"` 13 Id int64 `orm:"column(id);auto" description:"唯一标识"`
14 CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"` 14 CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
15 UserId int64 `orm:"column(user_id)" description:"表user.id 用户编号"` 15 UserId int64 `orm:"column(user_id)" description:"表user.id 用户编号"`
  16 + NickName string `orm:"column(nick_name)"`
16 ChanceTotal int `orm:"column(chance_total)" description:"发表机会数"` 17 ChanceTotal int `orm:"column(chance_total)" description:"发表机会数"`
17 CommentTotal int `orm:"column(comment_total)" description:"发表评论总数"` 18 CommentTotal int `orm:"column(comment_total)" description:"发表评论总数"`
18 CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"` 19 CreateAt time.Time `orm:"column(create_at);type(timestamp)" description:"创建时间"`
@@ -53,6 +54,15 @@ func init() { @@ -53,6 +54,15 @@ func init() {
53 orm.RegisterModel(new(UserCompany)) 54 orm.RegisterModel(new(UserCompany))
54 } 55 }
55 56
  57 +func GetUserCompanyById(id int64) (v *UserCompany, err error) {
  58 + o := orm.NewOrm()
  59 + v = &UserCompany{Id: id}
  60 + if err = o.Read(v); err == nil {
  61 + return v, nil
  62 + }
  63 + return nil, err
  64 +}
  65 +
56 // AddUserCompany insert a new UserCompany into database and returns 66 // AddUserCompany insert a new UserCompany into database and returns
57 // last inserted Id on success. 67 // last inserted Id on success.
58 func AddUserCompany(m *UserCompany, o orm.Ormer) (id int64, err error) { 68 func AddUserCompany(m *UserCompany, o orm.Ormer) (id int64, err error) {
@@ -66,16 +76,19 @@ func AddUserCompany(m *UserCompany, o orm.Ormer) (id int64, err error) { @@ -66,16 +76,19 @@ func AddUserCompany(m *UserCompany, o orm.Ormer) (id int64, err error) {
66 76
67 // UpdateUserCompany updates UserCompany by Id and returns error if 77 // UpdateUserCompany updates UserCompany by Id and returns error if
68 // the record to be updated doesn't exist 78 // the record to be updated doesn't exist
69 -func UpdateUserCompanyById(m *UserCompany) (err error) {  
70 - o := orm.NewOrm()  
71 - v := UserCompany{Id: m.Id}  
72 - // ascertain id exists in the database  
73 - if err = o.Read(&v); err == nil {  
74 - var num int64  
75 - if num, err = o.Update(m); err == nil {  
76 - fmt.Println("Number of records updated in database:", num)  
77 - } 79 +func UpdateUserCompanyById(m *UserCompany, col []string, om ...orm.Ormer) (err error) {
  80 + var o orm.Ormer
  81 + if len(om) > 0 {
  82 + o = om[0]
  83 + } else {
  84 + o = orm.NewOrm()
  85 + }
  86 + var num int64
  87 + m.UpdateAt = time.Now()
  88 + if num, err = o.Update(m, col...); err == nil {
  89 + fmt.Println("Number of records updated in database:", num)
78 } 90 }
  91 +
79 return 92 return
80 } 93 }
81 94
@@ -8,8 +8,8 @@ import ( @@ -8,8 +8,8 @@ import (
8 ) 8 )
9 9
10 type UserDepartment struct { 10 type UserDepartment struct {
11 - Id int64 `orm:"column(id);auto" description:"主键"`  
12 - UserId int64 `orm:"column(user_id)" description:"用户id"` 11 + Id int64 `orm:"column(id);auto" description:"主键"`
  12 + //UserId int64 `orm:"column(user_id)" description:"用户id"`
13 CompanyId int64 `orm:"column(company_id)" description:"公司id"` 13 CompanyId int64 `orm:"column(company_id)" description:"公司id"`
14 DepartmentId int64 `orm:"column(department_id)" description:"部门id"` 14 DepartmentId int64 `orm:"column(department_id)" description:"部门id"`
15 CreateTime time.Time `orm:"column(create_time);type(timestamp);null" description:"创建时间"` 15 CreateTime time.Time `orm:"column(create_time);type(timestamp);null" description:"创建时间"`
@@ -8,8 +8,8 @@ import ( @@ -8,8 +8,8 @@ import (
8 ) 8 )
9 9
10 type UserPosition struct { 10 type UserPosition struct {
11 - Id int64 `orm:"column(id)" description:"唯一键值"`  
12 - UserId int64 `orm:"column(user_id)" description:"表user.id 用户编号"` 11 + Id int64 `orm:"column(id)" description:"唯一键值"`
  12 + //UserId int64 `orm:"column(user_id)" description:"表user.id 用户编号"`
13 PositionId int64 `orm:"column(position_id)" description:"表position.id 职位编号"` 13 PositionId int64 `orm:"column(position_id)" description:"表position.id 职位编号"`
14 CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"` 14 CreateAt time.Time `orm:"column(create_at);type(timestamp);null" description:"创建时间"`
15 CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"` 15 CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
@@ -9,7 +9,6 @@ import ( @@ -9,7 +9,6 @@ import (
9 type UserRole struct { 9 type UserRole struct {
10 Id int `orm:"column(id)"` 10 Id int `orm:"column(id)"`
11 RoleId int64 `orm:"column(role_id)"` 11 RoleId int64 `orm:"column(role_id)"`
12 - UserId int64 `orm:"column(user_id)"`  
13 EnableStatus int8 `orm:"column(enable_status)" description:"是否有效"` 12 EnableStatus int8 `orm:"column(enable_status)" description:"是否有效"`
14 CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"` 13 CompanyId int64 `orm:"column(company_id)" description:"表company.id 公司编号"`
15 UserCompanyId int64 `orm:"column(user_company_id)"` 14 UserCompanyId int64 `orm:"column(user_company_id)"`
@@ -90,7 +90,7 @@ type Template struct { @@ -90,7 +90,7 @@ type Template struct {
90 Code string `json:"code" valid:"Required; MaxSize(6)"` 90 Code string `json:"code" valid:"Required; MaxSize(6)"`
91 ChanceTypeId int `json:"chanceTypeId" valid:"Required;"` //机会类型编号 91 ChanceTypeId int `json:"chanceTypeId" valid:"Required;"` //机会类型编号
92 Name string `json:"name" valid:"Required;"` 92 Name string `json:"name" valid:"Required;"`
93 - Doc string `json:"doc" valid:"Required;"` 93 + Doc string `json:"doc"`
94 Icon string `json:"icon" valid:"Required;"` 94 Icon string `json:"icon" valid:"Required;"`
95 InputList []*InputElement `json:"inputList" valid:"Required;"` 95 InputList []*InputElement `json:"inputList" valid:"Required;"`
96 } 96 }
@@ -55,7 +55,7 @@ type ResponseMeInfo struct { @@ -55,7 +55,7 @@ type ResponseMeInfo struct {
55 Companyid int64 `json:"company_id"` 55 Companyid int64 `json:"company_id"`
56 Companyname string `json:"company_name"` 56 Companyname string `json:"company_name"`
57 Logo string `json:"logo"` 57 Logo string `json:"logo"`
58 - Companys []MeCompany `json:"companys"` 58 + Companys []MeCompany `json:"-"`
59 // Menu 59 // Menu
60 } 60 }
61 61
@@ -43,7 +43,7 @@ type PositionBase struct { @@ -43,7 +43,7 @@ type PositionBase struct {
43 //DepartUserBase 下拉选择列表-部门下的人员 43 //DepartUserBase 下拉选择列表-部门下的人员
44 type DepartUserBase struct { 44 type DepartUserBase struct {
45 UserCompanyId int64 `json:"id" orm:"column(user_company_id)"` 45 UserCompanyId int64 `json:"id" orm:"column(user_company_id)"`
46 - Name string `json:"name" orm:"-"` 46 + NickName string `json:"name" orm:"column(nick_name)"`
47 } 47 }
48 48
49 //部门和人员混合 49 //部门和人员混合
@@ -51,3 +51,9 @@ type DepartAndUser struct { @@ -51,3 +51,9 @@ type DepartAndUser struct {
51 Departments []DepartmentBase `json:"departments"` 51 Departments []DepartmentBase `json:"departments"`
52 Members []DepartmentMember `json:"members"` 52 Members []DepartmentMember `json:"members"`
53 } 53 }
  54 +
  55 +type UserInfoBase struct {
  56 + UserCompanyId int64 `json:"user_company_id"`
  57 + Name string `json:"name"`
  58 + Phone string `json:"phone"`
  59 +}
@@ -89,7 +89,7 @@ type RequestUserAdd struct { @@ -89,7 +89,7 @@ type RequestUserAdd struct {
89 89
90 //RequestUserEdit 编辑用户 90 //RequestUserEdit 编辑用户
91 type RequestUserEdit struct { 91 type RequestUserEdit struct {
92 - ID int64 `json:"id"` 92 + UserCompanyID int64 `json:"user_company_id"`
93 RequestUserAdd 93 RequestUserAdd
94 } 94 }
95 95
@@ -123,9 +123,9 @@ type ResponseCompanyBase struct { @@ -123,9 +123,9 @@ type ResponseCompanyBase struct {
123 123
124 //CenterCompanyInfo 统一用户中心调用的公司数据 124 //CenterCompanyInfo 统一用户中心调用的公司数据
125 type CenterCompanyInfo struct { 125 type CenterCompanyInfo struct {
126 - CompanyId int64 `json:"company_id"` //总后台的公司id  
127 - CompanyName string `json:"company_name"` //  
128 - AdminId int64 `json:"admin_id"` //统一用户中心的用户id 126 + CompanyId int64 `json:"company_id"` //总后台的公司id
  127 + CompanyName string `json:"company_name"` //
  128 + // AdminId int64 `json:"admin_id"` //统一用户中心的用户id
129 AdminAccount string `json:"admin_account"` 129 AdminAccount string `json:"admin_account"`
130 AdminName string `json:"admin_name"` 130 AdminName string `json:"admin_name"`
131 Status int8 `json:"status"` //公司的状态 【1:启用】【2:禁用】 131 Status int8 `json:"status"` //公司的状态 【1:启用】【2:禁用】
1 package protocol 1 package protocol
2 2
  3 +var NullData = struct{}{}
  4 +
3 //CustomErrParse 解析自定义错误结构体 5 //CustomErrParse 解析自定义错误结构体
4 type CustomErrParse interface { 6 type CustomErrParse interface {
5 ParseToMessage() *ResponseMessage 7 ParseToMessage() *ResponseMessage
@@ -37,7 +39,7 @@ func NewMessage(code string) *ResponseMessage { @@ -37,7 +39,7 @@ func NewMessage(code string) *ResponseMessage {
37 rsp := &ResponseMessage{ 39 rsp := &ResponseMessage{
38 Errno: transformCode(ecode.Errno), 40 Errno: transformCode(ecode.Errno),
39 Errmsg: ecode.Errmsg, 41 Errmsg: ecode.Errmsg,
40 - Data: nil, 42 + Data: NullData,
41 } 43 }
42 return rsp 44 return rsp
43 } 45 }
@@ -89,8 +91,12 @@ func SearchErr(code string) ErrorCode { @@ -89,8 +91,12 @@ func SearchErr(code string) ErrorCode {
89 //NewReturnResponse 控制层响应返回 91 //NewReturnResponse 控制层响应返回
90 func NewReturnResponse(data interface{}, eRR error) (msg *ResponseMessage) { 92 func NewReturnResponse(data interface{}, eRR error) (msg *ResponseMessage) {
91 // var msg *ResponseMessage 93 // var msg *ResponseMessage
  94 + if data == nil {
  95 + data = NullData
  96 + }
92 if eRR == nil { 97 if eRR == nil {
93 msg = NewMessage("0") 98 msg = NewMessage("0")
  99 +
94 msg.Data = data 100 msg.Data = data
95 return msg 101 return msg
96 } 102 }
@@ -108,6 +114,9 @@ func BadRequestParam(code string) *ResponseMessage { @@ -108,6 +114,9 @@ func BadRequestParam(code string) *ResponseMessage {
108 114
109 //NewPageDataResponse 控制层分页数据响应返回 115 //NewPageDataResponse 控制层分页数据响应返回
110 func NewPageDataResponse(data interface{}, eRR error) (msg *ResponseMessage) { 116 func NewPageDataResponse(data interface{}, eRR error) (msg *ResponseMessage) {
  117 + if data == nil {
  118 + data = NullData
  119 + }
111 if eRR != nil { 120 if eRR != nil {
112 if x, ok := eRR.(CustomErrParse); ok { 121 if x, ok := eRR.(CustomErrParse); ok {
113 return x.ParseToMessage() 122 return x.ParseToMessage()
@@ -2,7 +2,7 @@ package protocol @@ -2,7 +2,7 @@ package protocol
2 2
3 var errmessge ErrorMap = map[string]string{ 3 var errmessge ErrorMap = map[string]string{
4 //操作 4 //操作
5 - "0": "成功", 5 + "0": "ok",
6 "1": "网络连接无响应", 6 "1": "网络连接无响应",
7 //角色相关 7 //角色相关
8 "10001": "请先删除该分组下的其他角色", 8 "10001": "请先删除该分组下的其他角色",
@@ -46,10 +46,11 @@ func init() { @@ -46,10 +46,11 @@ func init() {
46 beego.NSRouter("/edit", &controllers.CompanyController{}, "post:UserEdit"), 46 beego.NSRouter("/edit", &controllers.CompanyController{}, "post:UserEdit"),
47 beego.NSRouter("/delete", &controllers.CompanyController{}, "post:UserDelete"), 47 beego.NSRouter("/delete", &controllers.CompanyController{}, "post:UserDelete"),
48 beego.NSRouter("/allow_forbid", &controllers.CompanyController{}, "post:UserAllowForbid"), 48 beego.NSRouter("/allow_forbid", &controllers.CompanyController{}, "post:UserAllowForbid"),
  49 + beego.NSRouter("/info", &controllers.CompanyController{}, "post:UserDetail"),
49 ), 50 ),
50 beego.NSNamespace("/auth", 51 beego.NSNamespace("/auth",
51 beego.NSRouter("/change_company", &controllers.AuthController{}, "post:ChangeCompany"), 52 beego.NSRouter("/change_company", &controllers.AuthController{}, "post:ChangeCompany"),
52 - beego.NSRouter("/refresh_token", &controllers.AuthController{}, "post:RefreshToken"), 53 + //beego.NSRouter("/refresh_token", &controllers.AuthController{}, "post:RefreshToken"),
53 beego.NSRouter("/me", &controllers.AuthController{}, "post:Me"), 54 beego.NSRouter("/me", &controllers.AuthController{}, "post:Me"),
54 ), 55 ),
55 beego.NSNamespace("/bulletin", 56 beego.NSNamespace("/bulletin",
@@ -80,12 +81,17 @@ func init() { @@ -80,12 +81,17 @@ func init() {
80 beego.NSRouter("/deleteCategory", &controllers.TemplateController{}, "post:TemplateDeleteCategory"), 81 beego.NSRouter("/deleteCategory", &controllers.TemplateController{}, "post:TemplateDeleteCategory"),
81 beego.NSRouter("/sortCategory", &controllers.TemplateController{}, "post:CategoryEditSort"), 82 beego.NSRouter("/sortCategory", &controllers.TemplateController{}, "post:CategoryEditSort"),
82 ), 83 ),
  84 + beego.NSNamespace("/upload",
  85 + beego.NSRouter("/image", &controllers.UploadController{}, "post:UploadImage"),
  86 + ),
83 ) 87 )
84 88
85 nsAuth := beego.NewNamespace("/auth", 89 nsAuth := beego.NewNamespace("/auth",
86 beego.NSBefore(middleware.AllowOption), 90 beego.NSBefore(middleware.AllowOption),
87 beego.NSBefore(middleware.LogRequestData), 91 beego.NSBefore(middleware.LogRequestData),
88 beego.NSRouter("/login", &controllers.AuthController{}, "post:Login"), 92 beego.NSRouter("/login", &controllers.AuthController{}, "post:Login"),
  93 + beego.NSRouter("/startCaptcha", &controllers.AuthController{}, "post:RegisterGeetest"),
  94 + beego.NSRouter("/verifyCaptcha", &controllers.AuthController{}, "post:ValidateGeetest"),
89 ) 95 )
90 nsUcenter := beego.NewNamespace("/ucenter", 96 nsUcenter := beego.NewNamespace("/ucenter",
91 beego.NSBefore(middleware.LogRequestData), 97 beego.NSBefore(middleware.LogRequestData),
@@ -96,7 +102,6 @@ func init() { @@ -96,7 +102,6 @@ func init() {
96 beego.AddNamespace(nsV1) 102 beego.AddNamespace(nsV1)
97 beego.AddNamespace(nsAuth) 103 beego.AddNamespace(nsAuth)
98 beego.AddNamespace(nsUcenter) 104 beego.AddNamespace(nsUcenter)
99 -  
100 nsTest := beego.NewNamespace("/test", 105 nsTest := beego.NewNamespace("/test",
101 beego.NSCond(func(ctx *context.Context) bool { 106 beego.NSCond(func(ctx *context.Context) bool {
102 if beego.BConfig.RunMode != "prod" { 107 if beego.BConfig.RunMode != "prod" {
@@ -108,4 +113,5 @@ func init() { @@ -108,4 +113,5 @@ func init() {
108 ) 113 )
109 beego.AddNamespace(nsTest) 114 beego.AddNamespace(nsTest)
110 beego.SetStaticPath("/log", beego.AppConfig.String("log_filename")) 115 beego.SetStaticPath("/log", beego.AppConfig.String("log_filename"))
  116 + beego.SetStaticPath("/file/opp", beego.AppConfig.String("file_save_path"))
111 } 117 }
@@ -3,7 +3,6 @@ package auth @@ -3,7 +3,6 @@ package auth
3 import ( 3 import (
4 "crypto/sha1" 4 "crypto/sha1"
5 "encoding/hex" 5 "encoding/hex"
6 - "encoding/json"  
7 "fmt" 6 "fmt"
8 "io" 7 "io"
9 "oppmg/common/log" 8 "oppmg/common/log"
@@ -201,51 +200,31 @@ func LoginAuthByUCenter(account, password string) (protocol.LoginAuthToken, erro @@ -201,51 +200,31 @@ func LoginAuthByUCenter(account, password string) (protocol.LoginAuthToken, erro
201 log.Debug("no company") 200 log.Debug("no company")
202 return logintoken, protocol.NewErrWithMessage("10022") 201 return logintoken, protocol.NewErrWithMessage("10022")
203 } 202 }
204 - companyid = companys[0].Id  
205 - // var uclientReturn *ucenter.ResponseLogin  
206 - // uclientReturn, err = requestUCenterLogin(account, password)  
207 - // if err != nil {  
208 - // return logintoken, protocol.NewErrWithMessage("10021")  
209 - // }  
210 - // //更新用户数据  
211 - // _ = uclientReturn  
212 - // userdata.Accid = uclientReturn.Data.Accid  
213 - // userdata.Icon = uclientReturn.Data.Avatar  
214 - // userdata.ImToken = uclientReturn.Data.Imtoken  
215 - // userdata.NickName = uclientReturn.Data.NickName  
216 - // userdata.CsAccount = uclientReturn.Data.CustomerAccount  
217 - // userdata.LastLoginTime = time.Now()  
218 - // err = models.UpdateUserById(userdata, []string{"Accid", "Icon", "ImToken", "NickName", "CsAccount", "LastLoginTime"})  
219 - // if err != nil {  
220 - // log.Error("更新用户数据失败:%s", err)  
221 - // }  
222 - logintoken, _ = GenerateAuthToken(userdata.Id, companyid)  
223 - return logintoken, err  
224 -}  
225 -  
226 -func requestUCenterLogin(account, password string) (*ucenter.ResponseLogin, error) {  
227 - var uclientReturn *ucenter.ResponseLogin  
228 - param := ucenter.RequesLogin{  
229 - Type: 1,  
230 - Phone: account,  
231 - Password: password, 203 + //获取上一次登录的公司
  204 + uAuth, err := models.GetUserAuthByUser(userdata.Id)
  205 + if err == nil {
  206 + companyid = uAuth.CurrentCompanyId
  207 + } else {
  208 + companyid = companys[0].Id
232 } 209 }
233 - uclient := ucenter.NewUCenterClient()  
234 - btBody, err := uclient.Call(param) 210 + var uclientReturn *ucenter.ResponseLogin
  211 + uclientReturn, err = ucenter.RequestUCenterLogin(account, password)
235 if err != nil { 212 if err != nil {
236 - log.Error("统一用户中心请求失败 err:%s", err)  
237 - return nil, protocol.NewErrWithMessage("1") 213 + return logintoken, protocol.NewErrWithMessage("10021")
238 } 214 }
239 - err = json.Unmarshal(btBody, &uclientReturn) 215 + //更新用户数据
  216 + userdata.Accid = uclientReturn.Data.Accid
  217 + userdata.Icon = uclientReturn.Data.Avatar
  218 + userdata.ImToken = uclientReturn.Data.Imtoken
  219 + userdata.NickName = uclientReturn.Data.NickName
  220 + userdata.CsAccount = uclientReturn.Data.CustomerAccount
  221 + userdata.LastLoginTime = time.Now()
  222 + err = models.UpdateUserById(userdata, []string{"Accid", "Icon", "ImToken", "NickName", "CsAccount", "LastLoginTime"})
240 if err != nil { 223 if err != nil {
241 - log.Error("解析统一用户中心响应失败 err:%s", err)  
242 - return nil, protocol.NewErrWithMessage("1")  
243 - }  
244 - if !(uclientReturn.Code == ucenter.ResponseCode0 &&  
245 - uclientReturn.Msg == ucenter.ResponseMsgOk) {  
246 - return nil, protocol.NewErrWithMessage("10021") 224 + log.Error("更新用户数据失败:%s", err)
247 } 225 }
248 - return uclientReturn, nil 226 + logintoken, _ = GenerateAuthToken(userdata.Id, companyid)
  227 + return logintoken, err
249 } 228 }
250 229
251 type companybase struct { 230 type companybase struct {
@@ -286,9 +265,9 @@ func getUserCompanyReal(userid int64) ([]companybase, error) { @@ -286,9 +265,9 @@ func getUserCompanyReal(userid int64) ([]companybase, error) {
286 265
287 func UserBaseInfo(userid, companyid int64) (protocol.ResponseMeInfo, error) { 266 func UserBaseInfo(userid, companyid int64) (protocol.ResponseMeInfo, error) {
288 var ( 267 var (
289 - err error  
290 - userinfo *models.User  
291 - companylist []companybase 268 + err error
  269 + userinfo *models.User
  270 +
292 meInfo protocol.ResponseMeInfo 271 meInfo protocol.ResponseMeInfo
293 currentCompany *models.Company 272 currentCompany *models.Company
294 ) 273 )
@@ -302,11 +281,7 @@ func UserBaseInfo(userid, companyid int64) (protocol.ResponseMeInfo, error) { @@ -302,11 +281,7 @@ func UserBaseInfo(userid, companyid int64) (protocol.ResponseMeInfo, error) {
302 log.Error("GetCompanyById(%d) err:%s", companyid, err) 281 log.Error("GetCompanyById(%d) err:%s", companyid, err)
303 return meInfo, protocol.NewErrWithMessage("1", err) 282 return meInfo, protocol.NewErrWithMessage("1", err)
304 } 283 }
305 - companylist, err = getUserCompanyReal(userid)  
306 - if err != nil {  
307 - log.Error("getUserCompanyReal(%d) err:%s", userid, err)  
308 - return meInfo, protocol.NewErrWithMessage("1", err)  
309 - } 284 +
310 meInfo = protocol.ResponseMeInfo{ 285 meInfo = protocol.ResponseMeInfo{
311 NickName: userinfo.NickName, 286 NickName: userinfo.NickName,
312 Icon: userinfo.Icon, 287 Icon: userinfo.Icon,
@@ -314,12 +289,42 @@ func UserBaseInfo(userid, companyid int64) (protocol.ResponseMeInfo, error) { @@ -314,12 +289,42 @@ func UserBaseInfo(userid, companyid int64) (protocol.ResponseMeInfo, error) {
314 Companyname: currentCompany.Name, 289 Companyname: currentCompany.Name,
315 Logo: currentCompany.Logo, 290 Logo: currentCompany.Logo,
316 } 291 }
  292 +
  293 + return meInfo, nil
  294 +}
  295 +
  296 +func UserHasCompanys(userid int64) ([]protocol.MeCompany, error) {
  297 + var (
  298 + companylist []companybase
  299 + err error
  300 + mecompanys []protocol.MeCompany
  301 + )
  302 + companylist, err = getUserCompanyReal(userid)
  303 + if err != nil {
  304 + log.Error("getUserCompanyReal(%d) err:%s", userid, err)
  305 + return nil, protocol.NewErrWithMessage("1", err)
  306 + }
317 for _, v := range companylist { 307 for _, v := range companylist {
318 t := protocol.MeCompany{ 308 t := protocol.MeCompany{
319 Id: v.Id, 309 Id: v.Id,
320 Name: v.Name, 310 Name: v.Name,
321 } 311 }
322 - meInfo.Companys = append(meInfo.Companys, t) 312 + mecompanys = append(mecompanys, t)
323 } 313 }
324 - return meInfo, nil 314 + return mecompanys, nil
  315 +}
  316 +
  317 +func GetUserHasMenu(userid, companyid int64) ([]protocol.PermissionItem, error) {
  318 + const datasql string = `SELECT id,name,icon,parent_id,senior_status,sort,code
  319 + FROM menu WHERE enabled=1 ORDER BY sort `
  320 + var (
  321 + list []protocol.PermissionItem
  322 + err error
  323 + )
  324 + err = utils.ExecuteQueryAll(&list, datasql)
  325 + if err != nil {
  326 + log.Error("EXECUTE SQL err:%s", err)
  327 + return nil, protocol.NewErrWithMessage("1")
  328 + }
  329 + return list, nil
325 } 330 }
1 package company 1 package company
2 2
3 import ( 3 import (
4 - "fmt"  
5 "oppmg/common/log" 4 "oppmg/common/log"
6 "oppmg/models" 5 "oppmg/models"
7 "oppmg/protocol" 6 "oppmg/protocol"
  7 + "oppmg/services/ucenter"
8 "time" 8 "time"
9 9
10 "github.com/astaxie/beego/orm" 10 "github.com/astaxie/beego/orm"
11 ) 11 )
12 12
13 -// type CenterCompanyInfo struct {  
14 -// CompanyId int64  
15 -// CompanyName string  
16 -// AdminId int64  
17 -// AdminAccount string  
18 -// AdminName string  
19 -// }  
20 -  
21 -// func GetCenterCompanyInfo(companyid int64) (CenterCompanyInfo, error) {  
22 -  
23 -// //TODO 调用统一用户中心的数据  
24 -// data := CenterCompanyInfo{  
25 -// CompanyId: 9999 + companyid,  
26 -// CompanyName: "调试用公司数据",  
27 -// AdminId: 9999 + companyid,  
28 -// AdminAccount: "调试用自己修改",  
29 -// AdminName: "调试用自己修改",  
30 -// }  
31 -// return data, nil  
32 -// }  
33 -  
34 //InitCompanyInfo 初始化公司 13 //InitCompanyInfo 初始化公司
35 -//@uCompanyid 从统一用户中心获取的公司id companyid,  
36 func InitCompanyInfo(centerCompany protocol.CenterCompanyInfo) error { 14 func InitCompanyInfo(centerCompany protocol.CenterCompanyInfo) error {
37 // var ( 15 // var (
38 // centerCompany CenterCompanyInfo 16 // centerCompany CenterCompanyInfo
@@ -43,8 +21,7 @@ func InitCompanyInfo(centerCompany protocol.CenterCompanyInfo) error { @@ -43,8 +21,7 @@ func InitCompanyInfo(centerCompany protocol.CenterCompanyInfo) error {
43 // return protocol.NewErrWithMessage("10051") 21 // return protocol.NewErrWithMessage("10051")
44 // } 22 // }
45 var ( 23 var (
46 - newDeparment *models.Department  
47 - //newUserDepart = &models.UserDepartment{} 24 + newDeparment *models.Department
48 newRoleGroup *models.Role 25 newRoleGroup *models.Role
49 newRole *models.Role 26 newRole *models.Role
50 newUser *models.User 27 newUser *models.User
@@ -160,7 +137,7 @@ func initAdminUser(centerCompany protocol.CenterCompanyInfo, o orm.Ormer) (*mode @@ -160,7 +137,7 @@ func initAdminUser(centerCompany protocol.CenterCompanyInfo, o orm.Ormer) (*mode
160 newUser = &models.User{} 137 newUser = &models.User{}
161 ) 138 )
162 err = o.QueryTable(&models.User{}). 139 err = o.QueryTable(&models.User{}).
163 - Filter("user_center_id", centerCompany.AdminId). 140 + Filter("phone", centerCompany.AdminAccount).
164 Filter("delete_at", 0). 141 Filter("delete_at", 0).
165 One(newUser) 142 One(newUser)
166 if err == nil { 143 if err == nil {
@@ -178,16 +155,21 @@ func initAdminUser(centerCompany protocol.CenterCompanyInfo, o orm.Ormer) (*mode @@ -178,16 +155,21 @@ func initAdminUser(centerCompany protocol.CenterCompanyInfo, o orm.Ormer) (*mode
178 return nil, err 155 return nil, err
179 } 156 }
180 } else if err == orm.ErrNoRows { 157 } else if err == orm.ErrNoRows {
  158 + ucenterUser, err := ucenter.RequestUCenterAddUser(centerCompany.AdminAccount, centerCompany.AdminName, "")
  159 + if err != nil {
  160 + log.Error("获取统一用户中心数据失败 :%s", err)
  161 + }
181 //添加用户 162 //添加用户
182 newUser = &models.User{ 163 newUser = &models.User{
183 Phone: centerCompany.AdminAccount, 164 Phone: centerCompany.AdminAccount,
184 - UserCenterId: centerCompany.AdminId,  
185 NickName: centerCompany.AdminName, 165 NickName: centerCompany.AdminName,
  166 + Icon: ucenterUser.Data.Avatar,
  167 + Accid: ucenterUser.Data.Accid,
  168 + UserCenterId: ucenterUser.Data.Id,
  169 + CsAccount: ucenterUser.Data.CustomerAccount,
186 } 170 }
187 - id, err := models.AddUser(newUser, o)  
188 - fmt.Println("-=====>user_id=", id) 171 + _, err = models.AddUser(newUser, o)
189 if err != nil { 172 if err != nil {
190 -  
191 log.Error("添加用户数据失败:%s", err) 173 log.Error("添加用户数据失败:%s", err)
192 return nil, err 174 return nil, err
193 } 175 }
@@ -290,9 +272,9 @@ func initUserDedaprtmet(newDepartment *models.Department, newUserCompany *models @@ -290,9 +272,9 @@ func initUserDedaprtmet(newDepartment *models.Department, newUserCompany *models
290 //添加部门 272 //添加部门
291 newUserDepartment = &models.UserDepartment{ 273 newUserDepartment = &models.UserDepartment{
292 UserCompanyId: newUserCompany.Id, 274 UserCompanyId: newUserCompany.Id,
293 - UserId: newUserCompany.UserId,  
294 - CompanyId: newUserCompany.CompanyId,  
295 - DepartmentId: newDepartment.Id, 275 + //UserId: newUserCompany.UserId,
  276 + CompanyId: newUserCompany.CompanyId,
  277 + DepartmentId: newDepartment.Id,
296 } 278 }
297 _, err = models.AddUserDepartment(newUserDepartment, o) 279 _, err = models.AddUserDepartment(newUserDepartment, o)
298 if err != nil { 280 if err != nil {
@@ -394,7 +376,6 @@ func initUserRole(newUserCompany *models.UserCompany, newRole *models.Role, o or @@ -394,7 +376,6 @@ func initUserRole(newUserCompany *models.UserCompany, newRole *models.Role, o or
394 RoleId: newRole.Id, 376 RoleId: newRole.Id,
395 UserCompanyId: newUserCompany.Id, 377 UserCompanyId: newUserCompany.Id,
396 CompanyId: newUserCompany.CompanyId, 378 CompanyId: newUserCompany.CompanyId,
397 - UserId: newUserCompany.UserId,  
398 } 379 }
399 _, err = models.AddUserRole(newUserRole, o) 380 _, err = models.AddUserRole(newUserRole, o)
400 if err != nil { 381 if err != nil {
@@ -386,33 +386,16 @@ func GetDepartmentUser(companyid int64, departmentid int64) ([]protocol.DepartUs @@ -386,33 +386,16 @@ func GetDepartmentUser(companyid int64, departmentid int64) ([]protocol.DepartUs
386 log.Error("deparment.CompanyId err") 386 log.Error("deparment.CompanyId err")
387 return nil, protocol.NewErrWithMessage("1") 387 return nil, protocol.NewErrWithMessage("1")
388 } 388 }
389 - const dataSql string = `SELECT b.user_id,b.id AS user_company_id FROM user_department AS a  
390 - JOIN user_company AS b ON a.user_company_id = b.id  
391 - WHERE a.department_id=? AND b.delete_at=0 `  
392 - type UsercompanyId struct {  
393 - UserCompanyId int64 `orm:"column(user_company_id)"`  
394 - UserId int64 `orm:"column(user_id)"`  
395 - } 389 + const dataSql string = `SELECT b.nick_name,a.user_company_id FROM user_department AS a
  390 + JOIN user_company AS b ON a.user_company_id = b.id
  391 + WHERE a.department_id=? AND b.delete_at=0 AND a.enable_status = 1 `
396 var ( 392 var (
397 - usercompanyData []UsercompanyId  
398 - returnData []protocol.DepartUserBase 393 + returnData []protocol.DepartUserBase
399 ) 394 )
400 - err = utils.ExecuteQueryAll(&usercompanyData, dataSql, department.Id) 395 + err = utils.ExecuteQueryAll(&returnData, dataSql, department.Id)
401 if err != nil { 396 if err != nil {
402 log.Error("EXECUTE SQL err:%s", err) 397 log.Error("EXECUTE SQL err:%s", err)
403 return nil, protocol.NewErrWithMessage("1") 398 return nil, protocol.NewErrWithMessage("1")
404 } 399 }
405 - for _, v := range usercompanyData {  
406 - udata, err := models.GetUserById(v.UserId)  
407 - if err != nil {  
408 - log.Error("获取user数据失败:%s", err)  
409 - continue  
410 - }  
411 - d := protocol.DepartUserBase{  
412 - UserCompanyId: v.UserCompanyId,  
413 - Name: udata.NickName,  
414 - }  
415 - returnData = append(returnData, d)  
416 - }  
417 return returnData, nil 400 return returnData, nil
418 } 401 }
@@ -15,11 +15,10 @@ import ( @@ -15,11 +15,10 @@ import (
15 15
16 func UserAdd(param protocol.RequestUserAdd) error { 16 func UserAdd(param protocol.RequestUserAdd) error {
17 var ( 17 var (
18 - userm *models.User  
19 - err error 18 + err error
20 ) 19 )
21 - //校验用户  
22 - err = validCompanyUser(param.CompanyId, param.Phone) 20 + //校验用户是否存在
  21 + err = existCompanyUser(param.CompanyId, param.Phone)
23 if err != nil { 22 if err != nil {
24 return err 23 return err
25 } 24 }
@@ -27,48 +26,55 @@ func UserAdd(param protocol.RequestUserAdd) error { @@ -27,48 +26,55 @@ func UserAdd(param protocol.RequestUserAdd) error {
27 err = validCompanyRole(param.CompanyId, param.Roles) 26 err = validCompanyRole(param.CompanyId, param.Roles)
28 if err != nil { 27 if err != nil {
29 log.Error(err.Error()) 28 log.Error(err.Error())
30 - return protocol.NewErrWithMessage("10031") 29 + return err
31 } 30 }
32 //校验部门 31 //校验部门
33 err = validCompanyDepart(param.CompanyId, param.Departments) 32 err = validCompanyDepart(param.CompanyId, param.Departments)
34 if err != nil { 33 if err != nil {
35 log.Error(err.Error()) 34 log.Error(err.Error())
36 - return protocol.NewErrWithMessage("10032") 35 + return err
37 } 36 }
38 //校验职位 37 //校验职位
39 err = validCompanyPosition(param.CompanyId, param.Positions) 38 err = validCompanyPosition(param.CompanyId, param.Positions)
40 if err != nil { 39 if err != nil {
41 log.Error(err.Error()) 40 log.Error(err.Error())
42 - return protocol.NewErrWithMessage("10033")  
43 - }  
44 - userm = &models.User{  
45 - NickName: param.Name,  
46 - Phone: param.Phone, 41 + return err
47 } 42 }
  43 + var (
  44 + userId int64
  45 + userCompanyid int64
  46 + )
48 o := orm.NewOrm() 47 o := orm.NewOrm()
49 o.Begin() 48 o.Begin()
50 - err = registUser(userm, param.CompanyId, o) 49 + //添加用户
  50 + userId, err = addNewUser(param.Name, param.Phone, o)
51 if err != nil { 51 if err != nil {
52 o.Rollback() 52 o.Rollback()
53 - log.Error("registUser err:%s", err) 53 + log.Error("addNewUser err:%s", err)
  54 + return protocol.NewErrWithMessage("1")
  55 + }
  56 + //添加用户公司关系
  57 + userCompanyid, err = addUserCompany(userId, param.CompanyId, param.Name, o)
  58 + if err != nil {
  59 + log.Error("addUserCompany err:%s", err)
54 return protocol.NewErrWithMessage("1") 60 return protocol.NewErrWithMessage("1")
55 } 61 }
56 //添加角色 62 //添加角色
57 - err = editUserRole(userm.Id, param.CompanyId, param.Roles, o) 63 + err = editUserRole(userCompanyid, userId, param.CompanyId, param.Roles, o)
58 if err != nil { 64 if err != nil {
59 o.Rollback() 65 o.Rollback()
60 log.Error("editUserRole err:%s", err) 66 log.Error("editUserRole err:%s", err)
61 return protocol.NewErrWithMessage("1") 67 return protocol.NewErrWithMessage("1")
62 } 68 }
63 //添加部门 69 //添加部门
64 - err = editUserDepart(userm.Id, param.CompanyId, param.Departments, o) 70 + err = editUserDepart(userCompanyid, userId, param.CompanyId, param.Departments, o)
65 if err != nil { 71 if err != nil {
66 o.Rollback() 72 o.Rollback()
67 log.Error("editUserDepart err:%s", err) 73 log.Error("editUserDepart err:%s", err)
68 return protocol.NewErrWithMessage("1") 74 return protocol.NewErrWithMessage("1")
69 } 75 }
70 //添加职位 76 //添加职位
71 - err = editUserDepart(userm.Id, param.CompanyId, param.Positions, o) 77 + err = editUserPosition(userCompanyid, userId, param.CompanyId, param.Positions, o)
72 if err != nil { 78 if err != nil {
73 o.Rollback() 79 o.Rollback()
74 log.Error("editUserDepart err:%s", err) 80 log.Error("editUserDepart err:%s", err)
@@ -141,7 +147,7 @@ func validCompanyPosition(companyid int64, positionid []int64) error { @@ -141,7 +147,7 @@ func validCompanyPosition(companyid int64, positionid []int64) error {
141 return nil 147 return nil
142 } 148 }
143 149
144 -func validCompanyUser(companyid int64, phone string) error { 150 +func existCompanyUser(companyid int64, phone string) error {
145 userdata, err := models.GetUserByPhone(phone) 151 userdata, err := models.GetUserByPhone(phone)
146 if err == orm.ErrNoRows { 152 if err == orm.ErrNoRows {
147 return nil 153 return nil
@@ -159,56 +165,93 @@ func validCompanyUser(companyid int64, phone string) error { @@ -159,56 +165,93 @@ func validCompanyUser(companyid int64, phone string) error {
159 } 165 }
160 166
161 //registUser 注册用户 167 //registUser 注册用户
162 -func registUser(userIn *models.User, companyid int64, o orm.Ormer) error { 168 +// func registUser(userIn *models.User, companyid int64, o orm.Ormer) error {
  169 +// var (
  170 +// err error
  171 +// usrData *models.User
  172 +// )
  173 +// usrData, err = models.GetUserByPhone(userIn.Phone)
  174 +// if err != nil && err != orm.ErrNoRows {
  175 +// return err
  176 +// }
  177 +// if err == orm.ErrNoRows {
  178 +// //用户不存在 添加用户
  179 +// _, err := models.AddUser(userIn, o)
  180 +// if err != nil {
  181 +// return err
  182 +// }
  183 +// }
  184 +// if err == nil {
  185 +// // 用户存在,更新用户
  186 +// usrData.NickName = userIn.NickName
  187 +// err = models.UpdateUserById(usrData, []string{"NickName"}, o)
  188 +// if err != nil {
  189 +// return err
  190 +// }
  191 +// }
  192 +// musercompany := &models.UserCompany{
  193 +// CompanyId: companyid,
  194 +// UserId: userIn.Id,
  195 +// }
  196 +
  197 +// _, err = models.AddUserCompany(musercompany, o)
  198 +// if err != nil {
  199 +// return err
  200 +// }
  201 +// return nil
  202 +// }
  203 +
  204 +func addNewUser(name string, phone string, o orm.Ormer) (userid int64, err error) {
163 var ( 205 var (
164 - err error  
165 usrData *models.User 206 usrData *models.User
166 ) 207 )
167 - usrData, err = models.GetUserByPhone(userIn.Phone) 208 + usrData, err = models.GetUserByPhone(phone)
168 if err != nil && err != orm.ErrNoRows { 209 if err != nil && err != orm.ErrNoRows {
169 - return err 210 + return 0, err
170 } 211 }
171 if err == orm.ErrNoRows { 212 if err == orm.ErrNoRows {
172 //用户不存在 添加用户 213 //用户不存在 添加用户
173 - _, err := models.AddUser(userIn, o) 214 + usrData = &models.User{
  215 + Phone: phone,
  216 + NickName: name,
  217 + }
  218 + _, err := models.AddUser(usrData, o)
174 if err != nil { 219 if err != nil {
175 - return err 220 + return 0, err
176 } 221 }
  222 + return usrData.Id, nil
177 } 223 }
178 if err == nil { 224 if err == nil {
179 - // 用户存在,更新用户  
180 - usrData.NickName = userIn.NickName  
181 - err = models.UpdateUserById(usrData, []string{"NickName"}, o)  
182 - if err != nil {  
183 - return err  
184 - } 225 + // 用户存在,
  226 + return usrData.Id, nil
185 } 227 }
186 - musercompany := &models.UserCompany{  
187 - CompanyId: companyid,  
188 - UserId: userIn.Id, 228 + return 0, err
  229 +}
  230 +
  231 +func addUserCompany(userId int64, companyId int64, nickname string, o orm.Ormer) (id int64, err error) {
  232 + m := &models.UserCompany{
  233 + UserId: userId,
  234 + CompanyId: companyId,
  235 + NickName: nickname,
189 } 236 }
190 - // ok := models.ExistUserCompany(usrData.Id, companyid)  
191 - // if !ok {  
192 - _, err = models.AddUserCompany(musercompany, o) 237 + id, err = models.AddUserCompany(m, o)
193 if err != nil { 238 if err != nil {
194 - return err 239 + return 0, err
195 } 240 }
196 - // }  
197 - // err = models.EnableUserCompany(usrData.Id, companyid)  
198 - return nil 241 + return id, err
199 } 242 }
200 243
201 -func editUserDepart(userid int64, companyid int64, departids []int64, o orm.Ormer) error { 244 +func editUserDepart(usercompanyid int64, userid int64, companyid int64, departids []int64, o orm.Ormer) error {
202 var ( 245 var (
203 oldDepartIds []int64 246 oldDepartIds []int64
204 err error 247 err error
205 delDepartIds []int64 248 delDepartIds []int64
206 addDepartIds []int64 249 addDepartIds []int64
207 ) 250 )
208 - dataSql := `SELECT department_id FROM user_department WHERE enable_status=1 AND company_id=? AND user_id=?`  
209 - dataSql2 := `UPDATE user_department SET enable_status = 2 WHERE company_id = ? AND user_id=? AND department_id=?`  
210 - datasql3 := `INSERT INTO user_department (user_id,department_id,company_id,enable_status,create_at) VALUES (?,?,?,?,?)`  
211 - err = utils.ExecuteQueryAllWithOrmer(o, &oldDepartIds, dataSql, companyid, userid) 251 + dataSql := `SELECT department_id FROM user_department WHERE enable_status=1 AND user_company_id=?`
  252 + dataSql2 := `UPDATE user_department SET enable_status = 2 WHERE user_company_id=? AND department_id=?`
  253 + datasql3 := `INSERT INTO user_department (user_company_id,department_id,company_id,enable_status,create_time) VALUES (?,?,?,?,?)`
  254 + err = utils.ExecuteQueryAllWithOrmer(o, &oldDepartIds, dataSql, usercompanyid)
212 if err != nil { 255 if err != nil {
213 e := fmt.Errorf("Execute SQL err:%s", err) 256 e := fmt.Errorf("Execute SQL err:%s", err)
214 log.Error(e.Error()) 257 log.Error(e.Error())
@@ -217,7 +260,7 @@ func editUserDepart(userid int64, companyid int64, departids []int64, o orm.Orme @@ -217,7 +260,7 @@ func editUserDepart(userid int64, companyid int64, departids []int64, o orm.Orme
217 delDepartIds = utils.ArrayInt64Diff(oldDepartIds, departids) 260 delDepartIds = utils.ArrayInt64Diff(oldDepartIds, departids)
218 addDepartIds = utils.ArrayInt64Diff(departids, oldDepartIds) 261 addDepartIds = utils.ArrayInt64Diff(departids, oldDepartIds)
219 for _, v := range delDepartIds { 262 for _, v := range delDepartIds {
220 - err = utils.ExecuteSQLWithOrmer(o, dataSql2, companyid, userid, v) 263 + err = utils.ExecuteSQLWithOrmer(o, dataSql2, usercompanyid, v)
221 if err != nil { 264 if err != nil {
222 e := fmt.Errorf("Execute SQL err:%s", err) 265 e := fmt.Errorf("Execute SQL err:%s", err)
223 log.Error(e.Error()) 266 log.Error(e.Error())
@@ -226,7 +269,7 @@ func editUserDepart(userid int64, companyid int64, departids []int64, o orm.Orme @@ -226,7 +269,7 @@ func editUserDepart(userid int64, companyid int64, departids []int64, o orm.Orme
226 } 269 }
227 nowTime := time.Now().String() 270 nowTime := time.Now().String()
228 for _, v := range addDepartIds { 271 for _, v := range addDepartIds {
229 - err = utils.ExecuteSQLWithOrmer(o, datasql3, userid, v, companyid, models.USER_POSITION_ENABLE_YES, nowTime) 272 + err = utils.ExecuteSQLWithOrmer(o, datasql3, usercompanyid, v, companyid, models.USER_POSITION_ENABLE_YES, nowTime)
230 if err != nil { 273 if err != nil {
231 e := fmt.Errorf("Execute SQL err:%s", err) 274 e := fmt.Errorf("Execute SQL err:%s", err)
232 log.Error(e.Error()) 275 log.Error(e.Error())
@@ -236,17 +279,17 @@ func editUserDepart(userid int64, companyid int64, departids []int64, o orm.Orme @@ -236,17 +279,17 @@ func editUserDepart(userid int64, companyid int64, departids []int64, o orm.Orme
236 return nil 279 return nil
237 } 280 }
238 281
239 -func editUserPosition(userid int64, companyid int64, positionids []int64, o orm.Ormer) error { 282 +func editUserPosition(usercompanyid int64, userid int64, companyid int64, positionids []int64, o orm.Ormer) error {
240 var ( 283 var (
241 oldPositionIds []int64 284 oldPositionIds []int64
242 err error 285 err error
243 delPositionIds []int64 286 delPositionIds []int64
244 addPositionIds []int64 287 addPositionIds []int64
245 ) 288 )
246 - dataSql := `SELECT position_id FROM user_position WHERE enable_status=1 AND company_id=? AND user_id=?`  
247 - dataSql2 := `UPDATE user_position SET enable_status = 2 WHERE company_id = ? AND user_id=? AND position_id=?`  
248 - datasql3 := `INSERT INTO user_position (user_id,position_id,company_id,enable_status,create_at) VALUES (?,?,?,?,?)`  
249 - err = utils.ExecuteQueryAllWithOrmer(o, &oldPositionIds, dataSql, companyid, userid) 289 + dataSql := `SELECT position_id FROM user_position WHERE enable_status=1 AND user_company_id=?`
  290 + dataSql2 := `UPDATE user_position SET enable_status = 2 WHERE user_company_id=? AND position_id=?`
  291 + datasql3 := `INSERT INTO user_position (user_company_id,position_id,company_id,enable_status,create_at) VALUES (?,?,?,?,?)`
  292 + err = utils.ExecuteQueryAllWithOrmer(o, &oldPositionIds, dataSql, usercompanyid)
250 if err != nil { 293 if err != nil {
251 e := fmt.Errorf("Execute SQL err:%s", err) 294 e := fmt.Errorf("Execute SQL err:%s", err)
252 log.Error(e.Error()) 295 log.Error(e.Error())
@@ -255,7 +298,7 @@ func editUserPosition(userid int64, companyid int64, positionids []int64, o orm. @@ -255,7 +298,7 @@ func editUserPosition(userid int64, companyid int64, positionids []int64, o orm.
255 delPositionIds = utils.ArrayInt64Diff(oldPositionIds, positionids) 298 delPositionIds = utils.ArrayInt64Diff(oldPositionIds, positionids)
256 addPositionIds = utils.ArrayInt64Diff(positionids, oldPositionIds) 299 addPositionIds = utils.ArrayInt64Diff(positionids, oldPositionIds)
257 for _, v := range delPositionIds { 300 for _, v := range delPositionIds {
258 - err = utils.ExecuteSQLWithOrmer(o, dataSql2, companyid, userid, v) 301 + err = utils.ExecuteSQLWithOrmer(o, dataSql2, usercompanyid, v)
259 if err != nil { 302 if err != nil {
260 e := fmt.Errorf("Execute SQL err:%s", err) 303 e := fmt.Errorf("Execute SQL err:%s", err)
261 log.Error(e.Error()) 304 log.Error(e.Error())
@@ -264,7 +307,7 @@ func editUserPosition(userid int64, companyid int64, positionids []int64, o orm. @@ -264,7 +307,7 @@ func editUserPosition(userid int64, companyid int64, positionids []int64, o orm.
264 } 307 }
265 nowTime := time.Now().String() 308 nowTime := time.Now().String()
266 for _, v := range addPositionIds { 309 for _, v := range addPositionIds {
267 - err = utils.ExecuteSQLWithOrmer(o, datasql3, userid, v, companyid, models.USER_POSITION_ENABLE_YES, nowTime) 310 + err = utils.ExecuteSQLWithOrmer(o, datasql3, usercompanyid, v, companyid, models.USER_POSITION_ENABLE_YES, nowTime)
268 if err != nil { 311 if err != nil {
269 e := fmt.Errorf("Execute SQL err:%s", err) 312 e := fmt.Errorf("Execute SQL err:%s", err)
270 log.Error(e.Error()) 313 log.Error(e.Error())
@@ -273,17 +316,17 @@ func editUserPosition(userid int64, companyid int64, positionids []int64, o orm. @@ -273,17 +316,17 @@ func editUserPosition(userid int64, companyid int64, positionids []int64, o orm.
273 } 316 }
274 return nil 317 return nil
275 } 318 }
276 -func editUserRole(userid int64, companyid int64, roleids []int64, o orm.Ormer) error { 319 +func editUserRole(usercompanyid int64, userid int64, companyid int64, roleids []int64, o orm.Ormer) error {
277 var ( 320 var (
278 oldRoleIds []int64 321 oldRoleIds []int64
279 err error 322 err error
280 delRoleIds []int64 323 delRoleIds []int64
281 addRoleIds []int64 324 addRoleIds []int64
282 ) 325 )
283 - dataSql := `SELECT role_id FROM user_role WHERE enable_status=1 AND company_id=? AND user_id=?`  
284 - dataSql2 := `UPDATE user_role SET enable_status = 2 WHERE company_id =? AND user_id=? AND role_id=?`  
285 - datasql3 := `INSERT INTO user_role (user_id,role_id,company_id,enable_status) VALUES (?,?,?,?)`  
286 - err = utils.ExecuteQueryAllWithOrmer(o, &oldRoleIds, dataSql, companyid, userid) 326 + dataSql := `SELECT role_id FROM user_role WHERE enable_status=1 AND user_company_id=?`
  327 + dataSql2 := `UPDATE user_role SET enable_status = 2 WHERE user_company_id=? AND role_id=?`
  328 + datasql3 := `INSERT INTO user_role (user_company_id,role_id,company_id,enable_status) VALUES (?,?,?,?)`
  329 + err = utils.ExecuteQueryAllWithOrmer(o, &oldRoleIds, dataSql, usercompanyid)
287 if err != nil { 330 if err != nil {
288 e := fmt.Errorf("Execute SQL err:%s", err) 331 e := fmt.Errorf("Execute SQL err:%s", err)
289 log.Error(e.Error()) 332 log.Error(e.Error())
@@ -292,7 +335,7 @@ func editUserRole(userid int64, companyid int64, roleids []int64, o orm.Ormer) e @@ -292,7 +335,7 @@ func editUserRole(userid int64, companyid int64, roleids []int64, o orm.Ormer) e
292 delRoleIds = utils.ArrayInt64Diff(oldRoleIds, roleids) 335 delRoleIds = utils.ArrayInt64Diff(oldRoleIds, roleids)
293 addRoleIds = utils.ArrayInt64Diff(roleids, oldRoleIds) 336 addRoleIds = utils.ArrayInt64Diff(roleids, oldRoleIds)
294 for _, v := range delRoleIds { 337 for _, v := range delRoleIds {
295 - err = utils.ExecuteSQLWithOrmer(o, dataSql2, companyid, userid, v) 338 + err = utils.ExecuteSQLWithOrmer(o, dataSql2, usercompanyid, v)
296 if err != nil { 339 if err != nil {
297 e := fmt.Errorf("Execute SQL err:%s", err) 340 e := fmt.Errorf("Execute SQL err:%s", err)
298 log.Error(e.Error()) 341 log.Error(e.Error())
@@ -300,7 +343,7 @@ func editUserRole(userid int64, companyid int64, roleids []int64, o orm.Ormer) e @@ -300,7 +343,7 @@ func editUserRole(userid int64, companyid int64, roleids []int64, o orm.Ormer) e
300 } 343 }
301 } 344 }
302 for _, v := range addRoleIds { 345 for _, v := range addRoleIds {
303 - err = utils.ExecuteSQLWithOrmer(o, datasql3, userid, v, companyid, models.USER_POSITION_ENABLE_YES) 346 + err = utils.ExecuteSQLWithOrmer(o, datasql3, usercompanyid, v, companyid, models.USER_POSITION_ENABLE_YES)
304 if err != nil { 347 if err != nil {
305 e := fmt.Errorf("Execute SQL err:%s", err) 348 e := fmt.Errorf("Execute SQL err:%s", err)
306 log.Error(e.Error()) 349 log.Error(e.Error())
@@ -310,12 +353,38 @@ func editUserRole(userid int64, companyid int64, roleids []int64, o orm.Ormer) e @@ -310,12 +353,38 @@ func editUserRole(userid int64, companyid int64, roleids []int64, o orm.Ormer) e
310 return nil 353 return nil
311 } 354 }
312 355
  356 +func editUserCompany(userCompanyid int64, userid int64, nickname string, o orm.Ormer) error {
  357 + m := &models.UserCompany{
  358 + Id: userCompanyid,
  359 + NickName: nickname,
  360 + UserId: userid,
  361 + }
  362 +
  363 + err := models.UpdateUserCompanyById(m, []string{"NickName", "UserId"}, o)
  364 + return err
  365 +}
  366 +
  367 +//校验user和公司的关系是否正确
  368 +func validUserCompany(userCompanyid int64, companyid int64) (*models.UserCompany, error) {
  369 + ucompany, err := models.GetUserCompanyById(userCompanyid)
  370 + if err != nil {
  371 + log.Error("GetUserCompanyById err;%s", err)
  372 + return nil, protocol.NewErrWithMessage("1")
  373 + }
  374 + if ucompany.CompanyId != companyid {
  375 + log.Error("用户与公司不关联")
  376 + return nil, protocol.NewErrWithMessage("1")
  377 + }
  378 + return ucompany, nil
  379 +}
  380 +
313 func UserEdit(param protocol.RequestUserEdit) error { 381 func UserEdit(param protocol.RequestUserEdit) error {
314 var ( 382 var (
315 - userm *models.User  
316 - err error 383 + err error
  384 + ucompany *models.UserCompany
317 ) 385 )
318 - err = validCompanyUser(param.CompanyId, param.Phone) 386 + //校验公司和用户的关联
  387 + ucompany, err = validUserCompany(param.UserCompanyID, param.CompanyId)
319 if err != nil { 388 if err != nil {
320 return err 389 return err
321 } 390 }
@@ -323,50 +392,64 @@ func UserEdit(param protocol.RequestUserEdit) error { @@ -323,50 +392,64 @@ func UserEdit(param protocol.RequestUserEdit) error {
323 err = validCompanyRole(param.CompanyId, param.Roles) 392 err = validCompanyRole(param.CompanyId, param.Roles)
324 if err != nil { 393 if err != nil {
325 log.Error(err.Error()) 394 log.Error(err.Error())
326 - return protocol.NewErrWithMessage("10031") 395 + return err
327 } 396 }
328 //校验部门 397 //校验部门
329 err = validCompanyDepart(param.CompanyId, param.Departments) 398 err = validCompanyDepart(param.CompanyId, param.Departments)
330 if err != nil { 399 if err != nil {
331 log.Error(err.Error()) 400 log.Error(err.Error())
332 - return protocol.NewErrWithMessage("10032") 401 + return err
333 } 402 }
334 //校验职位 403 //校验职位
335 err = validCompanyPosition(param.CompanyId, param.Positions) 404 err = validCompanyPosition(param.CompanyId, param.Positions)
336 if err != nil { 405 if err != nil {
337 log.Error(err.Error()) 406 log.Error(err.Error())
338 - return protocol.NewErrWithMessage("10033") 407 + return err
339 } 408 }
340 - userm = &models.User{  
341 - Id: param.ID,  
342 - NickName: param.Name,  
343 - Phone: param.Phone, 409 + //检查用户手机号是否生变更
  410 + var (
  411 + usrData *models.User
  412 + )
  413 + usrData, err = models.GetUserById(ucompany.UserId)
  414 + if err != nil {
  415 + log.Error("获取用户数据失败:%s", err)
  416 + return protocol.NewErrWithMessage("1")
344 } 417 }
345 o := orm.NewOrm() 418 o := orm.NewOrm()
346 o.Begin() 419 o.Begin()
347 - // err = registUser(userm, param.CompanyId, o)  
348 - // if err != nil {  
349 - // o.Rollback()  
350 - // log.Error("registUser err:%s", err)  
351 - // return protocol.NewErrWithMessage("1")  
352 - // }  
353 - // TODO 用户数据更新 420 + if usrData.Phone != param.Phone {
  421 + //手机号变更
  422 + uid, err := addNewUser(param.Name, param.Phone, o)
  423 + if err != nil {
  424 + o.Rollback()
  425 + log.Error("手机号变更,新增用户失败;%s", err)
  426 + return protocol.NewErrWithMessage("1")
  427 + }
  428 + ucompany.UserId = uid
  429 + }
  430 + //用户数据更新
  431 + err = editUserCompany(param.UserCompanyID, ucompany.UserId, param.Name, o)
  432 + if err != nil {
  433 + o.Rollback()
  434 + log.Error("editUserCompany err:%s", err)
  435 + return protocol.NewErrWithMessage("1")
  436 + }
354 //添加角色 437 //添加角色
355 - err = editUserRole(userm.Id, param.CompanyId, param.Roles, o) 438 + err = editUserRole(param.UserCompanyID, ucompany.UserId, param.CompanyId, param.Roles, o)
356 if err != nil { 439 if err != nil {
357 o.Rollback() 440 o.Rollback()
358 log.Error("editUserRole err:%s", err) 441 log.Error("editUserRole err:%s", err)
359 return protocol.NewErrWithMessage("1") 442 return protocol.NewErrWithMessage("1")
360 } 443 }
361 //添加部门 444 //添加部门
362 - err = editUserDepart(userm.Id, param.CompanyId, param.Departments, o) 445 + err = editUserDepart(param.UserCompanyID, ucompany.UserId, param.CompanyId, param.Departments, o)
363 if err != nil { 446 if err != nil {
364 o.Rollback() 447 o.Rollback()
365 log.Error("editUserDepart err:%s", err) 448 log.Error("editUserDepart err:%s", err)
366 return protocol.NewErrWithMessage("1") 449 return protocol.NewErrWithMessage("1")
367 } 450 }
368 //添加职位 451 //添加职位
369 - err = editUserDepart(userm.Id, param.CompanyId, param.Positions, o) 452 + err = editUserPosition(param.UserCompanyID, ucompany.UserId, param.CompanyId, param.Positions, o)
370 if err != nil { 453 if err != nil {
371 o.Rollback() 454 o.Rollback()
372 log.Error("editUserDepart err:%s", err) 455 log.Error("editUserDepart err:%s", err)
@@ -415,13 +498,12 @@ func UserDelete(userCompanyids []int64, companyid int64) error { @@ -415,13 +498,12 @@ func UserDelete(userCompanyids []int64, companyid int64) error {
415 log.Error(e.Error()) 498 log.Error(e.Error())
416 } 499 }
417 } 500 }
418 -  
419 return nil 501 return nil
420 } 502 }
421 503
422 func UserList(param protocol.RequestUserList) (protocol.ResponseUserList, error) { 504 func UserList(param protocol.RequestUserList) (protocol.ResponseUserList, error) {
423 505
424 - datasql := `SELECT a.id as user_company_id,a.company_id,a.user_id,a.enable, b.phone,b.nick_name 506 + datasql := `SELECT a.id as user_company_id,a.enable, b.phone,a.nick_name
425 FROM user_company AS a 507 FROM user_company AS a
426 LEFT JOIN user AS b ON a.user_id = b.id 508 LEFT JOIN user AS b ON a.user_id = b.id
427 WHERE a.company_id=? AND a.delete_at = 0 ` 509 WHERE a.company_id=? AND a.delete_at = 0 `
@@ -532,6 +614,30 @@ func GetUserRole(usercompanyid int64) []protocol.RoleBase { @@ -532,6 +614,30 @@ func GetUserRole(usercompanyid int64) []protocol.RoleBase {
532 return data 614 return data
533 } 615 }
534 616
  617 +func GetUserData(usercompanyid int64) (protocol.UserInfoBase, error) {
  618 + var (
  619 + ucompany *models.UserCompany
  620 + err error
  621 + uinfo protocol.UserInfoBase
  622 + )
  623 + ucompany, err = models.GetUserCompanyById(usercompanyid)
  624 + if err != nil {
  625 + log.Error("获取GetUserCompanyById失败 :%s", err)
  626 + return uinfo, err
  627 + }
  628 + userdata, err := models.GetUserById(ucompany.UserId)
  629 + if err != nil {
  630 + log.Error("获取GetUserById 失败:%s", err)
  631 + return uinfo, err
  632 + }
  633 + uinfo = protocol.UserInfoBase{
  634 + UserCompanyId: ucompany.Id,
  635 + Name: ucompany.NickName,
  636 + Phone: userdata.Phone,
  637 + }
  638 + return uinfo, nil
  639 +}
  640 +
535 //禁用用户 641 //禁用用户
536 func UserForbid(userCompanyids []int64, companyid int64) error { 642 func UserForbid(userCompanyids []int64, companyid int64) error {
537 if len(userCompanyids) == 0 { 643 if len(userCompanyids) == 0 {
@@ -154,5 +154,4 @@ func RoleMenuEdit(companyid int64, roleId int64, menuids []int64) error { @@ -154,5 +154,4 @@ func RoleMenuEdit(companyid int64, roleId int64, menuids []int64) error {
154 } 154 }
155 o.Commit() 155 o.Commit()
156 return nil 156 return nil
157 -  
158 } 157 }
  1 +package ucenter
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "oppmg/common/log"
  6 + "oppmg/protocol"
  7 +)
  8 +
  9 +func RequestUCenterLogin(account, password string) (*ResponseLogin, error) {
  10 + var uclientReturn *ResponseLogin
  11 + param := RequesLogin{
  12 + Type: 1,
  13 + Phone: account,
  14 + Password: password,
  15 + }
  16 + uclient := NewUCenterClient()
  17 + btBody, err := uclient.Call(param)
  18 + if err != nil {
  19 + log.Error("统一用户中心请求失败 err:%s", err)
  20 + return nil, protocol.NewErrWithMessage("1")
  21 + }
  22 + err = json.Unmarshal(btBody, &uclientReturn)
  23 + if err != nil {
  24 + log.Error("解析统一用户中心响应失败 err:%s", err)
  25 + return nil, protocol.NewErrWithMessage("1")
  26 + }
  27 + if !(uclientReturn.Code == ResponseCode0 &&
  28 + uclientReturn.Msg == ResponseMsgOk) {
  29 + return nil, protocol.NewErrWithMessage("10021")
  30 + }
  31 + return uclientReturn, nil
  32 +}
  33 +
  34 +func RequestUCenterAddUser(phone string, nickname string, avatar string) (*ResponseAddUser, error) {
  35 + var ucenterReturn *ResponseAddUser
  36 + param := RequestAddUser{
  37 + Phone: phone,
  38 + Nickname: nickname,
  39 + Avatar: avatar,
  40 + Password: "9d1f5048afd96b39a3dae71a99f2c77a30112d29", //默认密码:fmt.Sprintf("%x", sha1.Sum([]byte("mmm1234554321")))
  41 + RegIm: 1,
  42 + }
  43 + uclient := NewUCenterClient()
  44 + btBody, err := uclient.Call(param)
  45 + if err != nil {
  46 + log.Error("统一用户中心请求失败 err:%s", err)
  47 + return nil, protocol.NewErrWithMessage("1")
  48 + }
  49 + err = json.Unmarshal(btBody, &ucenterReturn)
  50 + if err != nil {
  51 + log.Error("解析统一用户中心响应失败 err:%s", err)
  52 + return nil, protocol.NewErrWithMessage("1")
  53 + }
  54 + if !(ucenterReturn.Code == ResponseCode0 &&
  55 + ucenterReturn.Msg == ResponseMsgOk) {
  56 + return nil, protocol.NewErrWithMessage("10021")
  57 + }
  58 + return ucenterReturn, nil
  59 +}
@@ -57,7 +57,7 @@ type ResponseLogin struct { @@ -57,7 +57,7 @@ type ResponseLogin struct {
57 57
58 type RequestAddUser struct { 58 type RequestAddUser struct {
59 Phone string `json:"phone"` 59 Phone string `json:"phone"`
60 - RegIm bool `json:"regIm"` 60 + RegIm int8 `json:"regIm"`
61 Nickname string `json:"nickname"` 61 Nickname string `json:"nickname"`
62 Avatar string `json:"avatar"` 62 Avatar string `json:"avatar"`
63 Password string `json:"password"` 63 Password string `json:"password"`
@@ -86,6 +86,19 @@ func (r RequestAddUser) Valid() error { @@ -86,6 +86,19 @@ func (r RequestAddUser) Valid() error {
86 return nil 86 return nil
87 } 87 }
88 88
  89 +type ResponseAddUser struct {
  90 + CommResponse
  91 + Data struct {
  92 + Id int64 `json:"id"`
  93 + Phone string `json:"phone"`
  94 + Nickname string `json:"nickname"`
  95 + Avatar string `json:"avatar"`
  96 + Token string `json:"token"`
  97 + Accid int64 `json:"accid"`
  98 + CustomerAccount int64 `json:"customerAccount"`
  99 + } `json:"data"`
  100 +}
  101 +
89 type RequestCheckCompany struct { 102 type RequestCheckCompany struct {
90 CompanyId int64 `json:"company_id"` 103 CompanyId int64 `json:"company_id"`
91 } 104 }
  1 +package geetest
  2 +
  3 +import (
  4 + "crypto/md5"
  5 + "encoding/hex"
  6 + "encoding/json"
  7 + "errors"
  8 + "io/ioutil"
  9 + "net/http"
  10 + "net/url"
  11 + "strings"
  12 + "time"
  13 +)
  14 +
  15 +type GeetestLib struct {
  16 + CaptchaID string
  17 + PrivateKey string
  18 + Client *http.Client
  19 +}
  20 +
  21 +type FailbackRegisterRespnse struct {
  22 + Success int `json:"success"`
  23 + GT string `json:"gt"`
  24 + Challenge string `json:"challenge"`
  25 + NewCaptcha int `json:"new_captcha"`
  26 +}
  27 +
  28 +const (
  29 + geetestHost = "http://api.geetest.com"
  30 + registerURL = geetestHost + "/register.php"
  31 + validateURL = geetestHost + "/validate.php"
  32 +)
  33 +
  34 +func MD5Encode(input string) string {
  35 + md5Instant := md5.New()
  36 + md5Instant.Write([]byte(input))
  37 + return hex.EncodeToString(md5Instant.Sum(nil))
  38 +}
  39 +
  40 +// 初始化 GeetestLib
  41 +func NewGeetestLib(capthcaID string, privateKey string, timeOut time.Duration) (geetest GeetestLib){
  42 + client := &http.Client{Timeout: timeOut}
  43 + geetest = GeetestLib{capthcaID, privateKey, client}
  44 + return
  45 +}
  46 +
  47 +func (g *GeetestLib) getFailBackRegisterResponse(success int, challenge string) []byte {
  48 + if challenge == "" {
  49 + challenge = hex.EncodeToString(md5.New().Sum(nil))
  50 + }
  51 +
  52 + response := FailbackRegisterRespnse{
  53 + success,
  54 + g.CaptchaID,
  55 + challenge,
  56 + 1,
  57 + }
  58 + res, _ := json.Marshal(response)
  59 + return res
  60 +}
  61 +
  62 +func (g *GeetestLib) do(req *http.Request) (body []byte, err error) {
  63 + req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
  64 + var resp *http.Response
  65 + if resp, err = g.Client.Do(req); err != nil {
  66 + return
  67 + }
  68 + defer resp.Body.Close()
  69 + if resp.StatusCode >= http.StatusInternalServerError {
  70 + err = errors.New("http status code 5xx")
  71 + return
  72 + }
  73 +
  74 + if body, err = ioutil.ReadAll(resp.Body); err != nil {
  75 + return
  76 + }
  77 + return
  78 +}
  79 +
  80 +func (g *GeetestLib) PreProcess(userID string, userIP string) (int8, []byte) {
  81 + params := url.Values{}
  82 + params.Add("gt", g.CaptchaID)
  83 + params.Add("new_captcha", "1")
  84 + if userID != "" {
  85 + params.Add("user_id", userID)
  86 + }
  87 + if userIP != "" {
  88 + params.Add("ip_adress", userIP)
  89 + }
  90 + req, _ := http.NewRequest("GET", registerURL+"?"+params.Encode(), nil)
  91 + body, err := g.do(req)
  92 + if err != nil {
  93 + return 0, g.getFailBackRegisterResponse(0, "")
  94 + }
  95 + challenge := string(body)
  96 + if len(challenge) != 32 {
  97 + return 0, g.getFailBackRegisterResponse(0, "")
  98 + } else {
  99 + challenge = MD5Encode(challenge + g.PrivateKey)
  100 + return 1, g.getFailBackRegisterResponse(1, challenge)
  101 + }
  102 +}
  103 +
  104 +func (g *GeetestLib) checkParas(challenge string, validate string, seccode string) bool {
  105 + if challenge == "" || validate == "" || seccode == "" {
  106 + return false
  107 + }
  108 + return true
  109 +}
  110 +
  111 +func (g *GeetestLib) checkSuccessRes(challenge string, validate string) bool {
  112 + return MD5Encode(g.PrivateKey+"geetest"+challenge) == validate
  113 +}
  114 +
  115 +func (g *GeetestLib) checkFailbackRes(challenge string, validate string) bool {
  116 + return MD5Encode(challenge) == validate
  117 +}
  118 +
  119 +func (g *GeetestLib) SuccessValidate(challenge string, validate string, seccode string, userID string, userIP string) bool {
  120 + if !g.checkParas(challenge, validate, seccode) {
  121 + return false
  122 + }
  123 + if !g.checkSuccessRes(challenge, validate) {
  124 + return false
  125 + }
  126 + params := url.Values{}
  127 + params.Add("seccode", seccode)
  128 + params.Add("challenge", challenge)
  129 + params.Add("captchaid", g.CaptchaID)
  130 + params.Add("sdk", "golang_v1.0.0")
  131 + if userID != "" {
  132 + params.Add("user_id", userID)
  133 + }
  134 + if userIP != "" {
  135 + params.Add("ip_adress", userIP)
  136 + }
  137 + req, _ := http.NewRequest("POST", validateURL, strings.NewReader(params.Encode()))
  138 + body, err := g.do(req)
  139 + if err != nil {
  140 + return false
  141 + }
  142 + res := string(body)
  143 + return res == MD5Encode(seccode)
  144 +}
  145 +
  146 +func (g *GeetestLib) FailbackValidate(challenge string, validate string, seccode string) bool {
  147 + if !g.checkParas(challenge, validate, seccode) {
  148 + return false
  149 + }
  150 + if !g.checkFailbackRes(challenge, validate) {
  151 + return false
  152 + }
  153 + return true
  154 +}
1 # github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2 1 # github.com/360EntSecGroup-Skylar/excelize/v2 v2.0.2
2 github.com/360EntSecGroup-Skylar/excelize/v2 2 github.com/360EntSecGroup-Skylar/excelize/v2
  3 +# github.com/GeeTeam/gt3-golang-sdk v0.0.0-20190704102600-e89c6d964c8f
  4 +github.com/GeeTeam/gt3-golang-sdk/geetest
3 # github.com/astaxie/beego v1.11.1 5 # github.com/astaxie/beego v1.11.1
4 github.com/astaxie/beego 6 github.com/astaxie/beego
5 github.com/astaxie/beego/config 7 github.com/astaxie/beego/config