作者 yangfu

统一用户中心修改

package v1
import (
"encoding/json"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"opp/controllers"
"opp/protocol"
"opp/services/auth"
)
type UcenterController struct {
controllers.BaseController
}
//UCenterLogin
//@router /login [post]
func (this *UcenterController) UCenterLogin() {
var msg *protocol.ResponseMessage
defer func() {
this.Resp(msg)
}()
var request *protocol.UCenterLoginRequest
if err := json.Unmarshal(this.ByteBody, &request); err != nil {
log.Error(err)
msg = protocol.BadRequestParam(1)
return
}
if b, m := this.Valid(request); !b {
msg = m
return
}
header := controllers.GetRequestHeader(this.Ctx)
msg = protocol.NewReturnResponse(auth.UCenterLogin(header, request))
}
... ...
... ... @@ -10,7 +10,6 @@ import (
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/orm"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/redis"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/websocket"
"opp/controllers"
"opp/internal/utils"
_ "opp/routers"
"opp/services/im"
... ... @@ -63,7 +62,6 @@ func main() {
defer func() {
log.Info("app on stop!")
}()
beego.InsertFilter("/*", beego.BeforeRouter, controllers.FilterComm)
log.Info("app on start!")
log.Info("Beego Run Mode:", beego.BConfig.RunMode)
... ...
... ... @@ -83,19 +83,19 @@ func DeleteUsers(id int64) (err error) {
return
}
func GetUserKefu() (v []*User, err error) {
func GetUserByMobile(mobile string) (v *User, err error) {
o := orm.NewOrm()
sql := `select * from user where is_kefu = 1 and enable_status=1`
if _, err = o.Raw(sql).QueryRows(&v); err == nil {
sql := "select * from user where phone=? and enable_status=1"
if err = o.Raw(sql, mobile).QueryRow(&v); err == nil {
return v, nil
}
return nil, err
}
func GetUserByMobile(mobile string) (v *User, err error) {
func GetUserByUcenterId(uid int64) (v *User, err error) {
o := orm.NewOrm()
sql := "select * from user where phone=? and enable_status=1"
if err = o.Raw(sql, mobile).QueryRow(&v); err == nil {
sql := "select * from user where user_center_id=? and enable_status=1"
if err = o.Raw(sql, uid).QueryRow(&v); err == nil {
return v, nil
}
return nil, err
... ...
... ... @@ -26,11 +26,7 @@ type RequestHeader struct {
/*Login */
type LoginRequest struct {
Phone string `json:"phone" valid:"Required;Mobile"`
Code string `json:"code"`
GrantType string `json:"grantType" valid:"Required"`
PassWord string `json:"password"`
ClientId string `json:"clientId" valid:"Required"`
Uid int64 `json:"uid" valid:"Required;"`
}
type LoginResponse struct {
AuthCode string `json:"authCode"`
... ... @@ -38,8 +34,11 @@ type LoginResponse struct {
/*统一用户中心登录*/
type UserCenterLoginRequest struct {
Phone string `json:"phone"`
PassWord string `json:"password"`
Phone string `json:"phone"`
PassWord string `json:"password"`
Code string `json:"code"`
GrantType string `json:"grantType" valid:"Required"`
ClientId string `json:"clientId" valid:"Required"`
}
type UserCenterLoginResponse struct {
... ...
... ... @@ -90,3 +90,58 @@ func (m Message) Unmarshal(v interface{}) error {
}
return json.Unmarshal(m.Data, v)
}
/**************公告****************/
type Question struct {
Id int `json:"id"`
Type int `json:"type" valid:"Required"`
Title string `json:"title" valid:"Required"`
Content []QuestionContent `json:"content" valid:"Required"`
}
type QuestionContent struct {
Id int `json:"id" valid:"Required"`
Content string `json:"content" valid:"Required"`
}
type Cover struct {
Path string `json:"path" valid:"Required"`
H int `json:"h"`
W int `json:"w"`
}
/*公告列表 BulletinList */
type BulletinListRequest struct {
}
type BulletinListResponse struct {
List []*BulletinItem `json:"list"`
Total int
}
type BulletinItem struct {
Id int `json:"id"`
Type int8 `json:"type"`
Title string `json:"title"`
Status int8 `json:"status"`
Receiver []Receiver `json:"receiver" valid:"Required"`
CreateAt string `json:"time"`
}
/*GetBulletin */
type GetBulletinRequest struct {
}
type GetBulletinResponse struct {
Id int `json:"id"`
Type int `json:"type" valid:"Required"`
Title string `json:"title" valid:"Required"`
Content string `json:"content" valid:"Required"`
AllowClose int `json:"allow_close"`
//AllowCondition int `json:"allow_condition"`
QuestionSwitch int `json:"question_switch"`
Receiver []Receiver `json:"receiver" valid:"Required"`
Question Question `json:"question"`
Cover Cover `json:"cover" valid:"Required"`
}
type Receiver struct {
Id int64 `json:"id"`
NickName string `json:"name"`
}
... ...
package protocol
const (
ModuleOportunity = "opportunity"
ModuleQuestion = "question"
)
const (
MethodLogin = "/auth/login"
MethodGetUser = "/users/"
)
/*UCenterLogin */
type UCenterLoginRequest struct {
Phone string `json:"phone"`
PassWord string `json:"password"`
Code string `json:"code"`
GrantType string `json:"grantType" valid:"Required"`
//ClientId string `json:"clientId" valid:"Required"`
}
type UCenterLoginResponse struct {
Uid int64 `json:"uid"` //统一用户中心用户编号,作为登录凭证
Module []*ModulePermission `json:"module"`
}
//模块权限 (机会)opportunity (问题)question
type ModulePermission struct {
Name string `json:"name"` //模块名称 子菜单名称 `
Menus []*ModulePermission `json:"-"` //子模块权限
}
/*UCenterGetUser */
type UCenterGetUserRequest struct {
}
type UCenterGetUserResponse struct {
Id int64 `json:"id"`
Phone string `json:"phone"`
NickName string `json:"nickname"`
Avatar string `json:"avatar"`
Token string `json:"token"`
Accid string `json:"accid"`
CustomerAccount string `json:"customerAccount"`
}
... ...
... ... @@ -183,6 +183,14 @@ func init() {
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:UcenterController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:UcenterController"],
beego.ControllerComments{
Method: "UCenterLogin",
Router: `/login`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Params: nil})
beego.GlobalControllerRouter["opp/controllers/v1:UploadController"] = append(beego.GlobalControllerRouter["opp/controllers/v1:UploadController"],
beego.ControllerComments{
Method: "Image",
... ...
... ... @@ -3,26 +3,26 @@ package routers
import (
"github.com/astaxie/beego"
"github.com/prometheus/client_golang/prometheus/promhttp"
"net/http"
"opp/controllers"
"opp/controllers/v1"
"opp/services/websocket"
)
var nsV1 *beego.Namespace
func init() {
nsV1 := beego.NewNamespace("v1",
beego.NSNamespace("auth", beego.NSInclude(&v1.AuthController{})),
beego.NSNamespace("upload", beego.NSInclude(&v1.UploadController{})),
beego.NSNamespace("version", beego.NSInclude(&v1.VersionController{})),
beego.NSNamespace("commend", beego.NSInclude(&v1.CommendController{})),
beego.NSNamespace("user", beego.NSInclude(&v1.UserController{})),
beego.NSNamespace("chance", beego.NSInclude(&v1.ChanceController{})),
beego.NSNamespace("message", beego.NSInclude(&v1.MessageController{})),
beego.NSNamespace("department", beego.NSInclude(&v1.DepartmentController{})),
beego.NSNamespace("ucenter", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.UcenterController{})),
beego.NSNamespace("auth", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.AuthController{})),
beego.NSNamespace("upload", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.UploadController{})),
beego.NSNamespace("version", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.VersionController{})),
beego.NSNamespace("commend", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.CommendController{})),
beego.NSNamespace("user", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.UserController{})),
beego.NSNamespace("chance", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.ChanceController{})),
beego.NSNamespace("message", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.MessageController{})),
beego.NSNamespace("department", beego.NSBefore(controllers.FilterComm), beego.NSInclude(&v1.DepartmentController{})),
)
beego.AddNamespace(nsV1)
beego.SetStaticPath("/file/opp", beego.AppConfig.String("source_path"))
beego.Handler("/metrics", promhttp.Handler())
beego.Handler("/upgrage", http.HandlerFunc(websocket.Upgrage))
//beego.Handler("/upgrage", http.HandlerFunc(websocket.Upgrage))
}
... ...
... ... @@ -51,6 +51,7 @@ func GetUserBaseInfoAggregation(uid int64, companyId int64) (v *protocol.UserBas
return
}
//获取用户基础数据
func GetUserBaseInfo(uid int64, companyId int64) (v *protocol.BaseUserInfo, err error) {
var (
agg *protocol.UserBaseInfoAggregation
... ... @@ -122,6 +123,7 @@ func GetTopPosition(positions []*protocol.Position) *protocol.Position {
return top
}
//获取机会
func GetChance(chanceId int64, companyId int64) (v *protocol.ChanceDetail, err error) {
var (
c *models.Chance
... ... @@ -147,6 +149,7 @@ func GetChance(chanceId int64, companyId int64) (v *protocol.ChanceDetail, err e
return
}
//构建统计sql语句
func GetIncrementSql(table string, column string, incre int, id int64) *utils.SqlData {
var sql *bytes.Buffer
sql = bytes.NewBuffer(nil)
... ...
package agg
import (
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/httplib"
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"io/ioutil"
"net/http"
"time"
)
/****************用户中心******************/
//请求用户中心接口
func RequestUserCenter(method string, httpMethod, request interface{}, rsponse interface{}) (data []byte, err error) {
var (
httpRsp *http.Response
curTime = fmt.Sprintf("%v", time.Now().Unix())
appKey = beego.AppConfig.String("user_center_app_key")
salt = beego.AppConfig.String("user_center_salt")
httpReq *httplib.BeegoHTTPRequest
)
if httpMethod == http.MethodGet {
httpReq = httplib.Get(beego.AppConfig.String("user_center_url") + method)
} else if httpMethod == http.MethodPost {
httpReq = httplib.Post(beego.AppConfig.String("user_center_url") + method)
} else if httpMethod == http.MethodPut {
httpReq = httplib.Put(beego.AppConfig.String("user_center_url") + method)
}
httpReq.JSONBody(request)
httpReq.Header("appKey", appKey)
httpReq.Header("curTime", curTime)
httpReq.Header("checkSum", getUserCenterCheckSum(curTime, "", beego.AppConfig.String("user_center_app_secret"), salt))
if httpRsp, err = httpReq.DoRequest(); err != nil {
log.Error(err)
return
}
data, err = ioutil.ReadAll(httpRsp.Body)
defer httpRsp.Body.Close()
if err != nil {
log.Error(err)
return
}
if err = json.Unmarshal(data, rsponse); err != nil {
log.Error(err)
return
}
return
}
//计算check_sum
func getUserCenterCheckSum(curTime, nonce, appKey, salt string) string {
sha1 := sha1.New()
sum := sha1.Sum([]byte(fmt.Sprintf("%s%s%s%s", curTime, nonce, appKey, salt)))
return hex.EncodeToString(sum)
}
... ...
... ... @@ -2,17 +2,13 @@ package auth
import (
"bytes"
"crypto/sha1"
"encoding/hex"
"encoding/json"
"fmt"
"github.com/astaxie/beego/httplib"
"github.com/astaxie/beego/orm"
"html/template"
"io/ioutil"
"math/rand"
"net/http"
"opp/internal/utils"
"opp/services/agg"
"strconv"
"time"
... ... @@ -21,7 +17,6 @@ import (
"opp/internal/repository"
"opp/models"
"opp/protocol"
s_im "opp/services/im"
s_sms "opp/services/sms"
"github.com/astaxie/beego"
... ... @@ -40,65 +35,54 @@ var (
//登录
func Login(header *protocol.RequestHeader, request *protocol.LoginRequest) (rsp *protocol.LoginResponse, err error) {
var (
user *models.User
userAuth *models.UserAuth
result bool
//checkImResponse *protocol.CheckImResponse
userCenterLogin *protocol.UserCenterLoginResponse
user *models.User
userAuth *models.UserAuth
getUserRequest *protocol.UCenterGetUserRequest = &protocol.UCenterGetUserRequest{}
getUserResponse *protocol.UCenterGetUserResponse
message *protocol.Message
)
user, err = repository.User.GetUsersByMobile(request.Phone)
user, err = models.GetUserByUcenterId(request.Uid)
if err != nil {
log.Error(err)
err = protocol.NewErrWithMessage(2002, err) //账号不存在
return
}
switch request.GrantType {
case protocol.LoginTypePassPord:
//if beego.BConfig.RunMode == "prod" {
//
//}
if userCenterLogin, err = userCenterAuthLogin(&protocol.UserCenterLoginRequest{
Phone: request.Phone,
PassWord: request.PassWord,
}); err != nil {
//TODO:验证模块权限
//从用户中心获取用户信息
if _, err = agg.RequestUserCenter(fmt.Sprintf("%v%v", protocol.MethodGetUser, request.Uid), http.MethodGet, getUserRequest, &message); err != nil {
log.Error(err)
return
}
log.Debug(fmt.Sprintf("ucenter_id:%v getuser response:", request.Uid), message.Errno, message.Errmsg)
if message.Errno == 0 && message.Errmsg == "ok" {
if err = message.Unmarshal(&getUserResponse); err != nil {
log.Error(err)
return
}
}
switch message.Errno {
case -1:
err = protocol.NewErrWithMessage(2002, err) //账号不存在
return
case 0:
goto Success
//if strings.Compare(user.Passwd, request.PassWord) == 0 {
// goto Success
//} else {
// err = protocol.NewErrWithMessage(2021, err) //登录密码错误
// return
//}
//break
case protocol.LoginTypeSmdcode:
//if beego.BConfig.RunMode =="dev"{
// goto Success
//}
if result, err = CheckSmsCode(request.Phone, request.Code, protocol.SmsCode); result && err == nil {
goto Success
} else {
//err = protocol.NewErrWithMessage(1012, err)
return
}
default:
err = fmt.Errorf("grantType error")
case 2002:
err = protocol.NewErrWithMessage(2002, err) //账号不存在
return
default:
err = fmt.Errorf("error_no:%v msg:%v", message.Errno, message.Errmsg)
break
}
Success:
{
user, err = repository.User.GetUsersByMobile(request.Phone)
if err != nil {
log.Error(err)
return
}
userAuth, err = repository.UserAuth.GetUserAuthByUserId(user.Id, header.DeviceType)
userAuth, err = repository.UserAuth.GetUserAuthByUserId(user.Id, 1)
if err != nil {
if err == orm.ErrNoRows {
userAuth = &models.UserAuth{
UserId: user.Id,
DeviceType: int8(header.DeviceType),
DeviceType: 1, //int8(header.DeviceType),
}
repository.UserAuth.AddUserAuth(userAuth)
} else {
... ... @@ -107,28 +91,14 @@ Success:
}
}
userAuth.AuthCode = uid.NewV1().StringNoDash()
//if checkImResponse, err = CheckIm(&protocol.CheckImRequest{
// Uid: fmt.Sprintf("%v", user.Id),
// Uname: user.NickName,
// Icon: user.Icon,
// IsCreated: user.ImToken != "",
//}); err != nil {
// return
//}
//if checkImResponse != nil && checkImResponse.ImToken != "" {
// user.ImToken = checkImResponse.ImToken
//}
//if user.CsAccount == 0 {
// user.CsAccount = imGetRandomCSAccount()
//}
/*更新用户信息*/
user.CsAccount, _ = strconv.ParseInt(userCenterLogin.CustomerAccount, 10, 64)
user.ImToken = userCenterLogin.Token
user.Icon = userCenterLogin.Avatar
user.NickName = userCenterLogin.NickName
user.Accid, _ = strconv.ParseInt(userCenterLogin.Accid, 10, 64)
user.UserCenterId = userCenterLogin.Id
user.CsAccount, _ = strconv.ParseInt(getUserResponse.CustomerAccount, 10, 64)
user.ImToken = getUserResponse.Token
user.Icon = getUserResponse.Avatar
user.NickName = getUserResponse.NickName
user.Accid, _ = strconv.ParseInt(getUserResponse.Accid, 10, 64)
user.UserCenterId = getUserResponse.Id
if err = repository.User.UpdateUserInfo(user); err != nil {
log.Error(err)
return
... ... @@ -143,13 +113,60 @@ Success:
return
}
//统一用户中心登录
func UCenterLogin(header *protocol.RequestHeader, request *protocol.UCenterLoginRequest) (rsp *protocol.UCenterLoginResponse, err error) {
var (
loginMethod = protocol.MethodLogin
//data []byte
loginResponse *protocol.UserCenterLoginResponse
)
var message protocol.Message
if _, err = agg.RequestUserCenter(loginMethod, http.MethodPost, request, &message); err != nil {
log.Error(err)
return
}
if message.Errno == 0 && message.Errmsg == "ok" {
if err = message.Unmarshal(&loginResponse); err != nil {
log.Error(err)
return
}
rsp = &protocol.UCenterLoginResponse{
Uid: loginResponse.Id,
Module: []*protocol.ModulePermission{
//TODO:取模块权限
&protocol.ModulePermission{
Name: protocol.ModuleOportunity,
},
&protocol.ModulePermission{
Name: protocol.ModuleQuestion,
},
},
}
}
log.Debug(fmt.Sprintf("simnum:%v login user-center response:", request.Phone), message.Errno, message.Errno)
switch message.Errno {
case -1:
err = protocol.NewErrWithMessage(2021, err) //密码错误
return
case 0:
break
case 2002:
err = protocol.NewErrWithMessage(2002, err) //账号不存在
return
default:
err = fmt.Errorf("error_no:%v msg:%v", message.Errno, message.Errmsg)
break
}
return
}
//更新设备信息
func UpdateDevice(header *protocol.RequestHeader, request *protocol.UpdateDeviceRequest) (rsp *protocol.UpdateDeviceResponse, err error) {
var (
userAuth *models.UserAuth
updateMap = make(map[string]interface{})
)
//rsp =&protocol.UpdateDeviceResponse{}
if userAuth, err = repository.UserAuth.GetUserAuthByUserId(header.Uid, header.DeviceType); err != nil {
log.Error(err)
return
... ... @@ -225,14 +242,6 @@ func RefreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.RefreshT
return
}
//刷新token loginType mobile im web
//func refreshToken(request *protocol.RefreshTokenRequest) (rsp *protocol.Access, err error) {
// if request.Uid == 0 {
// return
// }
// return nil, nil
//}
//检查token有效性
func CheckToken(request *protocol.CheckTokenRequest) (rsp *protocol.CheckTokenResponse, err error) {
var (
... ... @@ -410,161 +419,3 @@ func Revoke(header *protocol.RequestHeader, request *protocol.RevokeRequest) (rs
}
return
}
func CheckIm(request *protocol.CheckImRequest) (rsp *protocol.CheckImResponse, err error) {
var ()
if beego.BConfig.RunMode != "prod" {
return
}
rsp = &protocol.CheckImResponse{}
if !request.IsCreated {
if err = imUserCreate(request, rsp); err != nil {
return
}
} else {
if err = imUserInfoUpdate(request, rsp); err != nil {
return
}
}
if err = imUserRefreshToken(request, rsp); err != nil {
return
}
return
}
//create
func imUserCreate(request *protocol.CheckImRequest, rsp *protocol.CheckImResponse) (err error) {
var (
param s_im.UserCreate = s_im.UserCreate{
Accid: request.Uid,
Name: request.Uname,
Icon: request.Icon,
}
resp []byte
out s_im.UserTokenResult
)
if resp, err = s_im.DefaultImClient.Call(param); err != nil {
return
}
if err = json.Unmarshal(resp, &out); err != nil {
return
}
if out.Code != 200 || (out.Info.Accid != request.Uid) {
return s_im.ErrorFailCall
}
rsp.ImToken = out.Info.Token
return
}
//update user info
func imUserInfoUpdate(request *protocol.CheckImRequest, rsp *protocol.CheckImResponse) (err error) {
var (
param s_im.UserUpdateUinfo = s_im.UserUpdateUinfo{
Accid: request.Uid,
Name: request.Uname,
Icon: request.Icon,
}
resp []byte
out s_im.BaseResp
)
if resp, err = s_im.DefaultImClient.Call(param); err != nil {
return
}
if err = json.Unmarshal(resp, &out); err != nil {
return
}
if out.Code != 200 {
return s_im.ErrorFailCall
}
return
}
//refresh token
func imUserRefreshToken(request *protocol.CheckImRequest, rsp *protocol.CheckImResponse) (err error) {
var (
param s_im.UserRefreshToken = s_im.UserRefreshToken{
Accid: request.Uid,
}
resp []byte
out s_im.UserTokenResult
)
if resp, err = s_im.DefaultImClient.Call(param); err != nil {
return
}
if err = json.Unmarshal(resp, &out); err != nil {
return
}
if out.Code != 200 || (out.Info.Accid != request.Uid) {
return s_im.ErrorFailCall
}
rsp.ImToken = out.Info.Token
return
}
// 获取客服id
func imGetRandomCSAccount() (acid int64) {
kefus, err := models.GetUserKefu()
if err != nil {
log.Error(err)
return
}
if len(kefus) <= 0 {
return
}
index := rand.Intn(len(kefus))
acid = kefus[index].Id //Accid
return acid
}
//用户中心密码登录
func userCenterAuthLogin(request *protocol.UserCenterLoginRequest) (rsp *protocol.UserCenterLoginResponse, err error) {
var (
loginMethod = "/auth/login"
httpRsp *http.Response
data []byte
curTime = fmt.Sprintf("%v", time.Now().Unix())
appKey = beego.AppConfig.String("user_center_app_key")
salt = beego.AppConfig.String("user_center_salt")
)
rsp = &protocol.UserCenterLoginResponse{}
httpReq := httplib.Post(beego.AppConfig.String("user_center_url") + loginMethod)
httpReq.JSONBody(request)
httpReq.Header("appKey", appKey)
httpReq.Header("curTime", curTime)
httpReq.Header("checkSum", getUserCenterCheckSum(curTime, "", beego.AppConfig.String("user_center_app_secret"), salt))
if httpRsp, err = httpReq.DoRequest(); err != nil {
log.Error(err)
return
}
data, err = ioutil.ReadAll(httpRsp.Body)
defer httpRsp.Body.Close()
if err != nil {
log.Error(err)
return
}
log.Info(fmt.Sprintf("simnum:%v login user-center response:%v", request.Phone, string(data)))
type msg struct {
protocol.ErrorCode
Data *protocol.UserCenterLoginResponse `json:"data"`
}
var message protocol.Message
if err = json.Unmarshal(data, &message); err != nil {
log.Error(err)
return
}
if message.Errno == 0 && message.Errmsg == "ok" {
if err = message.Unmarshal(&rsp); err != nil {
log.Error(err)
return
}
} else {
err = fmt.Errorf("error_no:%v msg:%v", message.Errno, message.Errmsg)
}
return
}
func getUserCenterCheckSum(curTime, nonce, appKey, salt string) string {
sha1 := sha1.New()
sum := sha1.Sum([]byte(fmt.Sprintf("%s%s%s%s", curTime, nonce, appKey, salt)))
return hex.EncodeToString(sum)
}
... ...
package auth
import (
"gitlab.fjmaimaimai.com/mmm-go/gocomm/common"
"opp/internal/repository"
"testing"
... ... @@ -40,10 +39,7 @@ func Test_SmsCode(t *testing.T) {
func Test_Login(t *testing.T) {
login := &protocol.LoginRequest{
Phone: "18065048389",
Code: "562246",
GrantType: "signInPassword",
PassWord: "$2y$10$YWg7jPRVLBzc3kevokMkW.boswtCvhToqC.TappIwfqwJ.cI0efvy",
Uid: 1,
//ClientId:"123456",
}
loginRsp, err := Login(&protocol.RequestHeader{}, login)
... ... @@ -67,16 +63,3 @@ func Test_RefreshToken(t *testing.T) {
t.Fatal(err, rsp)
}
}
//测试用户中心登录
func Test_UserCenterAuthLogin(t *testing.T) {
if rsp, err := userCenterAuthLogin(&protocol.UserCenterLoginRequest{
Phone: "18065048301",
PassWord: "123456",
}); err != nil {
t.Log(err)
return
} else {
t.Log(common.AssertJson(rsp))
}
}
... ...
... ... @@ -2,10 +2,12 @@ package user
import (
"gitlab.fjmaimaimai.com/mmm-go/gocomm/pkg/log"
"net/http"
"opp/internal/repository"
"opp/internal/utils"
"opp/models"
"opp/protocol"
"opp/services/agg"
"opp/services/auth"
"strings"
)
... ... @@ -86,7 +88,8 @@ func ResetPassword(header *protocol.RequestHeader, request *protocol.ResetPasswo
//修改密码
func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePasswordRequest) (rsp *protocol.ChangePasswordResponse, err error) {
var (
user *models.User
user *models.User
loginResponse *protocol.UserCenterLoginResponse
)
//rsp =&protocol.ChangePasswordResponse{}
if !strings.EqualFold(request.NewPwd, request.ConfirmPwd) {
... ... @@ -97,6 +100,8 @@ func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePass
err = protocol.NewErrWithMessage(2027)
return
}
//old
if user, err = repository.User.GetUsersById(header.Uid); err != nil {
log.Error(err)
return
... ... @@ -105,6 +110,32 @@ func ChangePassword(header *protocol.RequestHeader, request *protocol.ChangePass
err = protocol.NewErrWithMessage(2028)
return
}
//new
var message protocol.Message
if _, err = agg.RequestUserCenter(protocol.MethodLogin, http.MethodPost, &protocol.UCenterLoginRequest{
PassWord: request.OldPwd,
Phone: user.Phone,
}, &message); err != nil {
log.Error(err)
return
}
if message.Errno == 0 && message.Errmsg == "ok" {
if err = message.Unmarshal(&loginResponse); err != nil {
log.Error(err)
return
}
if loginResponse.Id != user.UserCenterId {
err = protocol.NewErrWithMessage(1)
return
}
//修改密码
if _, err = agg.RequestUserCenter(protocol.MethodGetUser, http.MethodPut, nil, &message); err != nil {
}
}
err = utils.UpdateTableByMap(&models.User{Id: user.Id}, map[string]interface{}{"Passwd": request.NewPwd})
return
}
... ...
## 认证
## 统一用户中心
### 登录
* URL: /v1/auth/login
* URL: /v1/ucenter/login
* 格式: JSON
* HTTP请求方式: POST
* 请求示例
... ... @@ -11,8 +12,46 @@
"phone": "18860180001",
"code": "784657",
"grantType": "signInPassword",
"password": "123456",
"clientId": "signInPassword"
"password": "123456"
}
```
* 应答示例
```json
{
"code": 0,
"msg": "成功",
"data": {
"uid": 3507839547244544,
"module": [
{
"name": "opportunity"
},
{
"name": "question"
}
]
}
}
```
```
data.uid 统一用户中心uid
data.module 有权限的模块
```
## 认证
### 登录
* URL: /v1/auth/login
* 格式: JSON
* HTTP请求方式: POST
* 请求示例
```json
{
"uid":3507839547244544
}
```
... ... @@ -23,7 +62,7 @@
"code": 0,
"msg": "登录成功",
"data": {
"authCode": "5251839614a611eaab01000c29ad8d6d"
"authCode": "f7641e7d1cb811ea942d000c29ad8d6d"
}
}
```
... ...