作者 yangfu

add auth accessToken/refreshToken/changePwd

... ... @@ -22,8 +22,6 @@ metadata:
required: true
- ref: adminType
required: true
- ref: status
required: true
- ref: accessPartners
required: true
- ref: createAt
... ...
... ... @@ -5,6 +5,7 @@ go 1.16
require (
github.com/ajg/form v1.5.1 // indirect
github.com/beego/beego/v2 v2.0.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/fasthttp-contrib/websocket v0.0.0-20160511215533-1f3b11f56072 // indirect
github.com/fatih/structs v1.1.0 // indirect
github.com/gavv/httpexpect v2.0.0+incompatible
... ...
... ... @@ -44,6 +44,7 @@ github.com/cupcake/rdb v0.0.0-20161107195141-43ba34106c76/go.mod h1:vYwsqCOLxGii
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/eapache/go-resiliency v1.1.0/go.mod h1:kFI+JgMyC7bLPUVY133qvEBtVayf5mFgVsvEsIPBvNs=
github.com/eapache/go-xerial-snappy v0.0.0-20180814174437-776d5712da21/go.mod h1:+020luEh2TKB4/GOp8oxxtq0Daoen/Cii55CzbTV6DU=
... ...
package command
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type AccessTokenCommand struct {
// Attribute描述
AuthCode string `json:"authCode,omitempty"`
}
func (accessTokenCommand *AccessTokenCommand) Valid(validation *validation.Validation) {
}
func (accessTokenCommand *AccessTokenCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(accessTokenCommand)
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 ChangePasswordCommand struct {
// 旧密码
OldPwd string `json:"oldPwd,omitempty"`
// 新密码
NewPwd string `json:"newPwd,omitempty"`
// 确认密码
ConfirmPwd string `json:"confirmPwd,omitempty"`
// 手机号
Phone string `json:"phone,omitempty"`
}
func (changePasswordCommand *ChangePasswordCommand) Valid(validation *validation.Validation) {
}
func (changePasswordCommand *ChangePasswordCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(changePasswordCommand)
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 LoginByCompanyCommand struct {
// 1.高管 2.合伙人 4:游客
UserType int `json:"userType" valid:"Required"`
// 凭证
Credentials string `json:"credentials" valid:"Required"`
// 用户id
UserId int64 `json:"userId" valid:"Required"`
}
func (loginByCompanyCommand *LoginByCompanyCommand) Valid(validation *validation.Validation) {
}
func (loginByCompanyCommand *LoginByCompanyCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(loginByCompanyCommand)
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
RefreshToken string `json:"refreshToken,omitempty"`
}
func (refreshTokenCommand *RefreshTokenCommand) Valid(validation *validation.Validation) {
}
func (refreshTokenCommand *RefreshTokenCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(refreshTokenCommand)
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 RevokeCommand struct {
}
func (revokeCommand *RevokeCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (revokeCommand *RevokeCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(revokeCommand)
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 SendSmsCodeCommand struct {
// 手机号
Phone string `json:"phone,omitempty"`
}
func (sendSmsCodeCommand *SendSmsCodeCommand) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (sendSmsCodeCommand *SendSmsCodeCommand) ValidateCommand() error {
valid := validation.Validation{}
b, err := valid.Valid(sendSmsCodeCommand)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type LoginQuery struct {
// 手机号
Phone string `json:"phone,omitempty"`
// signInPassword(密码登录) 或 signInCaptcha(验证码登录)或signInCredentials(凭证登录)
GrantType string `json:"grantType,omitempty"`
// 密码(grantType = signInPassword)
Password string `json:"password,omitempty"`
// 验证码(grantType = signInCaptcha)
Captcha string `json:"captcha,omitempty"`
// 凭证(grantType = signInCredentials)
Credentials string `json:"credentials,omitempty"`
}
func (loginQuery *LoginQuery) Valid(validation *validation.Validation) {
}
func (loginQuery *LoginQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(loginQuery)
if err != nil {
return err
}
if !b {
for _, validErr := range valid.Errors {
return fmt.Errorf("%s %s", validErr.Key, validErr.Message)
}
}
return nil
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/application/auth/command"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/application/auth/query"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/application/factory"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
"math/rand"
"strconv"
"strings"
)
// 认证服务
type AuthService struct {
}
// 用户按公司登录
func (authService *AuthService) AccessToken(accessTokenCommand *command.AccessTokenCommand) (interface{}, error) {
if err := accessTokenCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.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()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
var claim = &domain.UserTokenClaim{}
var result bool
if result, err = domain.ValidToken(accessTokenCommand.AuthCode, claim); err != nil || !result {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
userId := claim.UserId
companyId := claim.CompanyId
rspMapData := map[string]interface{}{
"accessToken": domain.SignToken(int64(userId), companyId),
"refreshToken": domain.SignToken(int64(userId), companyId),
}
return rspMapData, nil
}
// 修改手机号密码
func (authService *AuthService) ChangePassword(changePasswordCommand *command.ChangePasswordCommand) (interface{}, error) {
if err := changePasswordCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.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 (
userAuth *domain.UserAuth
)
UserAuthRepository, _ := factory.CreateUserAuthRepository(map[string]interface{}{"transactionContext": transactionContext})
userAuth, err = UserAuthRepository.FindOne(map[string]interface{}{"phone": changePasswordCommand.Phone})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if !strings.EqualFold(userAuth.PhoneAuth.Password, changePasswordCommand.OldPwd) {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "密码有误!")
}
if err = userAuth.Update(map[string]interface{}{"password": changePasswordCommand.NewPwd}); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if _, err = UserAuthRepository.Save(userAuth); err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 用户登录 返回有权限的公司列表
func (authService *AuthService) Login(loginQuery *query.LoginQuery) (interface{}, error) {
if err := loginQuery.ValidateQuery(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.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 (
userAuth *domain.UserAuth
users []*domain.User
rspMapData = make(map[string]interface{})
userCompanies []interface{}
)
UserAuthRepository, _ := factory.CreateUserAuthRepository(map[string]interface{}{"transactionContext": transactionContext})
UserRepository, _ := factory.CreateUserRepository(map[string]interface{}{"transactionContext": transactionContext})
switch loginQuery.GrantType {
case "signInPassword":
if len(loginQuery.Password) == 0 {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "密码不能为空!")
}
userAuth, err = UserAuthRepository.FindOne(map[string]interface{}{"phone": loginQuery.Phone})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
if !strings.EqualFold(userAuth.PhoneAuth.Password, loginQuery.Password) {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "密码有误!")
}
case "signInCaptcha":
case "signInCredentials":
default:
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "undefined grantType:"+loginQuery.GrantType)
}
_, users, err = UserRepository.Find(map[string]interface{}{"inUserIds": userAuth.Users, "status": domain.StatusEnable})
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
credentials := "cred:" + strconv.Itoa(rand.Int())
rspMapData["credentials"] = credentials
CompanyRepository, _ := factory.CreateCompanyRepository(map[string]interface{}{"transactionContext": transactionContext})
for i := range users {
company, _ := CompanyRepository.FindOne(map[string]interface{}{"companyId": users[i].CompanyId, "status": domain.StatusEnable})
if company == nil {
continue
}
item := map[string]interface{}{
"user": users[i],
"company": company,
}
userCompanies = append(userCompanies, item)
}
return map[string]interface{}{"userCompanies": userCompanies, "credentials": credentials}, nil
}
// 用户按公司登录
func (authService *AuthService) LoginByCompany(loginByCompanyCommand *command.LoginByCompanyCommand) (interface{}, error) {
if err := loginByCompanyCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.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()
}()
//todo:valid/refresh credentials
if len(loginByCompanyCommand.Credentials) == 0 {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "credentials expire")
}
var user *domain.User
UserRepository, _ := factory.CreateUserRepository(map[string]interface{}{"transactionContext": transactionContext})
user, err = UserRepository.FindOne(map[string]interface{}{"userId": loginByCompanyCommand.UserId, "userType": loginByCompanyCommand.UserType})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
CompanyRepository, _ := factory.CreateCompanyRepository(map[string]interface{}{"transactionContext": transactionContext})
company, err := CompanyRepository.FindOne(map[string]interface{}{"companyId": user.CompanyId, "status": domain.StatusEnable})
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())
}
authCode := domain.SignToken(user.UserId, company.CompanyId)
return map[string]interface{}{"user": user, "company": company, "authCode": authCode}, nil
}
// 更新授权令牌accessToken
func (authService *AuthService) RefreshToken(refreshTokenCommand *command.RefreshTokenCommand) (interface{}, error) {
if err := refreshTokenCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.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()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
var claim = &domain.UserTokenClaim{}
var result bool
if result, err = domain.ValidToken(refreshTokenCommand.RefreshToken, claim); err != nil || !result {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
}
userId := claim.UserId
companyId := claim.CompanyId
rspMapData := map[string]interface{}{
"accessToken": domain.SignToken(int64(userId), companyId),
"refreshToken": domain.SignToken(int64(userId), companyId),
}
return rspMapData, nil
}
// 注销登录
func (authService *AuthService) Revoke(revokeCommand *command.RevokeCommand) (interface{}, error) {
if err := revokeCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.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()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 发送验证码
func (authService *AuthService) SendSmsCode(sendSmsCodeCommand *command.SendSmsCodeCommand) (interface{}, error) {
if err := sendSmsCodeCommand.ValidateCommand(); err != nil {
return nil, application.ThrowError(application.ARG_ERROR, err.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()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
func NewAuthService(options map[string]interface{}) *AuthService {
newAuthService := &AuthService{}
return newAuthService
}
... ...
... ... @@ -45,3 +45,19 @@ func CreateGoodsRepository(options map[string]interface{}) (domain.GoodsReposito
}
return repository.NewGoodsRepository(transactionContext)
}
func CreateUserRepository(options map[string]interface{}) (domain.UserRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewUserRepository(transactionContext)
}
func CreateCompanyRepository(options map[string]interface{}) (domain.CompanyRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewCompanyRepository(transactionContext)
}
... ...
package domain
import (
"github.com/dgrijalva/jwt-go"
eggJwt "github.com/linmadan/egglib-go/utils/jwt"
"time"
)
const (
secret = "$^%$Rdefault&*^(*&"
)
const (
AccessTokenExpire = 3600
)
type UserTokenClaim struct {
jwt.StandardClaims
UserId int64 `json:"userId"`
CompanyId int64 `json:"companyId"`
}
func NewUserTokenClaim(userId, companyId int64, expire int64) UserTokenClaim {
return UserTokenClaim{
UserId: userId,
CompanyId: companyId,
StandardClaims: jwt.StandardClaims{ExpiresAt: expire},
}
}
func SignToken(userId int64, companyId int64) string {
claim := NewUserTokenClaim(int64(userId), companyId, time.Now().Add(time.Second*AccessTokenExpire).Unix())
token, _ := eggJwt.Sign(claim, secret, "")
return token
}
func ValidToken(token string, claims *UserTokenClaim) (bool, error) {
result, c, err := eggJwt.Valid(token, claims, secret)
claims = c.Claims.(*UserTokenClaim)
return result, err
}
... ...
package domain
import "time"
// 公司信息
type Company struct {
// 公司Id
CompanyId int64 `json:"companyId"`
// 公司信息
CompanyInfo *CompanyInfo `json:"companyInfo"`
// 创建时间
CreateAt time.Time `json:"createAt"`
// 更新时间
UpdateAt time.Time `json:"updateAt"`
// 删除时间
DeleteAt time.Time `json:"deleteAt"`
}
type CompanyRepository interface {
Save(company *Company) (*Company, error)
Remove(company *Company) (*Company, error)
FindOne(queryOptions map[string]interface{}) (*Company, error)
Find(queryOptions map[string]interface{}) (int64, []*Company, error)
}
func (company *Company) Identify() interface{} {
if company.CompanyId == 0 {
return nil
}
return company.CompanyId
}
func (company *Company) Update(data map[string]interface{}) error {
if companyId, ok := data["companyId"]; ok {
company.CompanyId = companyId.(int64)
}
if companyId, ok := data["companyId"]; ok {
company.CompanyInfo.CompanyId = companyId.(int64)
}
if name, ok := data["name"]; ok {
company.CompanyInfo.Name = name.(string)
}
if abbreviation, ok := data["abbreviation"]; ok {
company.CompanyInfo.Abbreviation = abbreviation.(string)
}
if logo, ok := data["logo"]; ok {
company.CompanyInfo.Logo = logo.(string)
}
if phone, ok := data["phone"]; ok {
company.CompanyInfo.Phone = phone.(string)
}
if status, ok := data["status"]; ok {
company.CompanyInfo.Status = status.(int64)
}
if remarks, ok := data["remarks"]; ok {
company.CompanyInfo.Remarks = remarks.(string)
}
if enable, ok := data["enable"]; ok {
company.CompanyInfo.Enable = enable.(int64)
}
return nil
}
... ...
package domain
// 公司信息
type CompanyInfo struct {
// 公司Id
CompanyId int64 `json:"companyId"`
// 公司名称
Name string `json:"name"`
// 公司简称
Abbreviation string `json:"abbreviation"`
// 公司logo
Logo string `json:"logo"`
// 公司联系电话
Phone string `json:"phone"`
// 状态 1正常 2禁用
Status int64 `json:"status"`
// 备注
Remarks string `json:"remarks"`
// 是否有效【1:有效】【2:无效】
Enable int64 `json:"enable"`
// 公司主管理员
Admin *UserInfo `json:"admin"`
}
... ...
package domain
import "time"
const (
StatusEnable int64 = 1
StatusDisable int64 = 2
)
const (
SuperAdministrator = 1
EnterpriseAdministrator = 10
NormalUser = 100
)
// UserType
const (
Manager = 1
Partner = 2
Guest = 3
)
// 用户实体
type User struct {
// 用户id
UserId int64 `json:"userId"`
// 1.高管 2.合伙人 4:游客
UserType int `json:"userType"`
// 用户权限
Permissions []int `json:"permissions"`
// 公司Id
CompanyId int64 `json:"companyId"`
// 用户信息
UserInfo *UserInfo `json:"userInfo"`
// 合伙人信息
PartnerInfo *PartnerInfo `json:"partnerInfo"`
// 状态 1正常 2禁用
Status int64 `json:"status"`
// 管理员类型 1.超级管理员 10:企业管理员 100:普通用户
AdminType int `json:"adminType"`
// 合伙人列表 用户类型为高管时有效
AccessPartners []int64 `json:"accessPartners"`
// 创建时间
CreateAt time.Time `json:"createAt"`
// 更新时间
UpdateAt time.Time `json:"updateAt"`
// 删除时间
DeleteAt time.Time `json:"deleteAt"`
}
type UserRepository interface {
Save(user *User) (*User, error)
Remove(user *User) (*User, error)
FindOne(queryOptions map[string]interface{}) (*User, error)
Find(queryOptions map[string]interface{}) (int64, []*User, error)
}
func (user *User) Identify() interface{} {
if user.UserId == 0 {
return nil
}
return user.UserId
}
func (user *User) Update(data map[string]interface{}) error {
if userId, ok := data["userId"]; ok {
user.UserId = userId.(int64)
}
if userType, ok := data["userType"]; ok {
user.UserType = userType.(int)
}
if permissions, ok := data["permissions"]; ok {
user.Permissions = permissions.([]int)
}
if companyId, ok := data["companyId"]; ok {
user.CompanyId = companyId.(int64)
}
if isPrincipal, ok := data["isPrincipal"]; ok {
user.UserInfo.IsPrincipal = isPrincipal.(bool)
}
if uid, ok := data["uid"]; ok {
user.UserInfo.Uid = uid.(int64)
}
if userAccount, ok := data["userAccount"]; ok {
user.UserInfo.UserAccount = userAccount.(string)
}
if userAvatarUrl, ok := data["userAvatarUrl"]; ok {
user.UserInfo.UserAvatarUrl = userAvatarUrl.(string)
}
if userName, ok := data["userName"]; ok {
user.UserInfo.UserName = userName.(string)
}
if email, ok := data["email"]; ok {
user.UserInfo.Email = email.(string)
}
if gender, ok := data["gender"]; ok {
user.UserInfo.Gender = gender.(int)
}
if entryTime, ok := data["entryTime"]; ok {
user.UserInfo.EntryTime = entryTime.(time.Time)
}
if extension, ok := data["extension"]; ok {
user.UserInfo.Extension = extension.(string)
}
if workplace, ok := data["workplace"]; ok {
user.UserInfo.Workplace = workplace.(string)
}
if privateNumber, ok := data["privateNumber"]; ok {
user.UserInfo.PrivateNumber = privateNumber.(string)
}
if jobNumber, ok := data["jobNumber"]; ok {
user.UserInfo.JobNumber = jobNumber.(string)
}
if partnerAccount, ok := data["partnerAccount"]; ok {
user.PartnerInfo.PartnerAccount = partnerAccount.(string)
}
if partnerName, ok := data["partnerName"]; ok {
user.PartnerInfo.PartnerName = partnerName.(string)
}
if regionName, ok := data["regionName"]; ok {
user.PartnerInfo.RegionInfo.RegionName = regionName.(string)
}
if status, ok := data["status"]; ok {
user.PartnerInfo.Status = status.(int64)
}
return nil
}
... ...
package domain
import "time"
// 用户信息值对象
type UserInfo struct {
// 是否是公司负责人
IsPrincipal bool `json:"isPrincipal"`
// 统一用户id
Uid int64 `json:"uid"`
// 用户账号
UserAccount string `json:"userAccount"`
// 用户头像URL
UserAvatarUrl string `json:"userAvatarUrl"`
// 用户名称
UserName string `json:"userName"`
// 邮件地址
Email string `json:"email"`
// 性别
Gender int `json:"gender"`
// 入职时间
EntryTime time.Time `json:"entryTime"`
// 分机
Extension string `json:"extension"`
// 工作地
Workplace string `json:"workplace"`
// 私人电话
PrivateNumber string `json:"privateNumber"`
// 工号
JobNumber string `json:"jobNumber"`
}
... ...
... ... @@ -29,6 +29,8 @@ func init() {
&models.UserAuth{},
&models.Goods{},
&models.Order{},
&models.User{},
&models.Company{},
} {
err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: false,
... ...
package models
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
"time"
)
type Company struct {
tableName string `pg:"companys,alias:company"`
// 公司Id
CompanyId int64 `pg:",pk"`
// 公司信息
CompanyInfo *domain.CompanyInfo
// 创建时间
CreateAt time.Time
// 更新时间
UpdateAt time.Time
// 删除时间
DeleteAt time.Time
}
... ...
package models
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
"time"
)
type User struct {
tableName string `pg:"users,alias:users"`
// 用户id
UserId int64 `pg:",pk"`
// 1.高管 2.合伙人 4:游客
UserType int
// 用户权限
Permissions []int `pg:",array"`
// 公司Id
CompanyId int64
// 用户信息
UserInfo *domain.UserInfo
// 合伙人信息
PartnerInfo *domain.PartnerInfo
// 状态 1正常 2禁用
Status int64
// 管理员类型 1.超级管理员 10:企业管理员 100:普通用户
AdminType int
// 合伙人列表 用户类型为高管时有效
AccessPartners []int64 `pg:",array"`
// 创建时间
CreateAt time.Time
// 更新时间
UpdateAt time.Time
// 删除时间
DeleteAt time.Time
}
... ...
... ... @@ -6,9 +6,9 @@ import (
)
type UserAuth struct {
tableName string `pg:"user_auth"`
tableName string `pg:"user_auth,alias:user_auth"`
// 用户认证编号
UserAuthId int64
UserAuthId int64 `pg:",pk"`
// 用户id列表
Users []int64 `pg:",array"`
// 手机认证
... ...
package transform
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/models"
)
func TransformToCompanyDomainModelFromPgModels(companyModel *models.Company) (*domain.Company, error) {
return &domain.Company{
CompanyId: companyModel.CompanyId,
CompanyInfo: companyModel.CompanyInfo,
CreateAt: companyModel.CreateAt,
UpdateAt: companyModel.UpdateAt,
DeleteAt: companyModel.DeleteAt,
}, nil
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/models"
)
func TransformToUserDomainModelFromPgModels(userModel *models.User) (*domain.User, error) {
return &domain.User{
UserId: userModel.UserId,
UserType: userModel.UserType,
Permissions: userModel.Permissions,
CompanyId: userModel.CompanyId,
UserInfo: userModel.UserInfo,
PartnerInfo: userModel.PartnerInfo,
Status: userModel.Status,
AdminType: userModel.AdminType,
AccessPartners: userModel.AccessPartners,
CreateAt: userModel.CreateAt,
UpdateAt: userModel.UpdateAt,
DeleteAt: userModel.DeleteAt,
}, nil
}
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/transform"
)
type CompanyRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *CompanyRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *CompanyRepository) Save(company *domain.Company) (*domain.Company, error) {
sqlBuildFields := []string{
"company_id",
"company_info",
"create_at",
"update_at",
"delete_at",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "company_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if company.Identify() == nil {
companyId, err := repository.nextIdentify()
if err != nil {
return company, err
} else {
company.CompanyId = companyId
}
if _, err := tx.QueryOne(
pg.Scan(
&company.CompanyId,
&company.CompanyInfo,
&company.CreateAt,
&company.UpdateAt,
&company.DeleteAt,
),
fmt.Sprintf("INSERT INTO companys (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
company.CompanyId,
company.CompanyInfo,
company.CreateAt,
company.UpdateAt,
company.DeleteAt,
); err != nil {
return company, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&company.CompanyId,
&company.CompanyInfo,
&company.CreateAt,
&company.UpdateAt,
&company.DeleteAt,
),
fmt.Sprintf("UPDATE companys SET %s WHERE company_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
company.CompanyId,
company.CompanyInfo,
company.CreateAt,
company.UpdateAt,
company.DeleteAt,
company.Identify(),
); err != nil {
return company, err
}
}
return company, nil
}
func (repository *CompanyRepository) Remove(company *domain.Company) (*domain.Company, error) {
tx := repository.transactionContext.PgTx
companyModel := new(models.Company)
companyModel.CompanyId = company.Identify().(int64)
if _, err := tx.Model(companyModel).WherePK().Delete(); err != nil {
return company, err
}
return company, nil
}
func (repository *CompanyRepository) FindOne(queryOptions map[string]interface{}) (*domain.Company, error) {
tx := repository.transactionContext.PgTx
companyModel := new(models.Company)
query := sqlbuilder.BuildQuery(tx.Model(companyModel), queryOptions)
query.SetWhereByQueryOption("company.company_id = ?", "companyId")
query.SetWhereByQueryOption(`company.company_info @>'{"status":?}'`, "status")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if companyModel.CompanyId == 0 {
return nil, nil
} else {
return transform.TransformToCompanyDomainModelFromPgModels(companyModel)
}
}
func (repository *CompanyRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.Company, error) {
tx := repository.transactionContext.PgTx
var companyModels []*models.Company
companys := make([]*domain.Company, 0)
query := sqlbuilder.BuildQuery(tx.Model(&companyModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("company_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, companys, err
} else {
for _, companyModel := range companyModels {
if company, err := transform.TransformToCompanyDomainModelFromPgModels(companyModel); err != nil {
return 0, companys, err
} else {
companys = append(companys, company)
}
}
return int64(count), companys, nil
}
}
func NewCompanyRepository(transactionContext *pgTransaction.TransactionContext) (*CompanyRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &CompanyRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
... ... @@ -53,7 +53,7 @@ func (repository *UserAuthRepository) Save(userAuth *domain.UserAuth) (*domain.U
&userAuth.CreateAt,
&userAuth.UpdateAt,
),
fmt.Sprintf("INSERT INTO user_auths (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
fmt.Sprintf("INSERT INTO user_auth (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
userAuth.UserAuthId,
pg.Array(userAuth.Users),
userAuth.PhoneAuth,
... ... @@ -71,7 +71,7 @@ func (repository *UserAuthRepository) Save(userAuth *domain.UserAuth) (*domain.U
&userAuth.CreateAt,
&userAuth.UpdateAt,
),
fmt.Sprintf("UPDATE user_auths SET %s WHERE user_auth_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
fmt.Sprintf("UPDATE user_auth SET %s WHERE user_auth_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
userAuth.UserAuthId,
pg.Array(userAuth.Users),
userAuth.PhoneAuth,
... ... @@ -98,6 +98,9 @@ func (repository *UserAuthRepository) FindOne(queryOptions map[string]interface{
userAuthModel := new(models.UserAuth)
query := sqlbuilder.BuildQuery(tx.Model(userAuthModel), queryOptions)
query.SetWhereByQueryOption("user_auth.user_auth_id = ?", "userAuthId")
if v, ok := queryOptions["phone"]; ok {
query.Where(fmt.Sprintf(`user_auth.phone_auth @>'{"phone":"%v"}'`, v))
}
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
... ...
package repository
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/linmadan/egglib-go/persistent/pg/sqlbuilder"
pgTransaction "github.com/linmadan/egglib-go/transaction/pg"
"github.com/linmadan/egglib-go/utils/snowflake"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg/transform"
)
type UserRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *UserRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *UserRepository) Save(user *domain.User) (*domain.User, error) {
sqlBuildFields := []string{
"user_id",
"user_type",
"permissions",
"company_id",
"user_info",
"partner_info",
"status",
"admin_type",
"access_partners",
"create_at",
"update_at",
"delete_at",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "user_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if user.Identify() == nil {
userId, err := repository.nextIdentify()
if err != nil {
return user, err
} else {
user.UserId = userId
}
if _, err := tx.QueryOne(
pg.Scan(
&user.UserId,
&user.UserType,
pg.Array(&user.Permissions),
&user.CompanyId,
&user.UserInfo,
&user.PartnerInfo,
&user.Status,
&user.AdminType,
pg.Array(&user.AccessPartners),
&user.CreateAt,
&user.UpdateAt,
&user.DeleteAt,
),
fmt.Sprintf("INSERT INTO users (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
user.UserId,
user.UserType,
pg.Array(user.Permissions),
user.CompanyId,
user.UserInfo,
user.PartnerInfo,
user.Status,
user.AdminType,
pg.Array(user.AccessPartners),
user.CreateAt,
user.UpdateAt,
user.DeleteAt,
); err != nil {
return user, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&user.UserId,
&user.UserType,
pg.Array(&user.Permissions),
&user.CompanyId,
&user.UserInfo,
&user.PartnerInfo,
&user.Status,
&user.AdminType,
pg.Array(&user.AccessPartners),
&user.CreateAt,
&user.UpdateAt,
&user.DeleteAt,
),
fmt.Sprintf("UPDATE users SET %s WHERE user_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
user.UserId,
user.UserType,
pg.Array(user.Permissions),
user.CompanyId,
user.UserInfo,
user.PartnerInfo,
user.Status,
user.AdminType,
pg.Array(user.AccessPartners),
user.CreateAt,
user.UpdateAt,
user.DeleteAt,
user.Identify(),
); err != nil {
return user, err
}
}
return user, nil
}
func (repository *UserRepository) Remove(user *domain.User) (*domain.User, error) {
tx := repository.transactionContext.PgTx
userModel := new(models.User)
userModel.UserId = user.Identify().(int64)
if _, err := tx.Model(userModel).WherePK().Delete(); err != nil {
return user, err
}
return user, nil
}
func (repository *UserRepository) FindOne(queryOptions map[string]interface{}) (*domain.User, error) {
tx := repository.transactionContext.PgTx
userModel := new(models.User)
query := sqlbuilder.BuildQuery(tx.Model(userModel), queryOptions)
query.SetWhereByQueryOption("users.user_id = ?", "userId")
query.SetWhereByQueryOption("users.status = ?", "status")
query.SetWhereByQueryOption("users.user_type = ?", "userType")
if v, ok := queryOptions["inUserIds"]; ok {
query.Where("users.user_id in (?)", pg.Array(v))
}
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if userModel.UserId == 0 {
return nil, nil
} else {
return transform.TransformToUserDomainModelFromPgModels(userModel)
}
}
func (repository *UserRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.User, error) {
tx := repository.transactionContext.PgTx
var userModels []*models.User
users := make([]*domain.User, 0)
query := sqlbuilder.BuildQuery(tx.Model(&userModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("user_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, users, err
} else {
for _, userModel := range userModels {
if user, err := transform.TransformToUserDomainModelFromPgModels(userModel); err != nil {
return 0, users, err
} else {
users = append(users, user)
}
}
return int64(count), users, nil
}
}
func NewUserRepository(transactionContext *pgTransaction.TransactionContext) (*UserRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &UserRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/application/auth/command"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/application/auth/query"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/application/auth/service"
)
type AuthController struct {
beego.BaseController
}
func (controller *AuthController) Login() {
authService := service.NewAuthService(nil)
loginQuery := &query.LoginQuery{}
controller.Unmarshal(loginQuery)
data, err := authService.Login(loginQuery)
controller.Response(data, err)
}
func (controller *AuthController) LoginByCompany() {
authService := service.NewAuthService(nil)
loginByCompanyCommand := &command.LoginByCompanyCommand{}
controller.Unmarshal(loginByCompanyCommand)
data, err := authService.LoginByCompany(loginByCompanyCommand)
controller.Response(data, err)
}
func (controller *AuthController) AccessToken() {
authService := service.NewAuthService(nil)
accessTokenCommand := &command.AccessTokenCommand{}
controller.Unmarshal(accessTokenCommand)
data, err := authService.AccessToken(accessTokenCommand)
controller.Response(data, err)
}
func (controller *AuthController) RefreshToken() {
authService := service.NewAuthService(nil)
refreshTokenCommand := &command.RefreshTokenCommand{}
controller.Unmarshal(refreshTokenCommand)
data, err := authService.RefreshToken(refreshTokenCommand)
controller.Response(data, err)
}
func (controller *AuthController) SendSmsCode() {
authService := service.NewAuthService(nil)
sendSmsCodeCommand := &command.SendSmsCodeCommand{}
controller.Unmarshal(sendSmsCodeCommand)
data, err := authService.SendSmsCode(sendSmsCodeCommand)
controller.Response(data, err)
}
func (controller *AuthController) Revoke() {
authService := service.NewAuthService(nil)
revokeCommand := &command.RevokeCommand{}
controller.Unmarshal(revokeCommand)
data, err := authService.Revoke(revokeCommand)
controller.Response(data, err)
}
func (controller *AuthController) ChangePassword() {
authService := service.NewAuthService(nil)
changePasswordCommand := &command.ChangePasswordCommand{}
controller.Unmarshal(changePasswordCommand)
data, err := authService.ChangePassword(changePasswordCommand)
controller.Response(data, err)
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/port/beego/controllers"
)
func init() {
web.Router("/auths/login", &controllers.AuthController{}, "Post:Login")
web.Router("/auths/loginByCompany", &controllers.AuthController{}, "Post:LoginByCompany")
web.Router("/auths/accessToken", &controllers.AuthController{}, "Post:AccessToken")
web.Router("/auths/refreshToken", &controllers.AuthController{}, "Post:RefreshToken")
web.Router("/auths/sendSmsCode", &controllers.AuthController{}, "Post:SendSmsCode")
web.Router("/auths/revoke", &controllers.AuthController{}, "Post:Revoke")
web.Router("/auths/changePhonePassword", &controllers.AuthController{}, "Post:ChangePassword")
}
... ...
package auth
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
)
var _ = Describe("用户按公司登录", func() {
//var Id int64
//return
BeforeEach(func() {
//_, err := pG.DB.QueryOne(
// pg.Scan(&Id),
// "INSERT INTO s () VALUES () RETURNING _id",
//)
//Expect(err).NotTo(HaveOccurred())
})
Describe("用户按公司登录", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"authCode": domain.SignToken(1, 1000),
}
httpExpect.POST("/auths/accessToken").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
//_, err := pG.DB.Exec("DELETE FROM s WHERE true")
//Expect(err).NotTo(HaveOccurred())
})
})
... ...
package auth
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/beego/beego/v2/server/web"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
_ "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/port/beego"
)
func TestAuth(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Beego Port Auth Correlations Test Case Suite")
}
var handler http.Handler
var server *httptest.Server
var _ = BeforeSuite(func() {
handler = web.BeeApp.Handlers
server = httptest.NewServer(handler)
})
var _ = AfterSuite(func() {
server.Close()
})
... ...
package auth
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
)
var _ = Describe("修改手机号密码", func() {
var Id int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&Id),
`INSERT INTO user_auth (user_auth_id,users,phone_auth) VALUES (1,ARRAY [1],'{"phone":"18800000001","password":"password"}') RETURNING user_auth_id`,
)
Expect(err).NotTo(HaveOccurred())
})
Describe("修改手机号密码", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"oldPwd": "password",
"newPwd": "newPassword",
"confirmPwd": "newPassword",
"phone": "18800000001",
}
httpExpect.POST("/auths/changePhonePassword").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok")
//ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM user_auth WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package auth
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
)
var _ = Describe("用户按公司登录", func() {
var Id int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&Id),
"INSERT INTO users (user_id,user_type,company_id) VALUES (1,1,1000) RETURNING user_id",
)
_, err = pG.DB.QueryOne(
pg.Scan(&Id),
`INSERT INTO companys (company_id,company_info) VALUES (1000,'{"company_id":1000,"name":"company","status":1}') RETURNING company_id`,
)
_, err = pG.DB.QueryOne(
pg.Scan(&Id),
`INSERT INTO user_auth (user_auth_id,users,phone_auth) VALUES (1,ARRAY [1],'{"phone":"18800000001","password":"password"}') RETURNING user_auth_id`,
)
Expect(err).NotTo(HaveOccurred())
})
Describe("用户按公司登录", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"userType": 1,
"credentials": "string",
"userId": 1,
}
httpExpect.POST("/auths/loginByCompany").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM users WHERE true")
_, err = pG.DB.Exec("DELETE FROM companys WHERE true")
_, err = pG.DB.Exec("DELETE FROM user_auth WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package auth
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
)
var _ = Describe("用户登录 返回有权限的公司列表", func() {
var Id int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&Id),
"INSERT INTO users (user_id,user_type,company_id) VALUES (1,1,1000) RETURNING user_id",
)
_, err = pG.DB.QueryOne(
pg.Scan(&Id),
`INSERT INTO companys (company_id,company_info) VALUES (1000,'{"company_id":1000,"name":"company"}') RETURNING company_id`,
)
_, err = pG.DB.QueryOne(
pg.Scan(&Id),
`INSERT INTO user_auth (user_auth_id,users,phone_auth) VALUES (1,ARRAY [1],'{"phone":"18800000001","password":"password"}') RETURNING user_auth_id`,
)
Expect(err).NotTo(HaveOccurred())
})
Describe("用户登录 返回有权限的公司列表", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"phone": "18800000001",
"grantType": "signInPassword",
"password": "password",
"captcha": "",
"credentials": "",
}
httpExpect.POST("/auths/login").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM users WHERE true")
_, err = pG.DB.Exec("DELETE FROM companys WHERE true")
_, err = pG.DB.Exec("DELETE FROM user_auth WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package auth
import (
"gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/domain"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
)
var _ = Describe("更新授权令牌accessToken", func() {
//return
//var Id int64
BeforeEach(func() {
//_, err := pG.DB.QueryOne(
// pg.Scan(&Id),
// "INSERT INTO s () VALUES () RETURNING _id",
//)
//Expect(err).NotTo(HaveOccurred())
})
Describe("更新授权令牌accessToken", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"refreshToken": domain.SignToken(1, 1000),
}
httpExpect.POST("/auths/refreshToken").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
//_, err := pG.DB.Exec("DELETE FROM s WHERE true")
//Expect(err).NotTo(HaveOccurred())
})
})
... ...
package auth
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
)
var _ = Describe("注销登录", func() {
return
var Id int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&Id),
"INSERT INTO s () VALUES () RETURNING _id",
)
Expect(err).NotTo(HaveOccurred())
})
Describe("注销登录", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{}
httpExpect.POST("/auths/revoke").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM s WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...
package auth
import (
"github.com/go-pg/pg/v10"
"net/http"
"github.com/gavv/httpexpect"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
pG "gitlab.fjmaimaimai.com/mmm-go-pp/partner01/pkg/infrastructure/pg"
)
var _ = Describe("发送验证码", func() {
return
var Id int64
BeforeEach(func() {
_, err := pG.DB.QueryOne(
pg.Scan(&Id),
"INSERT INTO s () VALUES () RETURNING _id",
)
Expect(err).NotTo(HaveOccurred())
})
Describe("发送验证码", func() {
Context("", func() {
It("", func() {
httpExpect := httpexpect.New(GinkgoT(), server.URL)
body := map[string]interface{}{
"phone": "string",
}
httpExpect.POST("/auths/sendSmsCode").
WithJSON(body).
Expect().
Status(http.StatusOK).
JSON().
Object().
ContainsKey("code").ValueEqual("code", 0).
ContainsKey("msg").ValueEqual("msg", "ok").
ContainsKey("data").Value("data").Object()
})
})
})
AfterEach(func() {
_, err := pG.DB.Exec("DELETE FROM s WHERE true")
Expect(err).NotTo(HaveOccurred())
})
})
... ...