作者 tangxuhui

新增 ,手机端登录、刷新获取tokn

{"F:\\go\\src\\allied-creation\\allied-creation-gateway\\pkg\\port\\beego\\routers":1627631911600010400}
\ No newline at end of file
{"D:\\workspaceGo\\src\\allied-creation-gateway\\pkg\\port\\beego\\routers":1627703189719007400}
\ No newline at end of file
... ...
... ... @@ -2,9 +2,14 @@ package main
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/cache"
_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego"
)
func init() {
cache.InitRedist()
}
func main() {
web.Run()
}
... ...
package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type AccessTokenCommand struct {
AuthCode string `json:"authCode"`
AuthCode string `json:"authCode" valid:"Required"`
}
func (orgAddCommand *AccessTokenCommand) Valid(validation *validation.Validation) {
}
func (orgAddCommand *AccessTokenCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(orgAddCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type RefreshTokenCommand struct {
RefreshToken string `json:"refreshToken" valid:"Required"`
}
func (orgAddCommand *RefreshTokenCommand) Valid(validation *validation.Validation) {
}
func (orgAddCommand *RefreshTokenCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(orgAddCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
... ... @@ -8,6 +8,7 @@ import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/mobile/auth/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/cache"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/service_gateway/allied_creation_user"
)
... ... @@ -64,6 +65,9 @@ func (srv AuthService) SignInCaptcha(phone string, captcha string) (interface{},
//GetAuthAccessToken 获取令牌Token
func (srv AuthService) GetAuthAccessToken(accessTokenCommand *command.AccessTokenCommand) (interface{}, error) {
if err := accessTokenCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
ltoken := domain.LoginToken{}
err := ltoken.ParseToken(accessTokenCommand.AuthCode)
if err != nil {
... ... @@ -123,6 +127,32 @@ func (srv AuthService) GetAuthAccessToken(accessTokenCommand *command.AccessToke
UpdatedTime: time.Now(),
}
}
//判定当前凭证的companyId,OrganizationId 是否在用户列表中
var currentOrgIsOK bool
loopUser1:
for _, v := range userSeachResult.Users {
if v.Company.CompanyId == int(currentAccess.CompanyId) {
for _, vv := range v.UserOrg {
if vv.OrgID == int(currentAccess.OrganizationId) {
currentOrgIsOK = true
break loopUser1
}
}
}
}
//记录上一次的登录公司组织信息不可用 ,重登录置记录
if !currentOrgIsOK {
loopUser2:
for _, v := range userSeachResult.Users {
currentAccess.CompanyId = int64(v.Company.CompanyId)
for _, vv := range v.UserOrg {
currentAccess.OrganizationId = int64(vv.OrgID)
currentOrgIsOK = true
break loopUser2
}
}
}
//TODO
loginToken := domain.LoginToken{
UserId: currentAccess.UserId,
Account: currentAccess.Account,
... ... @@ -143,12 +173,133 @@ func (srv AuthService) GetAuthAccessToken(accessTokenCommand *command.AccessToke
}
currentAccess.RefreshToken = refreshTokenStr
currentAccess.AccessExpired = loginToken.ExpiresAt
//先存数据库
_, err = loginAccessRepository.Save(currentAccess)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
tokenCache := cache.LoginTokenCache{}
tokenCache.RemoveAccessToken(currentAccess.Account, domain.LoginPlatformApp)
tokenCache.RemoveRefreshToken(currentAccess.Account, domain.LoginPlatformApp)
tokenCache.SaveAccessToken(currentAccess)
tokenCache.SaveRefreshToken(currentAccess)
nowTime := time.Now().Unix()
return map[string]interface{}{
"refreshToken": accessTokenStr,
"accessToken": refreshTokenStr,
"expiresIn": currentAccess.AccessExpired - nowTime,
}, nil
}
func (srv AuthService) RefreshAuthAccessToken(refreshTokenCommand *command.RefreshTokenCommand) (interface{}, error) {
if err := refreshTokenCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
ltoken := domain.LoginToken{}
err := ltoken.ParseToken(refreshTokenCommand.RefreshToken)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "refreshToken 不可用,"+err.Error())
}
phone := ltoken.Account
creationUserGateway := allied_creation_user.NewHttplibAlliedCreationUser(0, 0, 0)
userSeachResult, err := creationUserGateway.UserSearch(allied_creation_user.ReqUserSearch{
Phone: phone,
})
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "用户信息获取失败,"+err.Error())
}
//判定当前凭证的companyId,OrganizationId 是否在用户列表中
var currentOrgIsOK bool
loopUser1:
for _, v := range userSeachResult.Users {
if v.Company.CompanyId == int(ltoken.CompanyId) {
for _, vv := range v.UserOrg {
if vv.OrgID == int(ltoken.OrgId) {
currentOrgIsOK = true
break loopUser1
}
}
}
}
if !currentOrgIsOK {
return nil, application.ThrowError(application.TRANSACTION_ERROR, "登录的公司组织不可用")
}
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.StartTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
defer func() {
transactionContext.RollbackTransaction()
}()
var loginAccessRepository domain.LoginAccessRepository
if loginAccessRepository, err = factory.CreateLoginAccessRepository(map[string]interface{}{
"transactionContext": transactionContext,
}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
_, lAccess, err := loginAccessRepository.Find(map[string]interface{}{
"account": phone,
"platform": domain.LoginPlatformApp,
})
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
var currentAccess *domain.LoginAccess
if len(lAccess) > 0 {
currentAccess = lAccess[0]
currentAccess.UpdatedTime = time.Now()
} else {
currentAccess = &domain.LoginAccess{
UserBaseId: ltoken.UserBaseId,
UserId: ltoken.UserId,
Account: ltoken.Account,
Platform: domain.LoginPlatformApp,
CompanyId: ltoken.CompanyId,
OrganizationId: ltoken.OrgId,
AccessToken: "",
RefreshToken: "",
AccessExpired: 0,
RefreshExpired: 0,
CreatedTime: time.Now(),
UpdatedTime: time.Now(),
}
}
accessTokenStr, err := ltoken.GenerateAccessToken()
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
currentAccess.AccessToken = accessTokenStr
currentAccess.AccessExpired = ltoken.ExpiresAt
refreshTokenStr, err := ltoken.GenerateRefreshToken()
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
currentAccess.RefreshToken = refreshTokenStr
currentAccess.RefreshExpired = ltoken.ExpiresAt
//先存数据库
_, err = loginAccessRepository.Save(currentAccess)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
//先删缓存
//后加缓存
return nil, nil
tokenCache := cache.LoginTokenCache{}
tokenCache.RemoveAccessToken(currentAccess.Account, domain.LoginPlatformApp)
tokenCache.RemoveRefreshToken(currentAccess.Account, domain.LoginPlatformApp)
tokenCache.SaveAccessToken(currentAccess)
tokenCache.SaveRefreshToken(currentAccess)
nowTime := time.Now().Unix()
return map[string]interface{}{
"refreshToken": accessTokenStr,
"accessToken": refreshTokenStr,
"expiresIn": currentAccess.AccessExpired - nowTime,
}, nil
}
... ...
... ... @@ -16,6 +16,7 @@ const (
type LoginToken struct {
jwt.StandardClaims
UserId int64 `json:"userId"`
UserBaseId int64 `json:"userBaseId"`
// 账号
Account string `json:"account"`
// 对应平台
... ...
... ... @@ -12,7 +12,7 @@ const (
KEY_PREFIX string = "allied:creation:gateway:"
)
func Init() *redis.Client {
func InitRedist() *redis.Client {
options := redis.Options{
Network: "tcp",
Addr: fmt.Sprintf("%s:%s", "127.0.0.1", "6379"),
... ... @@ -36,5 +36,10 @@ func Init() *redis.Client {
}
// 新建一个client
clientRedis = redis.NewClient(&options)
pong, err := clientRedis.Ping().Result()
if err != nil {
e := fmt.Errorf("redis 连接失败,%s,%w", pong, err)
panic(e)
}
return clientRedis
}
... ...
package mobile_client
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/mobile/auth/command"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/mobile/auth/service"
)
type AuthController struct {
baseController
}
func (controller *AuthController) Login() {
authService := service.AuthService{}
loginCmd := &command.LoginCommand{}
err := controller.Unmarshal(loginCmd)
if err != nil {
controller.Response(nil, err)
return
}
data, err := authService.AuthLogin(loginCmd)
controller.Response(data, err)
}
func (controller *AuthController) GetAuthAccessToken() {
authService := service.AuthService{}
accessTokenCommand := &command.AccessTokenCommand{}
err := controller.Unmarshal(accessTokenCommand)
if err != nil {
controller.Response(nil, err)
return
}
data, err := authService.GetAuthAccessToken(accessTokenCommand)
controller.Response(data, err)
}
func (controller *AuthController) RefreshAuthAccessToken() {
authService := service.AuthService{}
refreshTokenCmd := &command.RefreshTokenCommand{}
err := controller.Unmarshal(refreshTokenCmd)
if err != nil {
controller.Response(nil, err)
return
}
data, err := authService.RefreshAuthAccessToken(refreshTokenCmd)
controller.Response(data, err)
}
... ...
package mobile_client
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
)
type baseController struct {
beego.BaseController
}
func (controller *baseController) returnPageListData(count int64, data interface{}, err error, pageNumber int) {
dataMap := map[string]interface{}{
"grid": map[string]interface{}{
"total": count,
//"pageNumber": pageNumber,
"list": data,
},
}
controller.Response(dataMap, err)
}
func (controller *baseController) GetUserId() int64 {
return 1
}
func (controller *baseController) GetCompanyId() int64 {
return 1
}
func (controller *baseController) GetUserBaseId() int64 {
return 1
}
func (controller *baseController) GetOrgId() int64 {
return 1
}
func (controller *baseController) GetOperator() domain.Operator {
return domain.Operator{
UserId: 9,
CompanyId: 23,
OrgId: 45,
UserBaseId: 1,
}
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/controllers/mobile_client"
)
func init() {
web.Router("/v1/app/auth/login", &mobile_client.AuthController{}, "Post:Login")
web.Router("/v1/app/auth/access-token", &mobile_client.AuthController{}, "Post:GetAuthAccessToken")
web.Router("/v1/app/auth/refresh-token", &mobile_client.AuthController{}, "Post:RefreshAuthAccessToken")
}
... ...