作者 tangxuhui

新建

#!/bin/bash
export PATH=/root/local/bin:$PATH
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
if [ "$?" == "1" ];then
kubectl create -f /tmp/dev/project/project.yaml --record
kubectl -n <replace-your-k8s-namespace> get svc | grep -q project
if [ "$?" == "0" ];then
echo "project service install success!"
else
echo "project service install fail!"
fi
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
if [ "$?" == "0" ];then
echo "project deployment install success!"
else
echo "project deployment install fail!"
fi
else
kubectl delete -f /tmp/dev/project/project.yaml
kubectl -n <replace-your-k8s-namespace> get svc | grep -q project
while [ "$?" == "0" ]
do
kubectl -n <replace-your-k8s-namespace> get svc | grep -q project
done
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
while [ "$?" == "0" ]
do
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
done
kubectl create -f /tmp/dev/project/project.yaml --record
kubectl -n <replace-your-k8s-namespace> get svc | grep -q project
if [ "$?" == "0" ];then
echo "project service update success!"
else
echo "project service update fail!"
fi
kubectl -n <replace-your-k8s-namespace> get pods | grep -q project
if [ "$?" == "0" ];then
echo "project deployment update success!"
else
echo "project deployment update fail!"
fi
fi
\ No newline at end of file
... ...
apiVersion: v1
kind: Service
metadata:
name: project
namespace: <replace-your-k8s-namespace>
labels:
k8s-app: project
spec:
ports:
- name: "http"
port: 80
targetPort: 8082
selector:
k8s-app: project
---
apiVersion: extensions/v1beta1
kind: Deployment
metadata:
name: project
namespace: <replace-your-k8s-namespace>
labels:
k8s-app: project
spec:
replicas: 1
template:
metadata:
labels:
k8s-app: project
spec:
affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- preference: {}
weight: 100
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/hostname
operator: In
values:
- cn-hangzhou.i-bp1djh1xn7taumbue1ze
- cn-hangzhou.i-bp1djh1xn7taumbue1zd
- cn-hangzhou.i-bp1euf5u1ph9kbhtndhb
- cn-hangzhou.i-bp1hyp5oips9cdwxxgxy
containers:
- name: project
image: 192.168.0.243:5000/mmm/project:dev
imagePullPolicy: Always
ports:
- containerPort: 8082
volumeMounts:
- mountPath: /opt/logs
name: accesslogs
env:
- name: LOG_LEVEL
value: "debug"
- name: ERROR_BASE_CODE
value: "1"
- name: ERROR_BASE_CODE_MULTIPLE
value: "1000"
volumes:
- name: accesslogs
emptyDir: {}
\ No newline at end of file
... ...
... ... @@ -2,4 +2,12 @@ module gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway
go 1.16
require github.com/beego/beego/v2 v2.0.1
require (
github.com/beego/beego/v2 v2.0.1
github.com/boombuler/barcode v1.0.1
github.com/dgrijalva/jwt-go v3.2.0+incompatible
github.com/go-pg/pg/v10 v10.10.1
github.com/go-redis/redis v6.14.2+incompatible
github.com/linmadan/egglib-go v0.0.0-20210527091316-06b0732fb5f6
github.com/sony/sonyflake v1.0.0
)
... ...
package factory
import (
"github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/repository"
)
func CreateLoginAccessRepository(options map[string]interface{}) (domain.LoginAccessRepository, error) {
var transactionContext *pg.TransactionContext
if value, ok := options["transactionContext"]; ok {
transactionContext = value.(*pg.TransactionContext)
}
return repository.NewLoginAccessRepository(transactionContext)
}
... ...
package factory
import (
"github.com/linmadan/egglib-go/core/application"
pG "github.com/linmadan/egglib-go/transaction/pg"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/pg"
)
func CreateTransactionContext(options map[string]interface{}) (application.TransactionContext, error) {
return pG.NewPGTransactionContext(pg.DB), nil
}
... ...
package query
import (
"fmt"
"github.com/beego/beego/v2/core/validation"
)
type GetQrcodeForLoginQuery struct {
}
func (getQrcodeForLoginQuery *GetQrcodeForLoginQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (getQrcodeForLoginQuery *GetQrcodeForLoginQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(getQrcodeForLoginQuery)
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 LoginByAccountQuery struct {
// 账号
Account string `json:"account,omitempty"`
// 密码
Passwd string `json:"passwd,omitempty"`
}
func (loginByAccountQuery *LoginByAccountQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (loginByAccountQuery *LoginByAccountQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(loginByAccountQuery)
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 LoginByScanQrcodeQuery struct {
// 登录认证的凭证
AuthCode string `json:"authCode,omitempty"`
}
func (loginByScanQrcodeQuery *LoginByScanQrcodeQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (loginByScanQrcodeQuery *LoginByScanQrcodeQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(loginByScanQrcodeQuery)
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 LoginBySmsCodeQuery struct {
// 手机号
Phone string `json:"phone,omitempty"`
// 短信验证码
SmsCode string `json:"smsCode,omitempty"`
}
func (loginBySmsCodeQuery *LoginBySmsCodeQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (loginBySmsCodeQuery *LoginBySmsCodeQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(loginBySmsCodeQuery)
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 LoginInfoByAuthCodeQuery struct {
// 登录认证的凭证
AuthCode string `json:"authCode,omitempty"`
// 公司id
CompanyId string `json:"companyId,omitempty"`
// 组织id
OrganizationId string `json:"organizationId,omitempty"`
}
func (loginInfoByAuthCodeQuery *LoginInfoByAuthCodeQuery) Valid(validation *validation.Validation) {
validation.SetError("CustomValid", "未实现的自定义认证")
}
func (loginInfoByAuthCodeQuery *LoginInfoByAuthCodeQuery) ValidateQuery() error {
valid := validation.Validation{}
b, err := valid.Valid(loginInfoByAuthCodeQuery)
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/allied-creation/allied-creation-gateway/pkg/application/factory"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/loginAccess/query"
)
// 登录访问
type LoginAccessService struct {
}
// 获取扫码登录用的二维码信息
func (loginAccessService *LoginAccessService) GetQrcodeForLogin(getQrcodeForLoginQuery *query.GetQrcodeForLoginQuery) (interface{}, error) {
if err := getQrcodeForLoginQuery.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()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 使用手机号和密码登录系统
func (loginAccessService *LoginAccessService) LoginByAccount(loginByAccountQuery *query.LoginByAccountQuery) (interface{}, error) {
if err := loginByAccountQuery.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()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 询问扫二维码方式登录的状态
func (loginAccessService *LoginAccessService) LoginByScanQrcode(loginByScanQrcodeQuery *query.LoginByScanQrcodeQuery) (interface{}, error) {
if err := loginByScanQrcodeQuery.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()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 使用手机号和短信验证码登录系统
func (loginAccessService *LoginAccessService) LoginBySmsCode(loginBySmsCodeQuery *query.LoginBySmsCodeQuery) (interface{}, error) {
if err := loginBySmsCodeQuery.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()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
// 获取具体的进入系统的凭证
func (loginAccessService *LoginAccessService) LoginInfoByAuthCode(loginInfoByAuthCodeQuery *query.LoginInfoByAuthCodeQuery) (interface{}, error) {
if err := loginInfoByAuthCodeQuery.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()
}()
if err := transactionContext.CommitTransaction(); err != nil {
return nil, application.ThrowError(application.TRANSACTION_ERROR, err.Error())
}
return nil, nil
}
func NewLoginAccessService(options map[string]interface{}) *LoginAccessService {
newLoginAccessService := &LoginAccessService{}
return newLoginAccessService
}
... ...
package query
type GetAccessTokenCommand struct {
AuthCode string `json:"authCode"`
}
func (cmd GetAccessTokenCommand) Valid() error {
return nil
}
... ...
package query
type GetAccessTokenCommand struct {
AuthCode string `json:"authCode"`
}
func (cmd GetAccessTokenCommand) Valid() error {
return nil
}
... ...
package services
import (
"fmt"
"github.com/dgrijalva/jwt-go"
"github.com/sony/sonyflake"
)
var idwork *sonyflake.Sonyflake
func init() {
setting := sonyflake.Settings{
MachineID: func() (uint16, error) {
return 1, nil
},
CheckMachineID: func(u uint16) bool {
return true
},
}
idwork = sonyflake.NewSonyflake(setting)
}
const (
qrcodeExpires int64 = 3600 //二维码的有效时长,单位:秒
qrcodeSecret string = "27e6741f0e0b658c"
)
type qrcodeMessage struct {
Key string `json:"key"`
jwt.StandardClaims
}
func (msg *qrcodeMessage) GenrateToken() (string, error) {
id, err := idwork.NextID()
if err != nil {
return "", fmt.Errorf("生成二维信息失败:%w", err)
}
msg.Key = fmt.Sprint(id)
//TODO jwt
return "", nil
}
func (msg *qrcodeMessage) ParseToken(token string) error {
//TODO jwt
return nil
}
... ...
package services
import (
"bytes"
"context"
"encoding/base64"
"image/png"
"github.com/boombuler/barcode"
"github.com/boombuler/barcode/qr"
)
//LoginAccessService 登录功能
type LoginAccessService struct {
}
//LoginByAccount 账号登录获取authcode和可选择列表
func (srv LoginAccessService) LoginByAccount(ctx context.Context) error {
return nil
}
//LoginBySmsCode 短信验证码登录获取authcode和可选择列表
func (srv LoginAccessService) LoginBySmsCode(ctx context.Context) error {
return nil
}
//LoginByAuthCode 使用authCode进行登录获取accessToken和用户权限信息
func (srv LoginAccessService) LoginInfoByAuthCode(ctx context.Context) error {
return nil
}
//GetQrcodeLogin 获取用于登录的二维码以及相应的key数据
func (srv LoginAccessService) GetQrcodeForLogin(ctx context.Context) error {
qrCode, err := qr.Encode("Hello World", qr.M, qr.Auto)
if err != nil {
return err
}
// Scale the barcode to 200x200 pixels
qrCode, err = barcode.Scale(qrCode, 200, 200)
if err != nil {
return err
}
var imgByte bytes.Buffer
// encode the barcode as png
err = png.Encode(&imgByte, qrCode)
if err != nil {
return err
}
imgBase64 := base64.StdEncoding.EncodeToString(imgByte.Bytes())
_ = imgBase64
return err
}
//ValidLoginForQrcode 检查以扫描二维码方式进行登录的状态
func (srv LoginAccessService) LoginByScanQrcode(ctx context.Context) error {
return nil
}
// ValidToken 检查token信息
func (srv LoginAccessService) ValidAccessToken(ctx context.Context) error {
return nil
}
// AuthCodeToAccessToken 用authcode交换accessToken
func (srv LoginAccessService) AuthCodeToAccessToken(ctx context.Context) error {
return nil
}
... ...
package constant
import "os"
const SERVICE_NAME = "project"
var LOG_LEVEL = "debug"
func init() {
if os.Getenv("LOG_LEVEL") != "" {
LOG_LEVEL = os.Getenv("LOG_LEVEL")
}
}
... ...
package constant
import "os"
var POSTGRESQL_DB_NAME = "project"
var POSTGRESQL_USER = "postgres"
var POSTGRESQL_PASSWORD = ""
var POSTGRESQL_HOST = "127.0.0.1"
var POSTGRESQL_PORT = "32432"
var DISABLE_CREATE_TABLE = false
var DISABLE_SQL_GENERATE_PRINT = false
func init() {
if os.Getenv("POSTGRESQL_DB_NAME") != "" {
POSTGRESQL_DB_NAME = os.Getenv("POSTGRESQL_DB_NAME")
}
if os.Getenv("POSTGRESQL_USER") != "" {
POSTGRESQL_USER = os.Getenv("POSTGRESQL_USER")
}
if os.Getenv("POSTGRESQL_PASSWORD") != "" {
POSTGRESQL_PASSWORD = os.Getenv("POSTGRESQL_PASSWORD")
}
if os.Getenv("POSTGRESQL_HOST") != "" {
POSTGRESQL_HOST = os.Getenv("POSTGRESQL_HOST")
}
if os.Getenv("POSTGRESQL_PORT") != "" {
POSTGRESQL_PORT = os.Getenv("POSTGRESQL_PORT")
}
if os.Getenv("DISABLE_CREATE_TABLE") != "" {
DISABLE_CREATE_TABLE = true
}
if os.Getenv("DISABLE_SQL_GENERATE_PRINT") != "" {
DISABLE_SQL_GENERATE_PRINT = true
}
}
... ...
package constant
var ValidationMessageTmpls = map[string]string{
"Required": "不能为空",
"Min": "最小值: %d",
"Max": "最大值: %d",
"Range": "数值的范围 %d - %d",
"MinSize": "最小长度: %d",
"MaxSize": "最大长度: %d",
"Length": "指定长度: %d",
"Alpha": "必须为有效的字母字符",
"Numeric": "必须为有效的数字",
"AlphaNumeric": "必须为有效的字母或数字",
"Match": "必须匹配 %s",
"NoMatch": "必须不匹配 %s",
"AlphaDash": "必须为字母、数字或横杠(-_)",
"Email": "必须为邮箱格式",
"IP": "必须为有效的IP格式",
"Base64": "必须为有效的base64字符",
"Mobile": "必须有效的手机号码",
"Tel": "必须是有效的电话号码",
"Phone": "必须是有效的电话或手机号码",
"ZipCode": "必须是有效的邮政编码",
}
\ No newline at end of file
... ...
package domain
import "time"
// 登录凭证存储
type LoginAccess struct {
LoginAccessId int64 `json:"loginAccessId"`
// 账号
Account string `json:"account"`
// 对应平台
Platform string `json:"platform"`
// 公司id
CompanyId int64 `json:"companyId"`
// 组织id
OrganizationId int64 `json:"organizationId"`
// 登录凭证存储
AccessToken string `json:"accessToken"`
// 刷新登录凭证
RefreshToken string `json:"refreshToken"`
// 登录凭证过期时间,时间戳精度秒
AccessExpired int64 `json:"accessExpired"`
// 刷新登录凭证过期时间,时间戳精度秒
RefreshExpired int64 `json:"refreshExpired"`
// 创建时间
CreatedTime time.Time `json:"createdTime"`
// 更新时间
UpdatedTime time.Time `json:"updatedTime"`
}
type LoginAccessRepository interface {
Save(loginAccess *LoginAccess) (*LoginAccess, error)
Remove(loginAccess *LoginAccess) (*LoginAccess, error)
FindOne(queryOptions map[string]interface{}) (*LoginAccess, error)
Find(queryOptions map[string]interface{}) (int64, []*LoginAccess, error)
}
func (loginAccess *LoginAccess) Identify() interface{} {
if loginAccess.LoginAccessId == 0 {
return nil
}
return loginAccess.LoginAccessId
}
func (loginAccess *LoginAccess) Update(data map[string]interface{}) error {
if account, ok := data["account"]; ok {
loginAccess.Account = account.(string)
}
if platform, ok := data["platform"]; ok {
loginAccess.Platform = platform.(string)
}
if companyId, ok := data["companyId"]; ok {
loginAccess.CompanyId = companyId.(int64)
}
if organizationId, ok := data["organizationId"]; ok {
loginAccess.OrganizationId = organizationId.(int64)
}
if accessToken, ok := data["accessToken"]; ok {
loginAccess.AccessToken = accessToken.(string)
}
if refreshToken, ok := data["refreshToken"]; ok {
loginAccess.RefreshToken = refreshToken.(string)
}
if accessExpired, ok := data["accessExpired"]; ok {
loginAccess.AccessExpired = accessExpired.(int64)
}
if refreshExpired, ok := data["refreshExpired"]; ok {
loginAccess.RefreshExpired = refreshExpired.(int64)
}
if createdTime, ok := data["createdTime"]; ok {
loginAccess.CreatedTime = createdTime.(time.Time)
}
if updatedTime, ok := data["updatedTime"]; ok {
loginAccess.UpdatedTime = updatedTime.(time.Time)
}
return nil
}
... ...
package domain
... ...
package domain
const (
loginTokenSecret string = "bbe35ad433dd8e67"
)
type LoginToken struct {
Account string `json:"account"`
CompanyId int64 `json:"companyId"`
DepartmentId int64 `json:"departmentId"`
}
func (t *LoginToken) GenerateAccessToken() error {
return nil
}
func (t *LoginToken) GenerateRefreshToken() error {
return nil
}
func (t *LoginToken) ParseToken(str string) error {
return nil
}
... ...
package cache
import "gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
type LoginAccessCache struct {
}
func (ca LoginAccessCache) Save(param *domain.LoginAccess) (*domain.LoginAccess, error) {
return nil, nil
}
func (ca LoginAccessCache) Remove(param *domain.LoginAccess) (*domain.LoginAccess, error) {
return nil, nil
}
func (ca LoginAccessCache) FindOne(account string, platform string) (*domain.LoginAccess, error) {
return nil, nil
}
... ...
package cache
type LoginQrcodeCache struct {
}
... ...
package cache
import (
"fmt"
"github.com/go-redis/redis"
)
var clientRedis *redis.Client
const (
keyPrefix string = "gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway"
)
func Init() *redis.Client {
options := redis.Options{
Network: "tcp",
Addr: fmt.Sprintf("%s:%s", "127.0.0.1", "6379"),
Dialer: nil,
OnConnect: nil,
Password: "",
DB: 1,
MaxRetries: 0,
MinRetryBackoff: 0,
MaxRetryBackoff: 0,
DialTimeout: 0,
ReadTimeout: 0,
WriteTimeout: 0,
PoolSize: 0,
MinIdleConns: 0,
MaxConnAge: 0,
PoolTimeout: 0,
IdleTimeout: 0,
IdleCheckFrequency: 0,
TLSConfig: nil,
}
// 新建一个client
clientRedis = redis.NewClient(&options)
return clientRedis
}
... ...
package pg
import (
"fmt"
"github.com/go-pg/pg/v10"
"github.com/go-pg/pg/v10/orm"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/constant"
//_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/pg/models"
"github.com/linmadan/egglib-go/persistent/pg/hooks"
)
var DB *pg.DB
func init() {
DB = pg.Connect(&pg.Options{
User: constant.POSTGRESQL_USER,
Password: constant.POSTGRESQL_PASSWORD,
Database: constant.POSTGRESQL_DB_NAME,
Addr: fmt.Sprintf("%s:%s", constant.POSTGRESQL_HOST, constant.POSTGRESQL_PORT),
})
if !constant.DISABLE_SQL_GENERATE_PRINT {
DB.AddQueryHook(hooks.SqlGeneratePrintHook{})
}
m := []interface{}{}
if !constant.DISABLE_CREATE_TABLE {
for _, model := range m {
err := DB.Model(model).CreateTable(&orm.CreateTableOptions{
Temp: false,
IfNotExists: true,
FKConstraints: true,
})
if err != nil {
panic(err)
}
}
}
}
... ...
package models
import "time"
type LoginAccess struct {
tableName string `pg:"login_accesss,alias:login_access"`
LoginAccessId int64 `pg:",pk"`
// 账号
Account string
// 对应平台
Platform string
// 公司id
CompanyId int64
// 组织id
OrganizationId int64
// 登录凭证存储
AccessToken string
// 刷新登录凭证
RefreshToken string
// 登录凭证过期时间,时间戳精度秒
AccessExpired int64
// 刷新登录凭证过期时间,时间戳精度秒
RefreshExpired int64
// 创建时间
CreatedTime time.Time
// 更新时间
UpdatedTime time.Time
}
... ...
package transform
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/pg/models"
)
func TransformToLoginAccessDomainModelFromPgModels(loginAccessModel *models.LoginAccess) (*domain.LoginAccess, error) {
return &domain.LoginAccess{
Account: loginAccessModel.Account,
Platform: loginAccessModel.Platform,
CompanyId: loginAccessModel.CompanyId,
OrganizationId: loginAccessModel.OrganizationId,
AccessToken: loginAccessModel.AccessToken,
RefreshToken: loginAccessModel.RefreshToken,
AccessExpired: loginAccessModel.AccessExpired,
RefreshExpired: loginAccessModel.RefreshExpired,
CreatedTime: loginAccessModel.CreatedTime,
UpdatedTime: loginAccessModel.UpdatedTime,
}, 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/allied-creation/allied-creation-gateway/pkg/domain"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/pg/models"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/infrastructure/pg/transform"
)
type LoginAccessRepository struct {
transactionContext *pgTransaction.TransactionContext
}
func (repository *LoginAccessRepository) nextIdentify() (int64, error) {
IdWorker, err := snowflake.NewIdWorker(1)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
func (repository *LoginAccessRepository) Save(loginAccess *domain.LoginAccess) (*domain.LoginAccess, error) {
sqlBuildFields := []string{
"account",
"platform",
"company_id",
"organization_id",
"access_token",
"refresh_token",
"access_expired",
"refresh_expired",
"created_time",
"updated_time",
}
insertFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
insertPlaceHoldersSnippet := sqlbuilder.SqlPlaceHoldersSnippet(sqlBuildFields)
returningFieldsSnippet := sqlbuilder.SqlFieldsSnippet(sqlBuildFields)
updateFields := sqlbuilder.RemoveSqlFields(sqlBuildFields, "loginAccess_id")
updateFieldsSnippet := sqlbuilder.SqlUpdateFieldsSnippet(updateFields)
tx := repository.transactionContext.PgTx
if loginAccess.Identify() == nil {
loginAccessId, err := repository.nextIdentify()
if err != nil {
return loginAccess, err
} else {
loginAccess.LoginAccessId = loginAccessId
}
if _, err := tx.QueryOne(
pg.Scan(
&loginAccess.Account,
&loginAccess.Platform,
&loginAccess.CompanyId,
&loginAccess.OrganizationId,
&loginAccess.AccessToken,
&loginAccess.RefreshToken,
&loginAccess.AccessExpired,
&loginAccess.RefreshExpired,
&loginAccess.CreatedTime,
&loginAccess.UpdatedTime,
),
fmt.Sprintf("INSERT INTO login_accesss (%s) VALUES (%s) RETURNING %s", insertFieldsSnippet, insertPlaceHoldersSnippet, returningFieldsSnippet),
loginAccess.Account,
loginAccess.Platform,
loginAccess.CompanyId,
loginAccess.OrganizationId,
loginAccess.AccessToken,
loginAccess.RefreshToken,
loginAccess.AccessExpired,
loginAccess.RefreshExpired,
loginAccess.CreatedTime,
loginAccess.UpdatedTime,
); err != nil {
return loginAccess, err
}
} else {
if _, err := tx.QueryOne(
pg.Scan(
&loginAccess.Account,
&loginAccess.Platform,
&loginAccess.CompanyId,
&loginAccess.OrganizationId,
&loginAccess.AccessToken,
&loginAccess.RefreshToken,
&loginAccess.AccessExpired,
&loginAccess.RefreshExpired,
&loginAccess.CreatedTime,
&loginAccess.UpdatedTime,
),
fmt.Sprintf("UPDATE login_accesss SET %s WHERE login_access_id=? RETURNING %s", updateFieldsSnippet, returningFieldsSnippet),
loginAccess.Account,
loginAccess.Platform,
loginAccess.CompanyId,
loginAccess.OrganizationId,
loginAccess.AccessToken,
loginAccess.RefreshToken,
loginAccess.AccessExpired,
loginAccess.RefreshExpired,
loginAccess.CreatedTime,
loginAccess.UpdatedTime,
loginAccess.Identify(),
); err != nil {
return loginAccess, err
}
}
return loginAccess, nil
}
func (repository *LoginAccessRepository) Remove(loginAccess *domain.LoginAccess) (*domain.LoginAccess, error) {
tx := repository.transactionContext.PgTx
loginAccessModel := new(models.LoginAccess)
loginAccessModel.LoginAccessId = loginAccess.Identify().(int64)
if _, err := tx.Model(loginAccessModel).WherePK().Delete(); err != nil {
return loginAccess, err
}
return loginAccess, nil
}
func (repository *LoginAccessRepository) FindOne(queryOptions map[string]interface{}) (*domain.LoginAccess, error) {
tx := repository.transactionContext.PgTx
loginAccessModel := new(models.LoginAccess)
query := sqlbuilder.BuildQuery(tx.Model(loginAccessModel), queryOptions)
query.SetWhereByQueryOption("login_access.login_access_id = ?", "loginAccessId")
if err := query.First(); err != nil {
if err.Error() == "pg: no rows in result set" {
return nil, fmt.Errorf("没有此资源")
} else {
return nil, err
}
}
if loginAccessModel.LoginAccessId == 0 {
return nil, nil
} else {
return transform.TransformToLoginAccessDomainModelFromPgModels(loginAccessModel)
}
}
func (repository *LoginAccessRepository) Find(queryOptions map[string]interface{}) (int64, []*domain.LoginAccess, error) {
tx := repository.transactionContext.PgTx
var loginAccessModels []*models.LoginAccess
loginAccesss := make([]*domain.LoginAccess, 0)
query := sqlbuilder.BuildQuery(tx.Model(&loginAccessModels), queryOptions)
query.SetOffsetAndLimit(20)
query.SetOrderDirect("login_access_id", "DESC")
if count, err := query.SelectAndCount(); err != nil {
return 0, loginAccesss, err
} else {
for _, loginAccessModel := range loginAccessModels {
if loginAccess, err := transform.TransformToLoginAccessDomainModelFromPgModels(loginAccessModel); err != nil {
return 0, loginAccesss, err
} else {
loginAccesss = append(loginAccesss, loginAccess)
}
}
return int64(count), loginAccesss, nil
}
}
func NewLoginAccessRepository(transactionContext *pgTransaction.TransactionContext) (*LoginAccessRepository, error) {
if transactionContext == nil {
return nil, fmt.Errorf("transactionContext参数不能为nil")
} else {
return &LoginAccessRepository{
transactionContext: transactionContext,
}, nil
}
}
... ...
package snowflake
import (
"github.com/linmadan/egglib-go/utils/snowflake"
)
// 这里workId进行分组防止数组序列化时报错
func NextIdentify(workId int64) (int64, error) {
IdWorker, err := snowflake.NewIdWorker(workId)
if err != nil {
return 0, err
}
id, err := IdWorker.NextId()
return id, err
}
... ...
package log
import (
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/constant"
"github.com/linmadan/egglib-go/log"
"github.com/linmadan/egglib-go/log/logrus"
)
var Logger log.Logger
func init() {
Logger = logrus.NewLogrusLogger()
Logger.SetServiceName(constant.SERVICE_NAME)
Logger.SetLevel(constant.LOG_LEVEL)
}
... ...
package beego
import (
"os"
"strconv"
"github.com/beego/beego/v2/server/web"
"github.com/linmadan/egglib-go/web/beego/filters"
//_ "gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/routers"
. "gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/log"
)
func init() {
web.BConfig.AppName = "project"
web.BConfig.CopyRequestBody = true
web.BConfig.RunMode = "dev"
web.BConfig.Listen.HTTPPort = 8080
web.BConfig.Listen.EnableAdmin = false
web.BConfig.WebConfig.CommentRouterPath = "/pkg/port/beego"
if os.Getenv("RUN_MODE") != "" {
web.BConfig.RunMode = os.Getenv("RUN_MODE")
}
if os.Getenv("HTTP_PORT") != "" {
portStr := os.Getenv("HTTP_PORT")
if port, err := strconv.Atoi(portStr); err == nil {
web.BConfig.Listen.HTTPPort = port
}
}
web.InsertFilter("/*", web.BeforeExec, filters.AllowCors())
web.InsertFilter("/*", web.BeforeExec, filters.CreateRequstLogFilter(Logger))
web.InsertFilter("/*", web.AfterExec, filters.CreateResponseLogFilter(Logger), web.WithReturnOnOutput(false))
}
... ...
package controllers
import (
"github.com/linmadan/egglib-go/web/beego"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/loginAccess/query"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/application/loginAccess/service"
)
type LoginAccessController struct {
beego.BaseController
}
func (controller *LoginAccessController) LoginByAccount() {
loginAccessService := service.NewLoginAccessService(nil)
loginByAccountQuery := &query.LoginByAccountQuery{}
data, err := loginAccessService.LoginByAccount(loginByAccountQuery)
controller.Response(data, err)
}
func (controller *LoginAccessController) LoginBySmsCode() {
loginAccessService := service.NewLoginAccessService(nil)
loginBySmsCodeQuery := &query.LoginBySmsCodeQuery{}
data, err := loginAccessService.LoginBySmsCode(loginBySmsCodeQuery)
controller.Response(data, err)
}
func (controller *LoginAccessController) LoginByScanQrcode() {
loginAccessService := service.NewLoginAccessService(nil)
loginByScanQrcodeQuery := &query.LoginByScanQrcodeQuery{}
data, err := loginAccessService.LoginByScanQrcode(loginByScanQrcodeQuery)
controller.Response(data, err)
}
func (controller *LoginAccessController) GetQrcodeForLogin() {
loginAccessService := service.NewLoginAccessService(nil)
getQrcodeForLoginQuery := &query.GetQrcodeForLoginQuery{}
data, err := loginAccessService.GetQrcodeForLogin(getQrcodeForLoginQuery)
controller.Response(data, err)
}
func (controller *LoginAccessController) LoginInfoByAuthCode() {
loginAccessService := service.NewLoginAccessService(nil)
loginInfoByAuthCodeQuery := &query.LoginInfoByAuthCodeQuery{}
data, err := loginAccessService.LoginInfoByAuthCode(loginInfoByAuthCodeQuery)
controller.Response(data, err)
}
... ...
package routers
import (
"github.com/beego/beego/v2/server/web"
"gitlab.fjmaimaimai.com/allied-creation/allied-creation-gateway/pkg/port/beego/controllers"
)
func init() {
web.Router("/auth/by-account", &controllers.LoginAccessController{}, "Post:LoginByAccount")
web.Router("/auth/by-smscode", &controllers.LoginAccessController{}, "Post:LoginBySmsCode")
web.Router("/auth/by-qrcode", &controllers.LoginAccessController{}, "Get:LoginByScanQrcode")
web.Router("/auth/get-qrcode", &controllers.LoginAccessController{}, "Get:GetQrcodeForLogin")
web.Router("/auth/profile", &controllers.LoginAccessController{}, "Get:LoginInfoByAuthCode")
}
... ...
package service_gateway
... ...