backend/app/brahma/api/murder/internal/service/user.go

80 lines
1.4 KiB
Go
Raw Normal View History

2022-01-25 17:03:14 +08:00
package service
import (
"context"
"fmt"
"git.icechen.cn/monorepo/backend/app/brahma/api/murder/internal/model"
"git.icechen.cn/monorepo/backend/pkg/wx"
"math/rand"
"strconv"
"time"
)
var appMap = make(map[string]Applet)
func init() {
2022-01-27 18:30:14 +08:00
//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
//}
2022-01-25 17:03:14 +08:00
}
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
}