添加对应 php注册登录的token 验证逻辑

This commit is contained in:
474420502 2024-04-15 17:01:42 +08:00
parent de7cd23deb
commit 62db070f61
6 changed files with 109 additions and 177 deletions

View File

@ -34,6 +34,7 @@ func (m *KillaraCustomerTokenModel) InsertToken(data *KillaraCustomerToken) erro
return m.db.Model(&KillaraCustomerToken{}).Transaction(func(tx *gorm.DB) error {
// 查找是否存在相同客户ID、平台和Token的记录
var existingToken KillaraCustomerToken
err := tx.Where("customer_id = ? AND platform = ? AND token = ?", data.CustomerId, data.Platform, *data.Token).First(&existingToken).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
@ -44,7 +45,7 @@ func (m *KillaraCustomerTokenModel) InsertToken(data *KillaraCustomerToken) erro
if !errors.Is(err, gorm.ErrRecordNotFound) {
// 存在记录,先删除
err = tx.Delete(&existingToken).Error
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
if err != nil {
tx.Rollback() // 删除错误,回滚事务
return err
}
@ -57,7 +58,7 @@ func (m *KillaraCustomerTokenModel) InsertToken(data *KillaraCustomerToken) erro
return err
}
return tx.Commit().Error // 提交事务
return err // 提交事务
})
}
@ -113,12 +114,12 @@ func (m *KillaraCustomerTokenModel) GetToken(token string) (*KillaraCustomerToke
// return nil, nil
// }
func (m *KillaraCustomerTokenModel) CheckToken(token string) (*KillaraCustomerToken, error) {
func (m *KillaraCustomerTokenModel) CheckToken(tokenstr string) (*KillaraCustomerToken, error) {
var resultToken *KillaraCustomerToken
err := m.db.Model(&KillaraCustomerToken{}).Transaction(func(tx *gorm.DB) error {
// 查找 Token 记录
var token KillaraCustomerToken
err := tx.Where("token = ?", token).First(&token).Error
err := tx.Where("token = ?", tokenstr).First(&token).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil
@ -138,7 +139,7 @@ func (m *KillaraCustomerTokenModel) CheckToken(token string) (*KillaraCustomerTo
}
resultToken = &token
return tx.Commit().Error // 提交事务
return err // 提交事务
})
if err != nil {
@ -150,7 +151,7 @@ func (m *KillaraCustomerTokenModel) CheckToken(token string) (*KillaraCustomerTo
func (m *KillaraCustomerTokenModel) ClearDuplicateToken(customerID uint64, currentToken string, platform int) error {
return m.db.Model(&KillaraCustomerToken{}).Transaction(func(tx *gorm.DB) error {
var tokens []KillaraCustomerToken
var tokens []*KillaraCustomerToken
err := tx.Where("customer_id = ? AND platform = ?", customerID, platform).Find(&tokens).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@ -164,7 +165,7 @@ func (m *KillaraCustomerTokenModel) ClearDuplicateToken(customerID uint64, curre
for _, token := range tokens {
if *token.Token != currentToken {
// err := tx.Delete(token).Error todo: 不太明白php为什么不删除token, 难道用来链路跟踪? 但是客户端id也被更新了, 没有存在的意义了
err := tx.Where("token = ?", token).Update("customer_id", 0).Error
err := tx.Where("token = ?", *token.Token).Update("customer_id", 0).Error
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return fmt.Errorf("tokens 查询出来, 自身都不存在, 疑似出了什么错误2")

View File

@ -97,7 +97,7 @@ func BaseGetToken(ctx *ActionContext[BaseGetTokenParam]) (resp *basic.Response)
}
err = modelToken.InsertToken(tokenItem)
log.Println(err)
log.Println(*tokenItem.Token)
if err != nil {
return resp.ErrorErr(1, err)
}
@ -342,7 +342,6 @@ func AccountLoginWithEmailPassword(ctx *ActionContext[AccountLoginWithEmailPassw
return resp.ErrorErr(1, err)
}
log.Println(ctx.Localize(translator.AccountNotRegistered))
if customer == nil {
return resp.ErrorTrCode(ctx, translator.AccountNotRegistered)
}

View File

@ -5,6 +5,8 @@ import (
"github.com/iapologizewhenimwrong/Vestmore_GO/utils/log"
)
var respLog = log.New(0)
// 全局返回的结构体
type Response struct {
Data interface{} `json:"data"`
@ -25,7 +27,7 @@ func (resp *Response) Error(errcode *ErrorCode, Data ...interface{}) *Response {
resp.ErrorText = errcode.Message
resp.IsSuccess = false
resp.setData(Data)
log.Error(resp.ErrorText)
respLog.Error(resp.ErrorText)
return resp
}
@ -38,7 +40,7 @@ func (resp *Response) ErrorErr(Code int, err error, Data ...interface{}) *Respon
resp.IsSuccess = false
resp.setData(Data)
log.Error(resp.ErrorText)
respLog.Error(resp.ErrorText)
return resp
}
@ -50,7 +52,7 @@ func (resp *Response) ErrorMsg(Code int, Message string, Data ...interface{}) *R
resp.ErrorText = Message
resp.IsSuccess = false
resp.setData(Data)
log.Error(resp.ErrorText)
respLog.Error(resp.ErrorText)
return resp
}

View File

@ -4,7 +4,6 @@ import (
"bytes"
"encoding/json"
"fmt"
"log"
"runtime"
"strings"
"sync"
@ -14,93 +13,50 @@ import (
)
type levelSkip struct {
SkipLogrus int
SkipBasic int
Skip int
Once sync.Once
}
// JSONFormatter formats logs into parsable json
type JSONFormatter struct {
skip []*levelSkip
once sync.Once
diffSkip int
skip []*levelSkip
once sync.Once
}
// Format renders a single log entry
func (h *JSONFormatter) Format(e *logrus.Entry) ([]byte, error) {
skipOnce := h.skip[int(e.Level)]
if skipOnce.SkipLogrus == 0 {
var skipLogrus OpenClose
for i := 4; i < 50; i++ {
skipOnce.Once.Do(func() {
for i := 4; i < 100; i++ {
// log.Println(i)
if pc, file, line, ok := runtime.Caller(i); ok {
if pc, _, _, ok := runtime.Caller(i); ok {
funcStruct := runtime.FuncForPC(pc)
log.Println(funcStruct.Name(), file, line)
skipLogrus.OpenFunc(func() bool {
return strings.Contains(funcStruct.Name(), "github.com/sirupsen/logrus.")
}, func() {
// skip = i
skipOnce.SkipLogrus = i
i = 10000
})
// log.Println(funcStruct.Name(), file, line)
if !strings.Contains(funcStruct.Name(), "github.com/sirupsen/logrus.") {
skipOnce.Skip++
if skipOnce.Skip >= 2 {
skipOnce.Skip = i - 3
break
}
}
} else {
break
}
}
}
if skipOnce.SkipBasic == 0 {
var skipBasic OpenClose
for i := 4; i < 50; i++ {
// log.Println(i)
if pc, file, line, ok := runtime.Caller(i); ok {
funcStruct := runtime.FuncForPC(pc)
log.Println(funcStruct.Name(), file, line)
skipBasic.OpenFunc(func() bool {
return strings.Contains(funcStruct.Name(), "basic.(*Response).")
}, func() {
skipOnce.SkipBasic = i + 1
})
} else {
break
}
}
}
})
var fileinfo string
if pc, _, _, ok := runtime.Caller(skipOnce.SkipBasic - 1); ok {
funcStruct := runtime.FuncForPC(pc)
log.Println(funcStruct.Name())
if strings.Contains(funcStruct.Name(), "basic.(*Response).") {
if _, file, line, ok := runtime.Caller(skipOnce.SkipBasic); ok {
if e.Level == logrus.InfoLevel {
fileinfo = fmt.Sprintf("%s:%d", file, line)
} else {
ps := strings.Split(file, "/")
// ps = ps[len(ps)-4:]
fileinfo = fmt.Sprintf("%s:%d", strings.Join(ps, "/"), line)
}
}
if _, file, line, ok := runtime.Caller(skipOnce.Skip + h.diffSkip); ok {
if e.Level == logrus.InfoLevel {
fileinfo = fmt.Sprintf("%s:%d", file, line)
} else {
ps := strings.Split(file, "/")
fileinfo = fmt.Sprintf("%s:%d", strings.Join(ps, "/"), line)
}
}
if fileinfo != "" {
if _, file, line, ok := runtime.Caller(skipOnce.SkipLogrus); ok {
if e.Level == logrus.InfoLevel {
fileinfo = fmt.Sprintf("%s:%d", file, line)
} else {
ps := strings.Split(file, "/")
// ps = ps[len(ps)-4:]
fileinfo = fmt.Sprintf("%s:%d", strings.Join(ps, "/"), line)
}
}
}
var Data map[string]any = make(map[string]any, 4)

View File

@ -12,31 +12,38 @@ import (
"github.com/sirupsen/logrus"
)
var l *logrus.Logger
var dlog *logrus.Logger
func init() {
l = logrus.New()
dlog = New(0)
}
func New(skip int) *logrus.Logger {
myl := logrus.New()
// 配置 Logstash 作为输出
l.AddHook(NewUTCTimeHook())
myl.AddHook(NewUTCTimeHook())
jf := &JSONFormatter{
skip: make([]*levelSkip, len(logrus.AllLevels)),
skip: make([]*levelSkip, len(logrus.AllLevels)),
diffSkip: skip,
}
for i := range jf.skip {
jf.skip[i] = &levelSkip{}
}
l.Formatter = jf
myl.Formatter = jf
myl.SetReportCaller(true)
// l.AddHook(&SkipHook{})
l.SetReportCaller(true)
if dlog != nil {
myl.SetOutput(dlog.Out)
}
return myl
}
type SkipHook struct {
autoSkip int
Formatter func(*logrus.Hook, *logrus.Entry) error
once sync.Once
}
@ -45,61 +52,28 @@ func (h *SkipHook) Levels() []logrus.Level {
return logrus.AllLevels
}
// OpenClose 开闭空间
type OpenClose struct {
Open bool
Close bool
Skip int
}
func (oc *OpenClose) OpenFunc(opendo func() bool, closedo func()) {
if oc.Open && oc.Close {
return
}
if opendo() {
if !oc.Open {
oc.Open = true
return
}
} else {
if oc.Open && !oc.Close {
oc.Close = true
closedo()
}
}
}
func (h *SkipHook) Fire(e *logrus.Entry) error {
var skipLogrus, skipBasic OpenClose
var skip int
for i := 4; i < 25; i++ {
log.Println(i)
if pc, file, line, ok := runtime.Caller(i); ok {
funcStruct := runtime.FuncForPC(pc)
log.Println(funcStruct.Name(), file, line)
skipLogrus.OpenFunc(func() bool {
return strings.Contains(funcStruct.Name(), "github.com/sirupsen/logrus.")
}, func() {
skip = i + 1
})
skipBasic.OpenFunc(func() bool {
return strings.Contains(funcStruct.Name(), "basic.(*Response).")
}, func() {
skip = i
i = 100
})
h.once.Do(func() {
for i := 4; i < 100; i++ {
log.Println(i)
if pc, file, line, ok := runtime.Caller(i); ok {
funcStruct := runtime.FuncForPC(pc)
log.Println(funcStruct.Name(), file, line)
if !strings.Contains(funcStruct.Name(), "github.com/sirupsen/logrus.") {
h.autoSkip++
if h.autoSkip >= 2 {
h.autoSkip = i - 3
break
}
}
} else {
break
}
}
})
}
if _, file, line, ok := runtime.Caller(skip); ok {
if _, file, line, ok := runtime.Caller(h.autoSkip); ok {
// funcStruct := runtime.FuncForPC(pc)
// log.Println(file, line, funcStruct.Name())
// funcName := funcStruct.Name()
@ -131,154 +105,154 @@ func (hook *UTCTimeHook) Fire(entry *logrus.Entry) error {
// this new returned entry.
// If you want multiple fields, use `WithFields`.
func WithField(key string, value interface{}) *logrus.Entry {
return l.WithField(key, value)
return dlog.WithField(key, value)
}
// Adds a struct of fields to the log entry. All it does is call `WithField` for
// each `Field`.
func WithFields(fields logrus.Fields) *logrus.Entry {
return l.WithFields(fields)
return dlog.WithFields(fields)
}
// Add an error as single field to the log entry. All it does is call
// `WithError` for the given `error`.
func WithError(err error) *logrus.Entry {
return l.WithError(err)
return dlog.WithError(err)
}
// Add a context to the log entry.
func WithContext(ctx context.Context) *logrus.Entry {
return l.WithContext(ctx)
return dlog.WithContext(ctx)
}
// Overrides the time of the log entry.
func WithTime(t time.Time) *logrus.Entry {
return l.WithTime(t)
return dlog.WithTime(t)
}
func Logf(level logrus.Level, format string, args ...interface{}) {
l.Logf(level, format, args...)
dlog.Logf(level, format, args...)
}
func Tracef(format string, args ...interface{}) {
l.Tracef(format, args...)
dlog.Tracef(format, args...)
}
func Debugf(format string, args ...interface{}) {
l.Debugf(format, args...)
dlog.Debugf(format, args...)
}
func Infof(format string, args ...interface{}) {
l.Infof(format, args...)
dlog.Infof(format, args...)
}
func Printf(format string, args ...interface{}) {
l.Printf(format, args...)
dlog.Printf(format, args...)
}
func Warnf(format string, args ...interface{}) {
l.Warnf(format, args...)
dlog.Warnf(format, args...)
}
func Warningf(format string, args ...interface{}) {
l.Warningf(format, args...)
dlog.Warningf(format, args...)
}
func Errorf(format string, args ...interface{}) {
l.Errorf(format, args...)
dlog.Errorf(format, args...)
}
func Fatalf(format string, args ...interface{}) {
l.Fatalf(format, args...)
dlog.Fatalf(format, args...)
}
func Panicf(format string, args ...interface{}) {
l.Panicf(format, args...)
dlog.Panicf(format, args...)
}
func Log(level logrus.Level, args ...interface{}) {
l.Log(level, args...)
dlog.Log(level, args...)
}
func Trace(args ...interface{}) {
l.Trace(args...)
dlog.Trace(args...)
}
func Debug(args ...interface{}) {
l.Debug(args...)
dlog.Debug(args...)
}
func Info(args ...interface{}) {
l.Info(args...)
dlog.Info(args...)
}
func Print(args ...interface{}) {
l.Print(args...)
dlog.Print(args...)
}
func Warn(args ...interface{}) {
l.Warn(args...)
dlog.Warn(args...)
}
func Warning(args ...interface{}) {
l.Warning(args...)
dlog.Warning(args...)
}
func Error(args ...interface{}) {
l.Error(args...)
dlog.Error(args...)
}
func Fatal(args ...interface{}) {
l.Fatal(args...)
dlog.Fatal(args...)
}
func Panic(args ...interface{}) {
l.Panic(args...)
dlog.Panic(args...)
}
func Logln(level logrus.Level, args ...interface{}) {
l.Logln(level, args...)
dlog.Logln(level, args...)
}
func Traceln(args ...interface{}) {
l.Traceln(args...)
dlog.Traceln(args...)
}
func Debugln(args ...interface{}) {
l.Debugln(args...)
dlog.Debugln(args...)
}
func Infoln(args ...interface{}) {
l.Infoln(args...)
dlog.Infoln(args...)
}
func Println(args ...interface{}) {
l.Println(args...)
dlog.Println(args...)
}
func Warnln(args ...interface{}) {
l.Warnln(args...)
dlog.Warnln(args...)
}
func Warningln(args ...interface{}) {
l.Warningln(args...)
dlog.Warningln(args...)
}
func Errorln(args ...interface{}) {
l.Errorln(args...)
dlog.Errorln(args...)
}
func Fatalln(args ...interface{}) {
l.Fatalln(args...)
dlog.Fatalln(args...)
}
func Panicln(args ...interface{}) {
l.Panicln(args...)
dlog.Panicln(args...)
}
func Exit(code int) {
l.Exit(code)
dlog.Exit(code)
}

View File

@ -14,7 +14,7 @@ func DebuglnTrackTime(do func(), fargs ...interface{}) {
var out []interface{}
out = append(out, t)
out = append(out, fargs...)
l.Debugln(out...)
dlog.Debugln(out...)
}
func InfolnTrackTime(do func(), fargs ...interface{}) {
@ -24,5 +24,5 @@ func InfolnTrackTime(do func(), fargs ...interface{}) {
var out []interface{}
out = append(out, t)
out = append(out, fargs...)
l.Infoln(out...)
dlog.Infoln(out...)
}