作者 庄敏学

PC端登录

正在显示 38 个修改的文件 包含 697 行增加90 行删除
... ... @@ -109,7 +109,11 @@ spec:
name: suplus-config
key: kafkaperformance.id
- name: KAFKA_BUSINESS_TOPIC
value: "mmm_business_test"
value: "mmm_business_test"
- name: UCENTER_SERVICE_HOST
value: "https://suplus-ucenter-test.fjmaimaimai.com"
- name: BUSINESS_ADMIN_SERVICE_HOST
value: "https://suplus-business-admin-test.fjmaimaimai.com"
volumes:
- name: accesslogs
emptyDir: {}
... ...
... ... @@ -6,6 +6,7 @@ require (
github.com/Shopify/sarama v1.25.0
github.com/beego/beego/v2 v2.0.5
github.com/bwmarrin/snowflake v0.3.0
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-pg/pg/v10 v10.10.7
github.com/linmadan/egglib-go v0.0.0-20210827085852-177fa745932d
)
... ...
... ... @@ -111,6 +111,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/dustin/go-humanize v0.0.0-20171111073723-bb3d318650d4/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
... ...
不能预览此文件类型
package command
type LoginCommand struct {
Code string `json:"code" valid:"Required"` //授权code
PlatformId int `json:"platformId" valid:"Required"` //登录平台ID,28-绩效管理后台 29-员工绩效
}
... ...
package service
import (
"github.com/linmadan/egglib-go/core/application"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/auth/command"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
)
type AuthService struct {
}
// Login PC端登录
func (service *AuthService) Login(loginCommand *command.LoginCommand) (interface{}, error) {
transactionContext, err := factory.CreateTransactionContext(nil)
if err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
if errStart := transactionContext.StartTransaction(); errStart != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, errStart.Error())
}
defer func() {
_ = transactionContext.RollbackTransaction()
}()
//统一用户中心登录
authCodeReply, err := factory.UCenterApi().AuthCode(loginCommand.Code)
if err != nil || !authCodeReply.IsOk() {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "统一用户中心认证失败")
}
//用户权限校验
userAuthReply, err := factory.BusinessAdminApi().GetUserAuth(authCodeReply.Data.MUid, loginCommand.PlatformId)
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "用户鉴权失败")
}
if !userAuthReply.IsOk() {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, userAuthReply.Message())
}
//获取公司数据
companyRepository := factory.CreateCompanyRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
company, err := companyRepository.FindOne(map[string]interface{}{
"id": authCodeReply.Data.CompanyId,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "获取公司数据失败")
}
userRepository := factory.CreateUserRepository(map[string]interface{}{
"transactionContext": transactionContext,
})
user, err := userRepository.FindOne(map[string]interface{}{
"id": authCodeReply.Data.MUid,
"companyId": company.Id,
})
if err != nil {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "获取公司数据失败")
}
if user.Status != domain.UserStatusEnable {
return nil, application.ThrowError(application.INTERNAL_SERVER_ERROR, "用户被禁用")
}
userAuth := &domain.UserAuth{
UserId: user.Id,
CompanyId: user.CompanyId,
Phone: user.Account,
PlatformId: loginCommand.PlatformId,
Name: user.Name,
AdminType: user.AdminType,
}
accessToken, err := userAuth.CreateAccessToken()
if 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 map[string]interface{}{
"access": map[string]interface{}{
"accessToken": accessToken,
"expiresIn": domain.JWTExpiresSecond,
},
}, nil
}
... ...
package command
//AddCompanyCommand 数据来源 企业平台 推送的消息
//新建公司
// AddCompanyCommand 数据来源 企业平台 推送的消息
// 新建公司
type SaveCompanyCommand struct {
//新添加的公司
Comapany struct {
Company struct {
Id int64 `json:"id" `
Logo string `json:"logo"` // 公司logo
Name string `json:"name"` // 公司名称
... ...
... ... @@ -79,14 +79,14 @@ func (c SyncDataCompanyService) addCompany(param *command.SaveCompanyCommand) er
}()
nowTime := time.Now()
newCompany := domain.Company{
Id: param.Comapany.Id,
Logo: param.Comapany.Logo,
Name: param.Comapany.Name,
Status: param.Comapany.Status,
UpdateAt: nowTime,
CreateAt: nowTime,
Id: param.Company.Id,
Logo: param.Company.Logo,
Name: param.Company.Name,
Status: param.Company.Status,
UpdatedAt: nowTime,
CreatedAt: nowTime,
ChargeUserIds: []int64{},
DeleteAt: nil,
DeletedAt: nil,
}
newUser := domain.User{
... ... @@ -144,7 +144,7 @@ func (c SyncDataCompanyService) editCompany(param *command.SaveCompanyCommand) e
_, companyList, err := companyRepo.Find(map[string]interface{}{
"limit": 1,
"id": param.Comapany.Id,
"id": param.Company.Id,
})
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
... ... @@ -165,7 +165,7 @@ func (c SyncDataCompanyService) editCompany(param *command.SaveCompanyCommand) e
newCompany = companyList[0]
} else {
newCompany = &domain.Company{
CreateAt: nowTime,
CreatedAt: nowTime,
}
}
if len(userList) > 0 {
... ... @@ -176,11 +176,11 @@ func (c SyncDataCompanyService) editCompany(param *command.SaveCompanyCommand) e
}
}
newCompany.Id = param.Comapany.Id
newCompany.Logo = param.Comapany.Logo
newCompany.Name = param.Comapany.Name
newCompany.Status = param.Comapany.Status
newCompany.UpdateAt = nowTime
newCompany.Id = param.Company.Id
newCompany.Logo = param.Company.Logo
newCompany.Name = param.Company.Name
newCompany.Status = param.Company.Status
newCompany.UpdatedAt = nowTime
newUser.Id = param.User.Id
newUser.Account = param.User.Phone
... ... @@ -245,7 +245,7 @@ func (srv SyncDataCompanyService) setCompanyCharge(param *command.SetCompanyChar
}
for i := range companyList {
companyList[i].ChargeUserIds = param.ChargeUserIds
companyList[i].UpdateAt = time.Now()
companyList[i].UpdatedAt = time.Now()
_, err = companyRepo.Update(companyList[i])
if err != nil {
return application.ThrowError(application.INTERNAL_SERVER_ERROR, err.Error())
... ...
... ... @@ -81,9 +81,9 @@ func (srv SyncDataDepartmentService) addDepartment(param *command.AddDepartmentC
ParentId: param.ParentId,
ChargeUserIds: param.ChargeUserIds,
Path: param.Path,
CreateAt: nowTime,
UpdateAt: nowTime,
DeleteAt: nil,
CreatedAt: nowTime,
UpdatedAt: nowTime,
DeletedAt: nil,
}
departmentRepo := factory.CreateDepartmentRepository(map[string]interface{}{
... ... @@ -130,11 +130,16 @@ func (srv SyncDataDepartmentService) editDepartment(param *command.EditDepartmen
for i := range departmentList {
if departmentList[i].Id == param.Id {
departmentList[i].CompanyId = param.CompanyId
departmentList[i].Name = param.Name
departmentList[i].Path = param.Path
departmentList[i].ChargeUserIds = make([]int64, 0)
departmentList[i].Level = param.Level
departmentList[i].ParentId = param.ParentId
if param.Name != "" {
departmentList[i].Name = param.Name
}
if param.Path != "" {
departmentList[i].Path = param.Path
}
if param.Level > 0 {
departmentList[i].Level = param.Level
}
if len(param.ChargeUserIds) > 0 {
departmentList[i].ChargeUserIds = param.ChargeUserIds
}
... ... @@ -218,9 +223,9 @@ func (srv SyncDataDepartmentService) importDepartment(param []command.ImportDepa
ParentId: param[i].ParentId,
ChargeUserIds: []int64{},
Path: param[i].Path,
CreateAt: nowTime,
UpdateAt: nowTime,
DeleteAt: nil,
CreatedAt: nowTime,
UpdatedAt: nowTime,
DeletedAt: nil,
}
_, err = departmentRepo.Insert(&newDepartment)
if err != nil {
... ...
package factory
import (
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/serviceGateway"
)
func UCenterApi() domain.UCenterApi {
return serviceGateway.NewHttpLibUCenterApiServiceGateway()
}
func BusinessAdminApi() domain.BusinessAdminApi {
return serviceGateway.NewHttpLibBusinessAdminServiceGateway()
}
... ...
package constant
import "os"
// 用户中心地址
var UCENTER_SERVICE_HOST = "http://suplus-ucenter-test.fjmaimaimai.com"
// var UCENTER_HOST = "https://suplus-ucenter-dev.fjmaimaimai.com" //统一用户中心地址
var UCENTER_SECRET = "cykbjnfqgctn"
var UCENTER_APP_KEY = "39aefef9e22744a3b2d2d3791824ae7b"
var UCENTER_CHECK_ALT = "rsF0pL!6DwjBO735"
// 企业平台地址
var BUSINESS_ADMIN_SERVICE_HOST = "http://suplus-business-admin-test.fjmaimaimai.com"
// 绩效管理平台ID
var PLATFORM_ADMIN_ID = 28
// 员工绩效平台ID
var PLATFORM_FONT_ID = 29
func init() {
if os.Getenv("UCENTER_SERVICE_HOST") != "" {
UCENTER_SERVICE_HOST = os.Getenv("UCENTER_SERVICE_HOST")
}
if os.Getenv("BUSINESS_ADMIN_SERVICE_HOST") != "" {
BUSINESS_ADMIN_SERVICE_HOST = os.Getenv("BUSINESS_ADMIN_SERVICE_HOST")
}
}
... ...
... ... @@ -2,7 +2,7 @@ package constant
import "os"
var POSTGRESQL_DB_NAME = "performance_dev"
var POSTGRESQL_DB_NAME = "performance_test"
var POSTGRESQL_USER = "postgres"
var POSTGRESQL_PASSWORD = "eagle1010"
var POSTGRESQL_HOST = "114.55.200.59"
... ...
package domain
import "gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/serviceGateway/reply"
// UCenterApi 统一用户中心
type UCenterApi interface {
AuthCode(code string) (*reply.UCenterAuthCode, error)
}
// BusinessAdminApi 企业平台
type BusinessAdminApi interface {
GetUserAuth(userId int64, platformId int) (*reply.BusinessAdminUserAuth, error)
}
... ...
... ... @@ -3,14 +3,14 @@ package domain
import "time"
type Company struct {
Id int64 //公司编号
Logo string //公司logo
Name string //公司名称
ChargeUserIds []int64 //公司级别的部门主管uids
Status int //公司状态,1正常 2禁用
UpdateAt time.Time //更新时间
CreateAt time.Time //创建时间
DeleteAt *time.Time
Id int64 //公司编号
Logo string //公司logo
Name string //公司名称
ChargeUserIds []int64 //公司级别的部门主管uids
Status int //公司状态,1正常 2禁用
UpdatedAt time.Time //更新时间
CreatedAt time.Time //创建时间
DeletedAt *time.Time //删除时间
}
type CompanyRepository interface {
... ...
... ... @@ -10,10 +10,11 @@ type Department struct {
ParentId int64 // 组织父级id
ChargeUserIds []int64 // 主管uids
Path string // 组织路径
CreateAt time.Time // 创建时间
UpdateAt time.Time // 更新时间
DeleteAt *time.Time // 删除时间
CreatedAt time.Time // 创建时间
UpdatedAt time.Time // 更新时间
DeletedAt *time.Time // 删除时间
}
type DepartmentRepository interface {
Insert(param *Department) (*Department, error)
Update(param *Department) (*Department, error)
... ...
... ... @@ -10,7 +10,7 @@ type ReceivedMessage struct {
MessageType string `json:"MessageType"`
MessageBody string `json:"MessageBody"`
OccurredOn time.Time `json:"OccurredOn"`
CreateAt time.Time `json:"-"`
CreatedAt time.Time `json:"-"`
}
type MessageBody struct {
... ...
... ... @@ -22,6 +22,8 @@ type User struct {
const (
UserTypeCommon int = 1
UserTypeManager int = 2
UserStatusEnable int = 1
)
type UserRepository interface {
... ...
package domain
import (
"errors"
"github.com/dgrijalva/jwt-go"
"time"
)
type UserAuth struct {
jwt.StandardClaims `json:"-"`
UserId int64 `json:"userId"`
CompanyId int64 `json:"companyId"`
Phone string `json:"phone"`
PlatformId int `json:"platformId"`
Name string `json:"name"`
AdminType int `json:"adminType"`
}
var issuer = "performance"
var secretKey = "Ma9HXITeliSYS43Z"
var JWTExpiresSecond = 3600 * 24
// CreateAccessToken 生成token
func (userAuth *UserAuth) CreateAccessToken() (string, error) {
userAuth.StandardClaims = jwt.StandardClaims{
ExpiresAt: time.Now().Add(time.Duration(JWTExpiresSecond) * time.Second).Unix(),
Issuer: issuer,
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, userAuth)
return token.SignedString([]byte(secretKey))
}
// ParseAccessToken 解析token
func (userAuth *UserAuth) ParseAccessToken(token string) (*UserAuth, error) {
user := &UserAuth{}
tokenClaims, err := jwt.ParseWithClaims(token, user, func(token *jwt.Token) (interface{}, error) {
return []byte(secretKey), nil
})
if err != nil || tokenClaims == nil {
return nil, errors.New("解析token失败")
}
if claim, ok := tokenClaims.Claims.(*UserAuth); ok && tokenClaims.Valid {
user.UserId = claim.UserId
user.CompanyId = claim.CompanyId
user.Phone = claim.Phone
user.PlatformId = claim.PlatformId
user.Name = claim.Name
user.AdminType = claim.AdminType
return user, nil
}
return user, errors.New("解析token失败")
}
... ...
... ... @@ -9,7 +9,7 @@ type Company struct {
Name string //公司名称
ChargeUserIds []int64 //公司级别的部门主管uids
Status int //公司状态,1正常 2禁用
UpdateAt time.Time //更新时间
CreateAt time.Time //创建时间
DeleteAt *time.Time `pg:",soft_delete"` //删除时间
CreatedAt time.Time //创建时间
UpdatedAt time.Time //更新时间
DeletedAt *time.Time `pg:",soft_delete"` //删除时间
}
... ...
... ... @@ -13,7 +13,7 @@ type Department struct {
ParentId int64 `pg:",use_zero"` // 组织父级id
ChargeUserIds []int64 // 主管uids
Path string // 组织路径
CreateAt time.Time // 创建时间
UpdateAt time.Time // 更新时间
DeleteAt *time.Time `pg:",soft_delete"` // 删除时间
CreatedAt time.Time // 创建时间
UpdatedAt time.Time // 更新时间
DeletedAt *time.Time `pg:",soft_delete"` // 删除时间
}
... ...
... ... @@ -8,5 +8,7 @@ type ReceivedMessage struct {
MessageType string
MessageBody string
OccurredOn time.Time
CreateAt time.Time
CreatedAt time.Time `pg:"default:now()"`
UpdatedAt time.Time `pg:"default:now()"`
DeletedAt *time.Time `pg:",soft_delete"`
}
... ...
... ... @@ -11,5 +11,5 @@ type Role struct {
CompanyId int64 `comment:"公司ID"`
CreatedAt time.Time `comment:"创建时间"`
UpdatedAt time.Time `comment:"更新时间"`
DeletedAt *time.Time `comment:"删除时间"`
DeletedAt *time.Time `comment:"删除时间" pg:",soft_delete"`
}
... ...
... ... @@ -10,5 +10,5 @@ type RoleUser struct {
CompanyId int64 `comment:"公司ID"`
CreatedAt time.Time `comment:"创建时间"`
UpdatedAt time.Time `comment:"更新时间"`
DeletedAt *time.Time `comment:"删除时间"`
DeletedAt *time.Time `comment:"删除时间" pg:",soft_delete"`
}
... ...
... ... @@ -14,7 +14,7 @@ type User struct {
Status int // 用户状态(1正常 2禁用)
DepartmentId []int // 用户归属的部门
PositionId []int // 用户职位
UpdateAt time.Time // 更新时间
CreateAt time.Time // 创建时间
DeleteAt *time.Time `pg:",soft_delete"` // 删除时间
CreatedAt time.Time // 创建时间
UpdatedAt time.Time // 更新时间
DeletedAt *time.Time `pg:",soft_delete"` // 删除时间
}
... ...
... ... @@ -28,9 +28,9 @@ func (repo *CompanyRepository) Insert(u *domain.Company) (*domain.Company, error
Name: u.Name,
Status: u.Status,
ChargeUserIds: u.ChargeUserIds,
UpdateAt: u.UpdateAt,
CreateAt: u.CreateAt,
DeleteAt: u.DeleteAt,
UpdatedAt: u.UpdatedAt,
CreatedAt: u.CreatedAt,
DeletedAt: u.DeletedAt,
}
tx := repo.transactionContext.PgTx
_, err := tx.Model(&companyModel).Insert()
... ... @@ -48,9 +48,9 @@ func (repo *CompanyRepository) Update(u *domain.Company) (*domain.Company, error
Name: u.Name,
Status: u.Status,
ChargeUserIds: u.ChargeUserIds,
UpdateAt: u.UpdateAt,
CreateAt: u.CreateAt,
DeleteAt: u.DeleteAt,
UpdatedAt: u.UpdatedAt,
CreatedAt: u.CreatedAt,
DeletedAt: u.DeletedAt,
}
tx := repo.transactionContext.PgTx
_, err := tx.Model(&companyModel).WherePK().Update()
... ... @@ -62,7 +62,7 @@ func (repo *CompanyRepository) Update(u *domain.Company) (*domain.Company, error
func (repo *CompanyRepository) Remove(u *domain.Company) (*domain.Company, error) {
nowTime := time.Now()
u.DeleteAt = &nowTime
u.DeletedAt = &nowTime
_, err := repo.Update(u)
return u, err
}
... ... @@ -113,12 +113,12 @@ func (repo *CompanyRepository) Find(queryOptions map[string]interface{}) (int, [
func (repo *CompanyRepository) TransformToCompanyDomain(m *models.Company) *domain.Company {
return &domain.Company{
Id: m.Id,
Logo: m.Logo,
Name: m.Name,
Status: m.Status,
UpdateAt: m.UpdateAt,
CreateAt: m.CreateAt,
DeleteAt: m.DeleteAt,
Id: m.Id,
Logo: m.Logo,
Name: m.Name,
Status: m.Status,
UpdatedAt: m.UpdatedAt,
CreatedAt: m.CreatedAt,
DeletedAt: m.DeletedAt,
}
}
... ...
... ... @@ -30,9 +30,9 @@ func (repo *DepartmentRepository) Insert(u *domain.Department) (*domain.Departme
ParentId: u.ParentId,
ChargeUserIds: u.ChargeUserIds,
Path: u.Path,
CreateAt: u.CreateAt,
UpdateAt: u.UpdateAt,
DeleteAt: nil,
CreatedAt: u.CreatedAt,
UpdatedAt: u.UpdatedAt,
DeletedAt: nil,
}
tx := repo.transactionContext.PgTx
_, err := tx.Model(&departmentModel).Insert()
... ... @@ -52,9 +52,9 @@ func (repo *DepartmentRepository) Update(u *domain.Department) (*domain.Departme
ParentId: u.ParentId,
ChargeUserIds: u.ChargeUserIds,
Path: u.Path,
CreateAt: u.CreateAt,
UpdateAt: u.UpdateAt,
DeleteAt: u.DeleteAt,
CreatedAt: u.CreatedAt,
UpdatedAt: u.UpdatedAt,
DeletedAt: u.DeletedAt,
}
tx := repo.transactionContext.PgTx
_, err := tx.Model(&departmentModel).WherePK().Update()
... ... @@ -95,14 +95,14 @@ func (repo *DepartmentRepository) FindOne(queryOptions map[string]interface{}) (
func (repo *DepartmentRepository) Find(queryOptions map[string]interface{}) (int, []*domain.Department, error) {
tx := repo.transactionContext.PgTx
dparmentModel := []models.Department{}
var dparmentModel []models.Department
query := tx.Model(&dparmentModel).
Limit(20)
if v, ok := queryOptions["id"]; ok {
query.Where("id=?", v)
}
if v, ok := queryOptions["ids"]; ok {
query.Where("id in(?)", pg.In(v))
query.Where("id in (?)", pg.In(v))
}
if v, ok := queryOptions["limit"]; ok {
query.Limit(v.(int))
... ... @@ -131,8 +131,8 @@ func (repo *DepartmentRepository) TransformToCompanyDomain(u *models.Department)
ParentId: u.ParentId,
ChargeUserIds: u.ChargeUserIds,
Path: u.Path,
CreateAt: u.CreateAt,
UpdateAt: u.UpdateAt,
DeleteAt: u.DeleteAt,
CreatedAt: u.CreatedAt,
UpdatedAt: u.UpdatedAt,
DeletedAt: u.DeletedAt,
}
}
... ...
... ... @@ -27,7 +27,7 @@ func (repo *ReceivedMessageRepository) SaveMessage(param *domain.ReceivedMessage
MessageType: param.MessageType,
MessageBody: param.MessageBody,
OccurredOn: param.OccurredOn,
CreateAt: time.Now(),
CreatedAt: time.Now(),
}
tx := repo.transactionContext.PgTx
_, err := tx.Model(message).
... ... @@ -50,7 +50,7 @@ func (repo *ReceivedMessageRepository) FindMessage(messageId int64) (*domain.Rec
MessageType: receivedMessageModel.MessageType,
MessageBody: receivedMessageModel.MessageBody,
OccurredOn: receivedMessageModel.OccurredOn,
CreateAt: receivedMessageModel.CreateAt,
CreatedAt: receivedMessageModel.CreatedAt,
}
return message, nil
... ...
... ... @@ -30,9 +30,9 @@ func (repo *UserRepository) Insert(user *domain.User) (*domain.User, error) {
AdminType: user.AdminType,
Name: user.Name,
Status: user.Status,
UpdateAt: user.UpdateAt,
CreateAt: user.CreateAt,
DeleteAt: user.DeleteAt,
UpdatedAt: user.UpdateAt,
CreatedAt: user.CreateAt,
DeletedAt: user.DeleteAt,
}
tx := repo.transactionContext.PgTx
_, err := tx.Model(&userModel).Insert()
... ... @@ -53,9 +53,9 @@ func (repo *UserRepository) Update(user *domain.User) (*domain.User, error) {
Name: user.Name,
Email: user.Email,
Status: user.Status,
UpdateAt: user.UpdateAt,
CreateAt: user.CreateAt,
DeleteAt: user.DeleteAt,
UpdatedAt: user.UpdateAt,
CreatedAt: user.CreateAt,
DeletedAt: user.DeleteAt,
}
tx := repo.transactionContext.PgTx
_, err := tx.Model(&userModel).WherePK().Update()
... ... @@ -83,6 +83,9 @@ func (repo *UserRepository) FindOne(queryOptions map[string]interface{}) (*domai
if v, ok := queryOptions["id"]; ok {
query.Where("id=?", v)
}
if v, ok := queryOptions["companyId"]; ok {
query.Where("company_id = ?", v)
}
err := query.First()
if err == pg.ErrNoRows {
return nil, ErrNoRows
... ... @@ -142,8 +145,8 @@ func (repo *UserRepository) TransformToUserDomain(user *models.User) *domain.Use
Name: user.Name,
Email: user.Email,
Status: user.Status,
UpdateAt: user.UpdateAt,
CreateAt: user.CreateAt,
DeleteAt: user.DeleteAt,
UpdateAt: user.UpdatedAt,
CreateAt: user.CreatedAt,
DeleteAt: user.DeletedAt,
}
}
... ...
package serviceGateway
import (
"crypto/tls"
"encoding/json"
"github.com/beego/beego/v2/client/httplib"
"github.com/linmadan/egglib-go/utils/tool_funs"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/log"
"io/ioutil"
"net/http"
"reflect"
"strings"
"time"
)
type httpLibBaseServiceGateway struct {
baseURL string
connectTimeout time.Duration
readWriteTimeout time.Duration
request *httplib.BeegoHTTPRequest
params map[string]interface{}
body string
}
func (client *httpLibBaseServiceGateway) CreateRequest(method, url string) {
client.request = httplib.NewBeegoRequest(client.baseURL+url, strings.ToUpper(method))
client.request.SetTLSClientConfig(&tls.Config{InsecureSkipVerify: true})
}
// 设置请求参数
func (client *httpLibBaseServiceGateway) SetParams(params map[string]string) {
if len(params) > 0 {
for key, value := range params {
client.request.Param(key, value)
client.params[key] = value
}
}
}
// 设置请求参数
func (client *httpLibBaseServiceGateway) SetParam(key, value string) {
client.request.Param(key, value)
client.params[key] = value
}
// 设置body
func (client *httpLibBaseServiceGateway) SetBody(body interface{}) {
//判断是否为string
ty := reflect.TypeOf(body)
if ty.Name() == "string" {
client.request.Body(body)
client.body = body.(string)
} else {
mBytes, _ := json.Marshal(body)
client.request.Body(mBytes)
client.body = string(mBytes)
}
client.request.Header("Content-Type", "application/json")
client.request.Header("Accept", "application/json")
}
// 设置头信息
func (client *httpLibBaseServiceGateway) SetHeader(key, value string) {
client.request.Header(key, value)
}
// 设置多个头部信息
func (client *httpLibBaseServiceGateway) SetHeaders(headers map[string]string) {
if len(headers) > 0 {
for key, value := range headers {
client.request.Header(key, value)
}
}
}
// 设置超时时间
func (client *httpLibBaseServiceGateway) SetTimeout(connectTimeout, readWriteTimeout time.Duration) {
client.request.SetTimeout(connectTimeout, readWriteTimeout)
}
// 设置cookie
func (client *httpLibBaseServiceGateway) SetCookie(cookie *http.Cookie) {
client.request.SetCookie(cookie)
}
// 设置UserAgent
func (client *httpLibBaseServiceGateway) SetUserAgent(userAgent string) {
client.request.SetUserAgent(userAgent)
}
// 请求结果返回结构体
func (client *httpLibBaseServiceGateway) ToJson(result interface{}) error {
response, err := client.request.Response()
if err != nil {
return err
}
client.addOptionLog(response)
mBytes, err := ioutil.ReadAll(response.Body)
if err != nil {
return err
}
err = json.Unmarshal(mBytes, result)
//增加返回数据日志
log.Logger.Debug(response.Request.Method+" "+response.Request.URL.String()+"----response----", tool_funs.SimpleStructToMap(result))
return err
}
// 请求结果返回string
func (client *httpLibBaseServiceGateway) ToString() (string, error) {
response, err := client.request.Response()
if err != nil {
return "", err
}
client.addOptionLog(response)
mBytes, err := ioutil.ReadAll(response.Body)
//增加返回数据日志
log.Logger.Debug(response.Request.Method + " " + response.Request.URL.String() + "----response----" + string(mBytes))
return string(mBytes), err
}
// 请求结果返回bytes
func (client *httpLibBaseServiceGateway) ToBytes() ([]byte, error) {
response, err := client.request.Response()
if err != nil {
return nil, err
}
client.addOptionLog(response)
mBytes, _ := ioutil.ReadAll(response.Body)
//增加返回数据日志
log.Logger.Debug(response.Request.Method + " " + response.Request.URL.String() + "----response----" + string(mBytes))
return mBytes, nil
}
// 添加options日志
func (client *httpLibBaseServiceGateway) addOptionLog(response *http.Response) {
logTxt := response.Request.Method + " " + response.Request.URL.String()
if response.Request.Method != http.MethodGet {
contentType := client.request.GetRequest().Header.Get("Content-Type")
if strings.Contains(strings.ToLower(contentType), "json") {
log.Logger.Debug(logTxt+" ----options----", map[string]interface{}{"body": client.body})
} else {
log.Logger.Debug(logTxt+" ----options----", map[string]interface{}{"params": client.params})
}
}
}
... ...
package serviceGateway
import (
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/serviceGateway/reply"
"net/http"
)
type HttpLibBusinessAdminServiceGateway struct {
httpLibBaseServiceGateway
}
// GetUserAuth 请求企业平台确认用户是否可以使用
func (serviceGateway *HttpLibBusinessAdminServiceGateway) GetUserAuth(userId int64, platformId int) (*reply.BusinessAdminUserAuth, error) {
businessAdminUserAuth := &reply.BusinessAdminUserAuth{}
serviceGateway.CreateRequest(http.MethodPost, "/auth/get-user-auth")
serviceGateway.SetBody(map[string]interface{}{
"userId": userId,
"platformId": platformId,
})
err := serviceGateway.ToJson(businessAdminUserAuth)
return businessAdminUserAuth, err
}
func NewHttpLibBusinessAdminServiceGateway() *HttpLibBusinessAdminServiceGateway {
return &HttpLibBusinessAdminServiceGateway{
httpLibBaseServiceGateway{
baseURL: constant.BUSINESS_ADMIN_SERVICE_HOST,
},
}
}
... ...
package serviceGateway
import (
"crypto/sha1"
"fmt"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/infrastructure/serviceGateway/reply"
"net/http"
"net/url"
"time"
)
type HttpLibUCenterApiServiceGateway struct {
httpLibBaseServiceGateway
}
func (serviceGateway *HttpLibUCenterApiServiceGateway) buildHeaders() map[string]string {
nowTime := fmt.Sprint(time.Now().Unix())
str := fmt.Sprintf("%s%s%s", nowTime, constant.UCENTER_SECRET, constant.UCENTER_CHECK_ALT)
bt := sha1.Sum([]byte(str))
checksum := fmt.Sprintf("%x", bt)
return map[string]string{
"appKey": constant.UCENTER_APP_KEY,
"nonce": "",
"curTime": nowTime,
"checkSum": checksum,
}
}
// AuthCode PC端登录
func (serviceGateway *HttpLibUCenterApiServiceGateway) AuthCode(code string) (*reply.UCenterAuthCode, error) {
authCodeReply := &reply.UCenterAuthCode{}
serviceGateway.CreateRequest(http.MethodPost, "/auth/serverLogin")
serviceGateway.SetBody(map[string]interface{}{
"type": 3,
"secret": url.QueryEscape(code),
})
serviceGateway.SetHeaders(serviceGateway.buildHeaders())
err := serviceGateway.ToJson(authCodeReply)
return authCodeReply, err
}
func NewHttpLibUCenterApiServiceGateway() *HttpLibUCenterApiServiceGateway {
return &HttpLibUCenterApiServiceGateway{
httpLibBaseServiceGateway{baseURL: constant.UCENTER_SERVICE_HOST},
}
}
... ...
package reply
type BaseReply struct {
Code int `json:"code"`
Msg string `json:"msg"`
}
func (msg *BaseReply) IsOk() bool {
if msg.Code != 0 {
return false
}
return true
}
... ...
package reply
type BusinessAdminUserAuth struct {
BaseReply
Data struct {
UserAuth bool `json:"userAuth"`
} `json:"data"`
}
func (businessAdminUserAuth *BusinessAdminUserAuth) Message() string {
if businessAdminUserAuth.Code == 10001 {
return "用户不存在"
}
if businessAdminUserAuth.Code == 10002 {
return "登录凭证已过期,请重新登陆"
}
if businessAdminUserAuth.Code == 10003 {
return "验证码不能为空"
}
if businessAdminUserAuth.Code == 10004 {
return "登录凭证不能为空"
}
if businessAdminUserAuth.Code == 10005 {
return "密码不能为空"
}
if businessAdminUserAuth.Code == 10006 {
return "当前账号已被禁用"
}
if businessAdminUserAuth.Code == 10007 {
return "该企业已被禁用,无法正常访问!重新选择其他企业进入,或退出登录。"
}
if businessAdminUserAuth.Code == 10008 {
return "抱歉,企业管理员未帮您开通权限。如需访问,请联系企业管理员"
}
if businessAdminUserAuth.Code == 10009 {
return "密码错误"
}
if businessAdminUserAuth.Code == 10010 {
return "验证码错误"
}
return "你没有权限进入系统,请联系管理员"
}
... ...
package reply
type UCenterAuthCode struct {
BaseReply
Data struct {
Id int64 `json:"id"` //统一用户中心的id,对应本系统中users表的open_id
Phone string `json:"phone"` //手机号 ,账号
NickName string `json:"nickname"` //昵称
Avatar string `json:"avatar"` //头像
ImToken string `json:"imtoken"` //网易云imtoken
AccId int64 `json:"accid"` //网易云id
CustomerAccount int64 `json:"customerAccount"` //客服id
CompanyId int64 `json:"companyId"` //总后台的公司id ,对应company表中的admin_company_id
MUid int64 `json:"muid"` //企业平台的用户id,对应本系统中users表的id
} `json:"data"`
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/auth/command"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/application/auth/service"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
)
type AuthController struct {
beego.BaseController
}
// Login PC端登录
func (controller *AuthController) Login() {
authService := &service.AuthService{}
loginCommand := &command.LoginCommand{}
_ = controller.Unmarshal(loginCommand)
resp, err := authService.Login(loginCommand)
controller.Response(resp, err)
}
func (controller *AuthController) User() {
userAuth := controller.Ctx.Input.GetData(domain.UserAuth{}).(*domain.UserAuth)
controller.Response(map[string]interface{}{
"user": userAuth,
}, nil)
}
... ...
package middlewares
import (
"github.com/beego/beego/v2/server/web/context"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
)
func CheckAdminToken() func(ctx *context.Context) {
return func(ctx *context.Context) {
adminToken := ctx.Input.Header("x-admin-token")
userAuth, err := (&domain.UserAuth{}).ParseAccessToken(adminToken)
if err != nil || userAuth.UserId <= 0 {
forbidden(ctx)
return
}
if userAuth.PlatformId != constant.PLATFORM_ADMIN_ID {
forbidden(ctx)
return
}
ctx.Input.SetData(domain.UserAuth{}, userAuth)
}
}
func forbidden(ctx *context.Context) {
resp := map[string]interface{}{
"code": 902,
"msg": "Authorization过期或无效,需要进行重新获取令牌",
}
_ = ctx.Output.JSON(resp, false, false)
}
... ...
package middlewares
import (
"github.com/beego/beego/v2/server/web/context"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/constant"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/domain"
)
func CheckFontToken() func(ctx *context.Context) {
return func(ctx *context.Context) {
adminToken := ctx.Input.Header("x-font-token")
userAuth, err := (&domain.UserAuth{}).ParseAccessToken(adminToken)
if err != nil || userAuth.UserId <= 0 {
forbidden(ctx)
return
}
if userAuth.PlatformId != constant.PLATFORM_FONT_ID {
forbidden(ctx)
return
}
ctx.Input.SetData(domain.UserAuth{}, userAuth)
}
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/port/beego/controllers"
"gitlab.fjmaimaimai.com/allied-creation/performance/pkg/port/beego/middlewares"
)
func init() {
web.Router("/login", &controllers.AuthController{}, "Post:Login")
web.InsertFilter("/auth/admin/*", web.BeforeExec, middlewares.CheckAdminToken())
web.Router("/auth/admin/user", &controllers.AuthController{}, "Get:User")
web.InsertFilter("/auth/font/*", web.BeforeExec, middlewares.CheckFontToken())
web.Router("/auth/font/user", &controllers.AuthController{}, "Get:User")
}
... ...