generated from pkg/go-template
82 lines
1.5 KiB
Go
82 lines
1.5 KiB
Go
|
package service
|
||
|
|
||
|
import (
|
||
|
"context"
|
||
|
"fmt"
|
||
|
"git.icechen.cn/monorepo/backend/app/brahma/api/murder/internal/model"
|
||
|
"git.icechen.cn/monorepo/backend/pkg/config"
|
||
|
"git.icechen.cn/monorepo/backend/pkg/wx"
|
||
|
ctxLogger "github.com/luizsuper/ctxLoggers"
|
||
|
"math/rand"
|
||
|
"strconv"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
var appMap = make(map[string]Applet)
|
||
|
|
||
|
func init() {
|
||
|
a := new(AppletConfig)
|
||
|
err := config.GetConfig(a)
|
||
|
if err != nil {
|
||
|
ctxLogger.Error(nil, err.Error())
|
||
|
panic(err)
|
||
|
}
|
||
|
for _, v := range a.Apps {
|
||
|
appMap[v.Type] = v
|
||
|
}
|
||
|
}
|
||
|
|
||
|
type AppletConfig struct {
|
||
|
Apps []Applet `json:"applet"`
|
||
|
}
|
||
|
|
||
|
type Applet struct {
|
||
|
Type string `json:"type"`
|
||
|
Appid string `json:"appid"`
|
||
|
Secret string `json:"secret"`
|
||
|
}
|
||
|
|
||
|
func Login(ctx context.Context, code, appType string) error {
|
||
|
session, err := wx.Code2Session(appMap[appType].Appid, appMap[appType].Secret, code)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
i, err := model.GetUserInfo(ctx, appType, session.OpenId)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if i == nil {
|
||
|
i = new(model.User)
|
||
|
i.Openid = session.OpenId
|
||
|
err = Register(ctx, i, true)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
}
|
||
|
|
||
|
err = generateToken(ctx, i)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|
||
|
|
||
|
func Register(ctx context.Context, user *model.User, isNew bool) error {
|
||
|
if isNew {
|
||
|
rand.Seed(time.Now().UnixNano())
|
||
|
intn := rand.Intn(2 ^ 1024)
|
||
|
itoa := strconv.Itoa(intn)
|
||
|
user.NickName = fmt.Sprintf("游客%v", itoa)
|
||
|
}
|
||
|
|
||
|
err := model.NewUser(ctx, user)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
return nil
|
||
|
}
|