作者 yangfu

统一用户中心修改

  1 +package v1
  2 +
  3 +import (
  4 + "encoding/json"
  5 + "gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
  6 + "opp/controllers"
  7 + "opp/protocol"
  8 + "opp/services/auth"
  9 +)
  10 +
  11 +type UcenterController struct {
  12 + controllers.BaseController
  13 +}
  14 +
  15 +//UCenterLogin
  16 +//@router /login [post]
  17 +func (this *UcenterController) UCenterLogin() {
  18 + var msg *protocol.ResponseMessage
  19 + defer func() {
  20 + this.Resp(msg)
  21 + }()
  22 + var request *protocol.UCenterLoginRequest
  23 + if err := json.Unmarshal(this.ByteBody, &request); err != nil {
  24 + log.Error(err)
  25 + msg = protocol.BadRequestParam(1)
  26 + return
  27 + }
  28 + if b, m := this.Valid(request); !b {
  29 + msg = m
  30 + return
  31 + }
  32 + header := controllers.GetRequestHeader(this.Ctx)
  33 + msg = protocol.NewReturnResponse(auth.UCenterLogin(header, request))
  34 +}
@@ -10,7 +10,6 @@ import ( @@ -10,7 +10,6 @@ import (
10 "gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/orm" 10 "gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/orm"
11 "gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/redis" 11 "gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/redis"
12 "gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/websocket" 12 "gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/websocket"
13 - "opp/controllers"  
14 "opp/internal/utils" 13 "opp/internal/utils"
15 _ "opp/routers" 14 _ "opp/routers"
16 "opp/services/im" 15 "opp/services/im"
@@ -63,7 +62,6 @@ func main() { @@ -63,7 +62,6 @@ func main() {
63 defer func() { 62 defer func() {
64 log.Info("app on stop!") 63 log.Info("app on stop!")
65 }() 64 }()
66 - beego.InsertFilter("/*", beego.BeforeRouter, controllers.FilterComm)  
67 log.Info("app on start!") 65 log.Info("app on start!")
68 log.Info("Beego Run Mode:", beego.BConfig.RunMode) 66 log.Info("Beego Run Mode:", beego.BConfig.RunMode)
69 67
@@ -83,19 +83,19 @@ func DeleteUsers(id int64) (err error) { @@ -83,19 +83,19 @@ func DeleteUsers(id int64) (err error) {
83 return 83 return
84 } 84 }
85 85
86 -func GetUserKefu() (v []*User, err error) { 86 +func GetUserByMobile(mobile string) (v *User, err error) {
87 o := orm.NewOrm() 87 o := orm.NewOrm()
88 - sql := `select * from user where is_kefu = 1 and enable_status=1`  
89 - if _, err = o.Raw(sql).QueryRows(&v); err == nil { 88 + sql := "select * from user where phone=? and enable_status=1"
  89 + if err = o.Raw(sql, mobile).QueryRow(&v); err == nil {
90 return v, nil 90 return v, nil
91 } 91 }
92 return nil, err 92 return nil, err
93 } 93 }
94 94
95 -func GetUserByMobile(mobile string) (v *User, err error) { 95 +func GetUserByUcenterId(uid int64) (v *User, err error) {
96 o := orm.NewOrm() 96 o := orm.NewOrm()
97 - sql := "select * from user where phone=? and enable_status=1"  
98 - if err = o.Raw(sql, mobile).QueryRow(&v); err == nil { 97 + sql := "select * from user where user_center_id=? and enable_status=1"
  98 + if err = o.Raw(sql, uid).QueryRow(&v); err == nil {
99 return v, nil 99 return v, nil
100 } 100 }
101 return nil, err 101 return nil, err
@@ -26,11 +26,7 @@ type RequestHeader struct { @@ -26,11 +26,7 @@ type RequestHeader struct {
26 26
27 /*Login */ 27 /*Login */
28 type LoginRequest struct { 28 type LoginRequest struct {
29 - Phone string `json:"phone" valid:"Required;Mobile"`  
30 - Code string `json:"code"`  
31 - GrantType string `json:"grantType" valid:"Required"`  
32 - PassWord string `json:"password"`  
33 - ClientId string `json:"clientId" valid:"Required"` 29 + Uid int64 `json:"uid" valid:"Required;"`
34 } 30 }
35 type LoginResponse struct { 31 type LoginResponse struct {
36 AuthCode string `json:"authCode"` 32 AuthCode string `json:"authCode"`
@@ -38,8 +34,11 @@ type LoginResponse struct { @@ -38,8 +34,11 @@ type LoginResponse struct {
38 34
39 /*统一用户中心登录*/ 35 /*统一用户中心登录*/
40 type UserCenterLoginRequest struct { 36 type UserCenterLoginRequest struct {
41 - Phone string `json:"phone"`  
42 - PassWord string `json:"password"` 37 + Phone string `json:"phone"`
  38 + PassWord string `json:"password"`
  39 + Code string `json:"code"`
  40 + GrantType string `json:"grantType" valid:"Required"`
  41 + ClientId string `json:"clientId" valid:"Required"`
43 } 42 }
44 43
45 type UserCenterLoginResponse struct { 44 type UserCenterLoginResponse struct {
@@ -90,3 +90,58 @@ func (m Message) Unmarshal(v interface{}) error { @@ -90,3 +90,58 @@ func (m Message) Unmarshal(v interface{}) error {
90 } 90 }
91 return json.Unmarshal(m.Data, v) 91 return json.Unmarshal(m.Data, v)
92 } 92 }
  93 +
  94 +/**************公告****************/
  95 +type Question struct {
  96 + Id int `json:"id"`
  97 + Type int `json:"type" valid:"Required"`
  98 + Title string `json:"title" valid:"Required"`
  99 + Content []QuestionContent `json:"content" valid:"Required"`
  100 +}
  101 +type QuestionContent struct {
  102 + Id int `json:"id" valid:"Required"`
  103 + Content string `json:"content" valid:"Required"`
  104 +}
  105 +type Cover struct {
  106 + Path string `json:"path" valid:"Required"`
  107 + H int `json:"h"`
  108 + W int `json:"w"`
  109 +}
  110 +
  111 +/*公告列表 BulletinList */
  112 +type BulletinListRequest struct {
  113 +}
  114 +type BulletinListResponse struct {
  115 + List []*BulletinItem `json:"list"`
  116 + Total int
  117 +}
  118 +
  119 +type BulletinItem struct {
  120 + Id int `json:"id"`
  121 + Type int8 `json:"type"`
  122 + Title string `json:"title"`
  123 + Status int8 `json:"status"`
  124 + Receiver []Receiver `json:"receiver" valid:"Required"`
  125 + CreateAt string `json:"time"`
  126 +}
  127 +
  128 +/*GetBulletin */
  129 +type GetBulletinRequest struct {
  130 +}
  131 +type GetBulletinResponse struct {
  132 + Id int `json:"id"`
  133 + Type int `json:"type" valid:"Required"`
  134 + Title string `json:"title" valid:"Required"`
  135 + Content string `json:"content" valid:"Required"`
  136 + AllowClose int `json:"allow_close"`
  137 + //AllowCondition int `json:"allow_condition"`
  138 + QuestionSwitch int `json:"question_switch"`
  139 + Receiver []Receiver `json:"receiver" valid:"Required"`
  140 + Question Question `json:"question"`
  141 + Cover Cover `json:"cover" valid:"Required"`
  142 +}
  143 +
  144 +type Receiver struct {
  145 + Id int64 `json:"id"`
  146 + NickName string `json:"name"`
  147 +}
  1 +package protocol
  2 +
  3 +const (
  4 + ModuleOportunity = "opportunity"
  5 + ModuleQuestion = "question"
  6 +)
  7 +
  8 +const (
  9 + MethodLogin = "/auth/login"
  10 + MethodGetUser = "/users/"
  11 +)
  12 +
  13 +/*UCenterLogin */
  14 +type UCenterLoginRequest struct {
  15 + Phone string `json:"phone"`
  16 + PassWord string `json:"password"`
  17 + Code string `json:"code"`
  18 + GrantType string `json:"grantType" valid:"Required"`
  19 + //ClientId string `json:"clientId" valid:"Required"`
  20 +}
  21 +type UCenterLoginResponse struct {
  22 + Uid int64 `json:"uid"` //统一用户中心用户编号,作为登录凭证
  23 + Module []*ModulePermission `json:"module"`
  24 +}
  25 +
  26 +//模块权限 (机会)opportunity (问题)question
  27 +type ModulePermission struct {
  28 + Name string `json:"name"` //模块名称 子菜单名称 `
  29 + Menus []*ModulePermission `json:"-"` //子模块权限
  30 +}
  31 +
  32 +/*UCenterGetUser */
  33 +type UCenterGetUserRequest struct {
  34 +}
  35 +type UCenterGetUserResponse struct {
  36 + Id int64 `json:"id"`
  37 + Phone string `json:"phone"`
  38 + NickName string `json:"nickname"`
  39 + Avatar string `json:"avatar"`
  40 + Token string `json:"token"`
  41 + Accid string `json:"accid"`
  42 + CustomerAccount string `json:"customerAccount"`
  43 +}
@@ -183,6 +183,14 @@ func init() { @@ -183,6 +183,14 @@ func init() {
183 MethodParams: param.Make(), 183 MethodParams: param.Make(),
184 Params: nil}) 184 Params: nil})
185 185
  186 + beego.GlobalControllerRouter["opp/controllers/v1:UcenterController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:UcenterController"],
  187 + beego.ControllerComments{
  188 + Method: "UCenterLogin",
  189 + Router: `/login`,
  190 + AllowHTTPMethods: []string{"post"},
  191 + MethodParams: param.Make(),
  192 + Params: nil})
  193 +
186 beego.GlobalControllerRouter["opp/controllers/v1:UploadController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:UploadController"], 194 beego.GlobalControllerRouter["opp/controllers/v1:UploadController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:UploadController"],
187 beego.ControllerComments{ 195 beego.ControllerComments{
188 Method: "Image", 196 Method: "Image",
@@ -3,26 +3,26 @@ package routers @@ -3,26 +3,26 @@ package routers
3 import ( 3 import (
4 "github.com/astaxie/beego" 4 "github.com/astaxie/beego"
5 "github.com/prometheus/client_golang/prometheus/promhttp" 5 "github.com/prometheus/client_golang/prometheus/promhttp"
6 - "net/http" 6 + "opp/controllers"
7 "opp/controllers/v1" 7 "opp/controllers/v1"
8 - "opp/services/websocket"  
9 ) 8 )
10 9
11 var nsV1 *beego.Namespace 10 var nsV1 *beego.Namespace
12 11
13 func init() { 12 func init() {
14 nsV1 := beego.NewNamespace("v1", 13 nsV1 := beego.NewNamespace("v1",
15 - beego.NSNamespace("auth", beego.NSInclude(&v1.AuthController{})),  
16 - beego.NSNamespace("upload", beego.NSInclude(&v1.UploadController{})),  
17 - beego.NSNamespace("version", beego.NSInclude(&v1.VersionController{})),  
18 - beego.NSNamespace("commend", beego.NSInclude(&v1.CommendController{})),  
19 - beego.NSNamespace("user", beego.NSInclude(&v1.UserController{})),  
20 - beego.NSNamespace("chance", beego.NSInclude(&v1.ChanceController{})),  
21 - beego.NSNamespace("message", beego.NSInclude(&v1.MessageController{})),  
22 - beego.NSNamespace("department", beego.NSInclude(&v1.DepartmentController{})), 14 + beego.NSNamespace("ucenter", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.UcenterController{})),
  15 + beego.NSNamespace("auth", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.AuthController{})),
  16 + beego.NSNamespace("upload", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.UploadController{})),
  17 + beego.NSNamespace("version", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.VersionController{})),
  18 + beego.NSNamespace("commend", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.CommendController{})),
  19 + beego.NSNamespace("user", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.UserController{})),
  20 + beego.NSNamespace("chance", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.ChanceController{})),
  21 + beego.NSNamespace("message", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.MessageController{})),
  22 + beego.NSNamespace("department", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.DepartmentController{})),
23 ) 23 )
24 beego.AddNamespace(nsV1) 24 beego.AddNamespace(nsV1)
25 beego.SetStaticPath("/file/opp", beego.AppConfig.String("source_path")) 25 beego.SetStaticPath("/file/opp", beego.AppConfig.String("source_path"))
26 beego.Handler("/metrics", promhttp.Handler()) 26 beego.Handler("/metrics", promhttp.Handler())
27 - beego.Handler("/upgrage", http.HandlerFunc(websocket.Upgrage)) 27 + //beego.Handler("/upgrage", http.HandlerFunc(websocket.Upgrage))
28 } 28 }
@@ -51,6 +51,7 @@ func GetUserBaseInfoAggregation(uid int64, companyId int64) (v *protocol.UserBas @@ -51,6 +51,7 @@ func GetUserBaseInfoAggregation(uid int64, companyId int64) (v *protocol.UserBas
51 return 51 return
52 } 52 }
53 53
  54 +//获取用户基础数据
54 func GetUserBaseInfo(uid int64, companyId int64) (v *protocol.BaseUserInfo, err error) { 55 func GetUserBaseInfo(uid int64, companyId int64) (v *protocol.BaseUserInfo, err error) {
55 var ( 56 var (
56 agg *protocol.UserBaseInfoAggregation 57 agg *protocol.UserBaseInfoAggregation
@@ -122,6 +123,7 @@ func GetTopPosition(positions []*protocol.Position) *protocol.Position { @@ -122,6 +123,7 @@ func GetTopPosition(positions []*protocol.Position) *protocol.Position {
122 return top 123 return top
123 } 124 }
124 125
  126 +//获取机会
125 func GetChance(chanceId int64, companyId int64) (v *protocol.ChanceDetail, err error) { 127 func GetChance(chanceId int64, companyId int64) (v *protocol.ChanceDetail, err error) {
126 var ( 128 var (
127 c *models.Chance 129 c *models.Chance
@@ -147,6 +149,7 @@ func GetChance(chanceId int64, companyId int64) (v *protocol.ChanceDetail, err e @@ -147,6 +149,7 @@ func GetChance(chanceId int64, companyId int64) (v *protocol.ChanceDetail, err e
147 return 149 return
148 } 150 }
149 151
  152 +//构建统计sql语句
150 func GetIncrementSql(table string, column string, incre int, id int64) *utils.SqlData { 153 func GetIncrementSql(table string, column string, incre int, id int64) *utils.SqlData {
151 var sql *bytes.Buffer 154 var sql *bytes.Buffer
152 sql = bytes.NewBuffer(nil) 155 sql = bytes.NewBuffer(nil)
  1 +package agg
  2 +
  3 +import (
  4 + "crypto/sha1"
  5 + "encoding/hex"
  6 + "encoding/json"
  7 + "fmt"
  8 + "github.com/astaxie/beego"
  9 + "github.com/astaxie/beego/httplib"
  10 + "gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
  11 + "io/ioutil"
  12 + "net/http"
  13 + "time"
  14 +)
  15 +
  16 +/****************用户中心******************/
  17 +//请求用户中心接口
  18 +func RequestUserCenter(method string, httpMethod, request interface{}, rsponse interface{}) (data []byte, err error) {
  19 + var (
  20 + httpRsp *http.Response
  21 + curTime = fmt.Sprintf("%v", time.Now().Unix())
  22 + appKey = beego.AppConfig.String("user_center_app_key")
  23 + salt = beego.AppConfig.String("user_center_salt")
  24 + httpReq *httplib.BeegoHTTPRequest
  25 + )
  26 +
  27 + if httpMethod == http.MethodGet {
  28 + httpReq = httplib.Get(beego.AppConfig.String("user_center_url") + method)
  29 + } else if httpMethod == http.MethodPost {
  30 + httpReq = httplib.Post(beego.AppConfig.String("user_center_url") + method)
  31 + } else if httpMethod == http.MethodPut {
  32 + httpReq = httplib.Put(beego.AppConfig.String("user_center_url") + method)
  33 + }
  34 + httpReq.JSONBody(request)
  35 + httpReq.Header("appKey", appKey)
  36 + httpReq.Header("curTime", curTime)
  37 + httpReq.Header("checkSum", getUserCenterCheckSum(curTime, "", beego.AppConfig.String("user_center_app_secret"), salt))
  38 + if httpRsp, err = httpReq.DoRequest(); err != nil {
  39 + log.Error(err)
  40 + return
  41 + }
  42 + data, err = ioutil.ReadAll(httpRsp.Body)
  43 + defer httpRsp.Body.Close()
  44 + if err != nil {
  45 + log.Error(err)
  46 + return
  47 + }
  48 + if err = json.Unmarshal(data, rsponse); err != nil {
  49 + log.Error(err)
  50 + return
  51 + }
  52 + return
  53 +}
  54 +
  55 +//计算check_sum
  56 +func getUserCenterCheckSum(curTime, nonce, appKey, salt string) string {
  57 + sha1 := sha1.New()
  58 + sum := sha1.Sum([]byte(fmt.Sprintf("%s%s%s%s", curTime, nonce, appKey, salt)))
  59 + return hex.EncodeToString(sum)
  60 +}
@@ -2,17 +2,13 @@ package auth @@ -2,17 +2,13 @@ package auth
2 2
3 import ( 3 import (
4 "bytes" 4 "bytes"
5 - "crypto/sha1"  
6 - "encoding/hex"  
7 "encoding/json" 5 "encoding/json"
8 "fmt" 6 "fmt"
9 - "github.com/astaxie/beego/httplib"  
10 "github.com/astaxie/beego/orm" 7 "github.com/astaxie/beego/orm"
11 "html/template" 8 "html/template"
12 - "io/ioutil"  
13 - "math/rand"  
14 "net/http" 9 "net/http"
15 "opp/internal/utils" 10 "opp/internal/utils"
  11 + "opp/services/agg"
16 "strconv" 12 "strconv"
17 "time" 13 "time"
18 14
@@ -21,7 +17,6 @@ import ( @@ -21,7 +17,6 @@ import (
21 "opp/internal/repository" 17 "opp/internal/repository"
22 "opp/models" 18 "opp/models"
23 "opp/protocol" 19 "opp/protocol"
24 - s_im "opp/services/im"  
25 s_sms "opp/services/sms" 20 s_sms "opp/services/sms"
26 21
27 "github.com/astaxie/beego" 22 "github.com/astaxie/beego"
@@ -40,65 +35,54 @@ var ( @@ -40,65 +35,54 @@ var (
40 //登录 35 //登录
41 func Login(header *protocol.RequestHeader, request *protocol.LoginRequest) (rsp *protocol.LoginResponse, err error) { 36 func Login(header *protocol.RequestHeader, request *protocol.LoginRequest) (rsp *protocol.LoginResponse, err error) {
42 var ( 37 var (
43 - user *models.User  
44 - userAuth *models.UserAuth  
45 - result bool  
46 - //checkImResponse *protocol.CheckImResponse  
47 - userCenterLogin *protocol.UserCenterLoginResponse 38 + user *models.User
  39 + userAuth *models.UserAuth
  40 + getUserRequest *protocol.UCenterGetUserRequest = &protocol.UCenterGetUserRequest{}
  41 + getUserResponse *protocol.UCenterGetUserResponse
  42 + message *protocol.Message
48 ) 43 )
49 - user, err = repository.User.GetUsersByMobile(request.Phone) 44 + user, err = models.GetUserByUcenterId(request.Uid)
50 if err != nil { 45 if err != nil {
51 log.Error(err) 46 log.Error(err)
52 err = protocol.NewErrWithMessage(2002, err) //账号不存在 47 err = protocol.NewErrWithMessage(2002, err) //账号不存在
53 return 48 return
54 } 49 }
55 - switch request.GrantType {  
56 - case protocol.LoginTypePassPord:  
57 - //if beego.BConfig.RunMode == "prod" {  
58 - //  
59 - //}  
60 - if userCenterLogin, err = userCenterAuthLogin(&protocol.UserCenterLoginRequest{  
61 - Phone: request.Phone,  
62 - PassWord: request.PassWord,  
63 - }); err != nil { 50 + //TODO:验证模块权限
  51 +
  52 + //从用户中心获取用户信息
  53 + if _, err = agg.RequestUserCenter(fmt.Sprintf("%v%v", protocol.MethodGetUser, request.Uid), http.MethodGet, getUserRequest, &message); err != nil {
  54 + log.Error(err)
  55 + return
  56 + }
  57 + log.Debug(fmt.Sprintf("ucenter_id:%v getuser response:", request.Uid), message.Errno, message.Errmsg)
  58 + if message.Errno == 0 && message.Errmsg == "ok" {
  59 + if err = message.Unmarshal(&getUserResponse); err != nil {
64 log.Error(err) 60 log.Error(err)
65 return 61 return
66 } 62 }
  63 + }
  64 + switch message.Errno {
  65 + case -1:
  66 + err = protocol.NewErrWithMessage(2002, err) //账号不存在
  67 + return
  68 + case 0:
67 goto Success 69 goto Success
68 - //if strings.Compare(user.Passwd, request.PassWord) == 0 {  
69 - // goto Success  
70 - //} else {  
71 - // err = protocol.NewErrWithMessage(2021, err) //登录密码错误  
72 - // return  
73 - //}  
74 - //break  
75 - case protocol.LoginTypeSmdcode:  
76 - //if beego.BConfig.RunMode =="dev"{  
77 - // goto Success  
78 - //}  
79 - if result, err = CheckSmsCode(request.Phone, request.Code, protocol.SmsCode); result && err == nil {  
80 - goto Success  
81 - } else {  
82 - //err = protocol.NewErrWithMessage(1012, err)  
83 - return  
84 - }  
85 - default:  
86 - err = fmt.Errorf("grantType error") 70 + case 2002:
  71 + err = protocol.NewErrWithMessage(2002, err) //账号不存在
87 return 72 return
  73 + default:
  74 + err = fmt.Errorf("error_no:%v msg:%v", message.Errno, message.Errmsg)
  75 + break
88 } 76 }
  77 +
89 Success: 78 Success:
90 { 79 {
91 - user, err = repository.User.GetUsersByMobile(request.Phone)  
92 - if err != nil {  
93 - log.Error(err)  
94 - return  
95 - }  
96 - userAuth, err = repository.UserAuth.GetUserAuthByUserId(user.Id, header.DeviceType) 80 + userAuth, err = repository.UserAuth.GetUserAuthByUserId(user.Id, 1)
97 if err != nil { 81 if err != nil {
98 if err == orm.ErrNoRows { 82 if err == orm.ErrNoRows {
99 userAuth = &models.UserAuth{ 83 userAuth = &models.UserAuth{
100 UserId: user.Id, 84 UserId: user.Id,
101 - DeviceType: int8(header.DeviceType), 85 + DeviceType: 1, //int8(header.DeviceType),
102 } 86 }
103 repository.UserAuth.AddUserAuth(userAuth) 87 repository.UserAuth.AddUserAuth(userAuth)
104 } else { 88 } else {
@@ -107,28 +91,14 @@ Success: @@ -107,28 +91,14 @@ Success:
107 } 91 }
108 } 92 }
109 userAuth.AuthCode = uid.NewV1().StringNoDash() 93 userAuth.AuthCode = uid.NewV1().StringNoDash()
110 - //if checkImResponse, err = CheckIm(&protocol.CheckImRequest{  
111 - // Uid: fmt.Sprintf("%v", user.Id),  
112 - // Uname: user.NickName,  
113 - // Icon: user.Icon,  
114 - // IsCreated: user.ImToken != "",  
115 - //}); err != nil {  
116 - // return  
117 - //}  
118 - //if checkImResponse != nil && checkImResponse.ImToken != "" {  
119 - // user.ImToken = checkImResponse.ImToken  
120 - //}  
121 - //if user.CsAccount == 0 {  
122 - // user.CsAccount = imGetRandomCSAccount()  
123 - //}  
124 94
125 /*更新用户信息*/ 95 /*更新用户信息*/
126 - user.CsAccount, _ = strconv.ParseInt(userCenterLogin.CustomerAccount, 10, 64)  
127 - user.ImToken = userCenterLogin.Token  
128 - user.Icon = userCenterLogin.Avatar  
129 - user.NickName = userCenterLogin.NickName  
130 - user.Accid, _ = strconv.ParseInt(userCenterLogin.Accid, 10, 64)  
131 - user.UserCenterId = userCenterLogin.Id 96 + user.CsAccount, _ = strconv.ParseInt(getUserResponse.CustomerAccount, 10, 64)
  97 + user.ImToken = getUserResponse.Token
  98 + user.Icon = getUserResponse.Avatar
  99 + user.NickName = getUserResponse.NickName
  100 + user.Accid, _ = strconv.ParseInt(getUserResponse.Accid, 10, 64)
  101 + user.UserCenterId = getUserResponse.Id
132 if err = repository.User.UpdateUserInfo(user); err != nil { 102 if err = repository.User.UpdateUserInfo(user); err != nil {
133 log.Error(err) 103 log.Error(err)
134 return 104 return
@@ -143,13 +113,60 @@ Success: @@ -143,13 +113,60 @@ Success:
143 return 113 return
144 } 114 }
145 115
  116 +//统一用户中心登录
  117 +func UCenterLogin(header *protocol.RequestHeader, request *protocol.UCenterLoginRequest) (rsp *protocol.UCenterLoginResponse, err error) {
  118 + var (
  119 + loginMethod = protocol.MethodLogin
  120 + //data []byte
  121 + loginResponse *protocol.UserCenterLoginResponse
  122 + )
  123 + var message protocol.Message
  124 + if _, err = agg.RequestUserCenter(loginMethod, http.MethodPost, request, &message); err != nil {
  125 + log.Error(err)
  126 + return
  127 + }
  128 + if message.Errno == 0 && message.Errmsg == "ok" {
  129 + if err = message.Unmarshal(&loginResponse); err != nil {
  130 + log.Error(err)
  131 + return
  132 + }
  133 + rsp = &protocol.UCenterLoginResponse{
  134 + Uid: loginResponse.Id,
  135 + Module: []*protocol.ModulePermission{
  136 + //TODO:取模块权限
  137 + &protocol.ModulePermission{
  138 + Name: protocol.ModuleOportunity,
  139 + },
  140 + &protocol.ModulePermission{
  141 + Name: protocol.ModuleQuestion,
  142 + },
  143 + },
  144 + }
  145 + }
  146 + log.Debug(fmt.Sprintf("simnum:%v login user-center response:", request.Phone), message.Errno, message.Errno)
  147 + switch message.Errno {
  148 + case -1:
  149 + err = protocol.NewErrWithMessage(2021, err) //密码错误
  150 + return
  151 + case 0:
  152 + break
  153 + case 2002:
  154 + err = protocol.NewErrWithMessage(2002, err) //账号不存在
  155 + return
  156 + default:
  157 + err = fmt.Errorf("error_no:%v msg:%v", message.Errno, message.Errmsg)
  158 + break
  159 + }
  160 +
  161 + return
  162 +}
  163 +
146 //更新设备信息 164 //更新设备信息
147 func UpdateDevice(header *protocol.RequestHeader, request *protocol.UpdateDeviceRequest) (rsp *protocol.UpdateDeviceResponse, err error) { 165 func UpdateDevice(header *protocol.RequestHeader, request *protocol.UpdateDeviceRequest) (rsp *protocol.UpdateDeviceResponse, err error) {
148 var ( 166 var (
149 userAuth *models.UserAuth 167 userAuth *models.UserAuth
150 updateMap = make(map[string]interface{}) 168 updateMap = make(map[string]interface{})
151 ) 169 )
152 - //rsp =&protocol.UpdateDeviceResponse{}  
153 if userAuth, err = repository.UserAuth.GetUserAuthByUserId(header.Uid, header.DeviceType); err != nil { 170 if userAuth, err = repository.UserAuth.GetUserAuthByUserId(header.Uid, header.DeviceType); err != nil {
154 log.Error(err) 171 log.Error(err)
155 return 172 return
@@ -225,14 +242,6 @@ func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshT @@ -225,14 +242,6 @@ func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshT
225 return 242 return
226 } 243 }
227 244
228 -//刷新token loginType mobile im web  
229 -//func refreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.Access, err error) {  
230 -// if request.Uid == 0 {  
231 -// return  
232 -// }  
233 -// return nil, nil  
234 -//}  
235 -  
236 //检查token有效性 245 //检查token有效性
237 func CheckToken(request *protocol.CheckTokenRequest) (rsp *protocol.CheckTokenResponse, err error) { 246 func CheckToken(request *protocol.CheckTokenRequest) (rsp *protocol.CheckTokenResponse, err error) {
238 var ( 247 var (
@@ -410,161 +419,3 @@ func Revoke(header *protocol.RequestHeader, request *protocol.RevokeRequest) (rs @@ -410,161 +419,3 @@ func Revoke(header *protocol.RequestHeader, request *protocol.RevokeRequest) (rs
410 } 419 }
411 return 420 return
412 } 421 }
413 -  
414 -func CheckIm(request *protocol.CheckImRequest) (rsp *protocol.CheckImResponse, err error) {  
415 - var ()  
416 - if beego.BConfig.RunMode != "prod" {  
417 - return  
418 - }  
419 - rsp = &protocol.CheckImResponse{}  
420 - if !request.IsCreated {  
421 - if err = imUserCreate(request, rsp); err != nil {  
422 - return  
423 - }  
424 - } else {  
425 - if err = imUserInfoUpdate(request, rsp); err != nil {  
426 - return  
427 - }  
428 - }  
429 - if err = imUserRefreshToken(request, rsp); err != nil {  
430 - return  
431 - }  
432 - return  
433 -}  
434 -  
435 -//create  
436 -func imUserCreate(request *protocol.CheckImRequest, rsp *protocol.CheckImResponse) (err error) {  
437 - var (  
438 - param s_im.UserCreate = s_im.UserCreate{  
439 - Accid: request.Uid,  
440 - Name: request.Uname,  
441 - Icon: request.Icon,  
442 - }  
443 - resp []byte  
444 - out s_im.UserTokenResult  
445 - )  
446 - if resp, err = s_im.DefaultImClient.Call(param); err != nil {  
447 - return  
448 - }  
449 - if err = json.Unmarshal(resp, &out); err != nil {  
450 - return  
451 - }  
452 - if out.Code != 200 || (out.Info.Accid != request.Uid) {  
453 - return s_im.ErrorFailCall  
454 - }  
455 - rsp.ImToken = out.Info.Token  
456 - return  
457 -}  
458 -  
459 -//update user info  
460 -func imUserInfoUpdate(request *protocol.CheckImRequest, rsp *protocol.CheckImResponse) (err error) {  
461 - var (  
462 - param s_im.UserUpdateUinfo = s_im.UserUpdateUinfo{  
463 - Accid: request.Uid,  
464 - Name: request.Uname,  
465 - Icon: request.Icon,  
466 - }  
467 - resp []byte  
468 - out s_im.BaseResp  
469 - )  
470 - if resp, err = s_im.DefaultImClient.Call(param); err != nil {  
471 - return  
472 - }  
473 - if err = json.Unmarshal(resp, &out); err != nil {  
474 - return  
475 - }  
476 - if out.Code != 200 {  
477 - return s_im.ErrorFailCall  
478 - }  
479 - return  
480 -}  
481 -  
482 -//refresh token  
483 -func imUserRefreshToken(request *protocol.CheckImRequest, rsp *protocol.CheckImResponse) (err error) {  
484 - var (  
485 - param s_im.UserRefreshToken = s_im.UserRefreshToken{  
486 - Accid: request.Uid,  
487 - }  
488 - resp []byte  
489 - out s_im.UserTokenResult  
490 - )  
491 - if resp, err = s_im.DefaultImClient.Call(param); err != nil {  
492 - return  
493 - }  
494 - if err = json.Unmarshal(resp, &out); err != nil {  
495 - return  
496 - }  
497 - if out.Code != 200 || (out.Info.Accid != request.Uid) {  
498 - return s_im.ErrorFailCall  
499 - }  
500 - rsp.ImToken = out.Info.Token  
501 - return  
502 -}  
503 -  
504 -// 获取客服id  
505 -func imGetRandomCSAccount() (acid int64) {  
506 - kefus, err := models.GetUserKefu()  
507 - if err != nil {  
508 - log.Error(err)  
509 - return  
510 - }  
511 - if len(kefus) <= 0 {  
512 - return  
513 - }  
514 - index := rand.Intn(len(kefus))  
515 - acid = kefus[index].Id //Accid  
516 - return acid  
517 -}  
518 -  
519 -//用户中心密码登录  
520 -func userCenterAuthLogin(request *protocol.UserCenterLoginRequest) (rsp *protocol.UserCenterLoginResponse, err error) {  
521 - var (  
522 - loginMethod = "/auth/login"  
523 - httpRsp *http.Response  
524 - data []byte  
525 - curTime = fmt.Sprintf("%v", time.Now().Unix())  
526 - appKey = beego.AppConfig.String("user_center_app_key")  
527 - salt = beego.AppConfig.String("user_center_salt")  
528 - )  
529 - rsp = &protocol.UserCenterLoginResponse{}  
530 - httpReq := httplib.Post(beego.AppConfig.String("user_center_url") + loginMethod)  
531 - httpReq.JSONBody(request)  
532 - httpReq.Header("appKey", appKey)  
533 - httpReq.Header("curTime", curTime)  
534 - httpReq.Header("checkSum", getUserCenterCheckSum(curTime, "", beego.AppConfig.String("user_center_app_secret"), salt))  
535 - if httpRsp, err = httpReq.DoRequest(); err != nil {  
536 - log.Error(err)  
537 - return  
538 - }  
539 - data, err = ioutil.ReadAll(httpRsp.Body)  
540 - defer httpRsp.Body.Close()  
541 - if err != nil {  
542 - log.Error(err)  
543 - return  
544 - }  
545 - log.Info(fmt.Sprintf("simnum:%v login user-center response:%v", request.Phone, string(data)))  
546 - type msg struct {  
547 - protocol.ErrorCode  
548 - Data *protocol.UserCenterLoginResponse `json:"data"`  
549 - }  
550 - var message protocol.Message  
551 - if err = json.Unmarshal(data, &message); err != nil {  
552 - log.Error(err)  
553 - return  
554 - }  
555 - if message.Errno == 0 && message.Errmsg == "ok" {  
556 - if err = message.Unmarshal(&rsp); err != nil {  
557 - log.Error(err)  
558 - return  
559 - }  
560 - } else {  
561 - err = fmt.Errorf("error_no:%v msg:%v", message.Errno, message.Errmsg)  
562 - }  
563 - return  
564 -}  
565 -  
566 -func getUserCenterCheckSum(curTime, nonce, appKey, salt string) string {  
567 - sha1 := sha1.New()  
568 - sum := sha1.Sum([]byte(fmt.Sprintf("%s%s%s%s", curTime, nonce, appKey, salt)))  
569 - return hex.EncodeToString(sum)  
570 -}  
1 package auth 1 package auth
2 2
3 import ( 3 import (
4 - "gitlab.fjmaimaimai.com/mmm-go/gocomm/common"  
5 "opp/internal/repository" 4 "opp/internal/repository"
6 "testing" 5 "testing"
7 6
@@ -40,10 +39,7 @@ func Test_SmsCode(t *testing.T) { @@ -40,10 +39,7 @@ func Test_SmsCode(t *testing.T) {
40 39
41 func Test_Login(t *testing.T) { 40 func Test_Login(t *testing.T) {
42 login := &protocol.LoginRequest{ 41 login := &protocol.LoginRequest{
43 - Phone: "18065048389",  
44 - Code: "562246",  
45 - GrantType: "signInPassword",  
46 - PassWord: "$2y$10$YWg7jPRVLBzc3kevokMkW.boswtCvhToqC.TappIwfqwJ.cI0efvy", 42 + Uid: 1,
47 //ClientId:"123456", 43 //ClientId:"123456",
48 } 44 }
49 loginRsp, err := Login(&protocol.RequestHeader{}, login) 45 loginRsp, err := Login(&protocol.RequestHeader{}, login)
@@ -67,16 +63,3 @@ func Test_RefreshToken(t *testing.T) { @@ -67,16 +63,3 @@ func Test_RefreshToken(t *testing.T) {
67 t.Fatal(err, rsp) 63 t.Fatal(err, rsp)
68 } 64 }
69 } 65 }
70 -  
71 -//测试用户中心登录  
72 -func Test_UserCenterAuthLogin(t *testing.T) {  
73 - if rsp, err := userCenterAuthLogin(&protocol.UserCenterLoginRequest{  
74 - Phone: "18065048301",  
75 - PassWord: "123456",  
76 - }); err != nil {  
77 - t.Log(err)  
78 - return  
79 - } else {  
80 - t.Log(common.AssertJson(rsp))  
81 - }  
82 -}  
@@ -2,10 +2,12 @@ package user @@ -2,10 +2,12 @@ package user
2 2
3 import ( 3 import (
4 "gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log" 4 "gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
  5 + "net/http"
5 "opp/internal/repository" 6 "opp/internal/repository"
6 "opp/internal/utils" 7 "opp/internal/utils"
7 "opp/models" 8 "opp/models"
8 "opp/protocol" 9 "opp/protocol"
  10 + "opp/services/agg"
9 "opp/services/auth" 11 "opp/services/auth"
10 "strings" 12 "strings"
11 ) 13 )
@@ -86,7 +88,8 @@ func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswo @@ -86,7 +88,8 @@ func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswo
86 //修改密码 88 //修改密码
87 func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePasswordRequest) (rsp *protocol.ChangePasswordResponse, err error) { 89 func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePasswordRequest) (rsp *protocol.ChangePasswordResponse, err error) {
88 var ( 90 var (
89 - user *models.User 91 + user *models.User
  92 + loginResponse *protocol.UserCenterLoginResponse
90 ) 93 )
91 //rsp =&protocol.ChangePasswordResponse{} 94 //rsp =&protocol.ChangePasswordResponse{}
92 if !strings.EqualFold(request.NewPwd, request.ConfirmPwd) { 95 if !strings.EqualFold(request.NewPwd, request.ConfirmPwd) {
@@ -97,6 +100,8 @@ func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePass @@ -97,6 +100,8 @@ func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePass
97 err = protocol.NewErrWithMessage(2027) 100 err = protocol.NewErrWithMessage(2027)
98 return 101 return
99 } 102 }
  103 +
  104 + //old
100 if user, err = repository.User.GetUsersById(header.Uid); err != nil { 105 if user, err = repository.User.GetUsersById(header.Uid); err != nil {
101 log.Error(err) 106 log.Error(err)
102 return 107 return
@@ -105,6 +110,32 @@ func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePass @@ -105,6 +110,32 @@ func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePass
105 err = protocol.NewErrWithMessage(2028) 110 err = protocol.NewErrWithMessage(2028)
106 return 111 return
107 } 112 }
  113 +
  114 + //new
  115 + var message protocol.Message
  116 + if _, err = agg.RequestUserCenter(protocol.MethodLogin, http.MethodPost, &protocol.UCenterLoginRequest{
  117 + PassWord: request.OldPwd,
  118 + Phone: user.Phone,
  119 + }, &message); err != nil {
  120 + log.Error(err)
  121 + return
  122 + }
  123 + if message.Errno == 0 && message.Errmsg == "ok" {
  124 + if err = message.Unmarshal(&loginResponse); err != nil {
  125 + log.Error(err)
  126 + return
  127 + }
  128 + if loginResponse.Id != user.UserCenterId {
  129 + err = protocol.NewErrWithMessage(1)
  130 + return
  131 + }
  132 +
  133 + //修改密码
  134 + if _, err = agg.RequestUserCenter(protocol.MethodGetUser, http.MethodPut, nil, &message); err != nil {
  135 +
  136 + }
  137 + }
  138 +
108 err = utils.UpdateTableByMap(&models.User{Id: user.Id}, map[string]interface{}{"Passwd": request.NewPwd}) 139 err = utils.UpdateTableByMap(&models.User{Id: user.Id}, map[string]interface{}{"Passwd": request.NewPwd})
109 return 140 return
110 } 141 }
1 -## 认证 1 +
  2 +## 统一用户中心
2 3
3 ### 登录 4 ### 登录
4 5
5 -* URL: /v1/auth/login 6 +* URL: /v1/ucenter/login
6 * 格式: JSON 7 * 格式: JSON
7 * HTTP请求方式: POST 8 * HTTP请求方式: POST
8 * 请求示例 9 * 请求示例
@@ -11,8 +12,46 @@ @@ -11,8 +12,46 @@
11 "phone": "18860180001", 12 "phone": "18860180001",
12 "code": "784657", 13 "code": "784657",
13 "grantType": "signInPassword", 14 "grantType": "signInPassword",
14 - "password": "123456",  
15 - "clientId": "signInPassword" 15 + "password": "123456"
  16 +}
  17 +```
  18 +
  19 +
  20 +* 应答示例
  21 +```json
  22 +{
  23 + "code": 0,
  24 + "msg": "成功",
  25 + "data": {
  26 + "uid": 3507839547244544,
  27 + "module": [
  28 + {
  29 + "name": "opportunity"
  30 + },
  31 + {
  32 + "name": "question"
  33 + }
  34 + ]
  35 + }
  36 +}
  37 +```
  38 +
  39 +```
  40 +data.uid 统一用户中心uid
  41 +data.module 有权限的模块
  42 +```
  43 +
  44 +## 认证
  45 +
  46 +### 登录
  47 +
  48 +* URL: /v1/auth/login
  49 +* 格式: JSON
  50 +* HTTP请求方式: POST
  51 +* 请求示例
  52 +```json
  53 +{
  54 + "uid":3507839547244544
16 } 55 }
17 ``` 56 ```
18 57
@@ -23,7 +62,7 @@ @@ -23,7 +62,7 @@
23 "code": 0, 62 "code": 0,
24 "msg": "登录成功", 63 "msg": "登录成功",
25 "data": { 64 "data": {
26 - "authCode": "5251839614a611eaab01000c29ad8d6d" 65 + "authCode": "f7641e7d1cb811ea942d000c29ad8d6d"
27 } 66 }
28 } 67 }
29 ``` 68 ```