feat: add register func for digimon

This commit is contained in:
王性驊 2025-10-02 17:52:22 +08:00
parent d435713e3b
commit 639879c089
12 changed files with 1445 additions and 17 deletions

1156
gateway.json Normal file

File diff suppressed because it is too large Load Diff

View File

@ -9,7 +9,7 @@ info (
consumes: "application/json" consumes: "application/json"
produces: "application/json" produces: "application/json"
schemes: "http,https" schemes: "http,https"
host: "127.0.0.1:8888" host: "localhost:8888"
) )
import ( import (

View File

@ -10,6 +10,7 @@ type (
CredentialsPayload { CredentialsPayload {
Password string `json:"password" validate:"required,min=8,max=128"` // 密碼 (後端應使用 bcrypt 進行雜湊) Password string `json:"password" validate:"required,min=8,max=128"` // 密碼 (後端應使用 bcrypt 進行雜湊)
PasswordConfirm string `json:"password_confirm" validate:"eqfield=Password"` // 確認密碼 PasswordConfirm string `json:"password_confirm" validate:"eqfield=Password"` // 確認密碼
AccountType string `json:"accountType" validate:"required,oneof=email phone any"`
} }
// PlatformPayload 第三方平台註冊的資料 // PlatformPayload 第三方平台註冊的資料

4
internal/domain/const.go Normal file
View File

@ -0,0 +1,4 @@
package domain
const SuccessCode = 10200
const SuccessMessage = "success"

View File

@ -1,11 +1,13 @@
package auth package auth
import ( import (
"net/http" "backend/internal/domain"
"backend/internal/logic/auth" "backend/internal/logic/auth"
"backend/internal/svc" "backend/internal/svc"
"backend/internal/types" "backend/internal/types"
"code.30cm.net/digimon/library-go/errs"
ers "code.30cm.net/digimon/library-go/errs"
"net/http"
"github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/httpx"
) )
@ -15,16 +17,40 @@ func LoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
var req types.LoginReq var req types.LoginReq
if err := httpx.Parse(r, &req); err != nil { if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err) e := errs.InvalidFormat(err.Error())
httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.RespOK{
Code: int(e.FullCode()),
Msg: err.Error(),
})
return return
} }
//if err := svcCtx.Validate.ValidateAll(req); err != nil {
// e := errs.InvalidFormat(err.Error())
// httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.RespOK{
// Code: int(e.FullCode()),
// Msg: err.Error(),
// })
//
// return
//}
l := auth.NewLoginLogic(r.Context(), svcCtx) l := auth.NewLoginLogic(r.Context(), svcCtx)
resp, err := l.Login(&req) resp, err := l.Login(&req)
if err != nil { if err != nil {
httpx.ErrorCtx(r.Context(), w, err) e := ers.FromError(err)
httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.ErrorResp{
Code: int(e.FullCode()),
Msg: e.Error(),
Error: e,
})
} else { } else {
httpx.OkJsonCtx(r.Context(), w, resp) httpx.WriteJsonCtx(r.Context(), w, http.StatusOK, types.RespOK{
Code: domain.SuccessCode,
Msg: domain.SuccessMessage,
Data: resp,
})
} }
} }
} }

View File

@ -1,6 +1,8 @@
package auth package auth
import ( import (
"backend/internal/domain"
"code.30cm.net/digimon/library-go/errs"
"net/http" "net/http"
"backend/internal/logic/auth" "backend/internal/logic/auth"
@ -15,16 +17,38 @@ func RegisterHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
var req types.LoginReq var req types.LoginReq
if err := httpx.Parse(r, &req); err != nil { if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err) e := errs.InvalidFormat(err.Error())
httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.RespOK{
Code: int(e.FullCode()),
Msg: err.Error(),
})
return return
} }
//if err := svcCtx.Validate.ValidateAll(req); err != nil {
// e := errs.InvalidFormat(err.Error())
// httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.RespOK{
// Code: int(e.FullCode()),
// Msg: err.Error(),
// })
//
// return
//}
l := auth.NewRegisterLogic(r.Context(), svcCtx) l := auth.NewRegisterLogic(r.Context(), svcCtx)
resp, err := l.Register(&req) resp, err := l.Register(&req)
if err != nil { if err != nil {
httpx.ErrorCtx(r.Context(), w, err) e := errs.FromError(err)
httpx.WriteJsonCtx(r.Context(), w, e.HTTPStatus(), types.ErrorResp{
Code: int(e.FullCode()),
Msg: e.Error(),
Error: e,
})
} else { } else {
httpx.OkJsonCtx(r.Context(), w, resp) httpx.WriteJsonCtx(r.Context(), w, http.StatusOK, types.RespOK{
Code: domain.SuccessCode,
Msg: domain.SuccessMessage,
Data: resp,
})
} }
} }
} }

View File

@ -9,7 +9,7 @@ import (
"github.com/zeromicro/go-zero/rest/httpx" "github.com/zeromicro/go-zero/rest/httpx"
) )
// 系統健康檢查 // PingHandler 系統健康檢查
func PingHandler(svcCtx *svc.ServiceContext) http.HandlerFunc { func PingHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
l := ping.NewPingLogic(r.Context(), svcCtx) l := ping.NewPingLogic(r.Context(), svcCtx)

View File

@ -1,10 +1,15 @@
package auth package auth
import ( import (
"context"
"backend/internal/svc" "backend/internal/svc"
"backend/internal/types" "backend/internal/types"
mb "backend/pkg/member/domain/member"
member "backend/pkg/member/domain/usecase"
"code.30cm.net/digimon/library-go/errs"
"code.30cm.net/digimon/library-go/errs/code"
"context"
"google.golang.org/protobuf/proto"
"time"
"github.com/zeromicro/go-zero/core/logx" "github.com/zeromicro/go-zero/core/logx"
) )
@ -15,6 +20,12 @@ type RegisterLogic struct {
svcCtx *svc.ServiceContext svcCtx *svc.ServiceContext
} }
var PrepareFunc map[string]func(ctx context.Context, req *types.LoginReq, svc *svc.ServiceContext) (buildData, error) = map[string]func(ctx context.Context, req *types.LoginReq, svc *svc.ServiceContext) (buildData, error){
mb.Digimon.ToString(): buildCredentialsData,
mb.Google.ToString(): buildGoogleData,
mb.Line.ToString(): buildLineData,
}
// 註冊新帳號 // 註冊新帳號
func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic { func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RegisterLogic {
return &RegisterLogic{ return &RegisterLogic{
@ -25,7 +36,186 @@ func NewRegisterLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Register
} }
func (l *RegisterLogic) Register(req *types.LoginReq) (resp *types.LoginResp, err error) { func (l *RegisterLogic) Register(req *types.LoginReq) (resp *types.LoginResp, err error) {
// todo: add your logic here and delete this line // Step 1: 根據平台構建相關數據
var bd buildData
return switch req.AuthMethod {
case "credentials":
fn, ok := PrepareFunc[mb.Digimon.ToString()]
if !ok {
return nil, errs.InvalidRangeWithScope(code.CloudEPMember, 0, "failed to get correct credentials method")
}
bd, err = fn(l.ctx, req, l.svcCtx)
if err != nil {
return nil, err
}
case "platform":
fn, ok := PrepareFunc[req.Platform.Provider]
if !ok {
return nil, errs.InvalidRangeWithScope(code.CloudEPMember, 0, "failed to get correct credentials method")
}
bd, err = fn(l.ctx, req, l.svcCtx)
if err != nil {
return nil, err
}
default:
return nil, errs.InvalidFormatWithScope(code.CloudEPMember, "failed to get correct auth method")
}
// Step 2: 建立帳號
if err := l.svcCtx.AccountUC.CreateUserAccount(l.ctx, bd.CreateAccountReq); err != nil {
return nil, err
}
// Step 3: 綁定帳號並獲取 UID
account, err := l.svcCtx.AccountUC.BindAccount(l.ctx, bd.BindingUserReq)
if err != nil {
return nil, err
}
bd.CreateUserInfoRequest.UID = account.UID
// Step 4: 更新使用者資訊
if err := l.svcCtx.AccountUC.BindUserInfo(l.ctx, bd.CreateUserInfoRequest); err != nil {
return nil, err
}
// Step 5: 生成 Token
req.LoginID = bd.CreateAccountReq.LoginID
token, err := l.generateToken(req, account.UID)
if err != nil {
return nil, err
}
return &types.LoginResp{
UID: account.UID,
AccessToken: token.AccessToken,
RefreshToken: token.RefreshToken,
TokenType: token.TokenType,
}, nil
}
type buildData struct {
CreateAccountReq member.CreateLoginUserRequest
BindingUserReq member.BindingUser
CreateUserInfoRequest member.CreateUserInfoRequest
}
func buildCredentialsData(_ context.Context, req *types.LoginReq, _ *svc.ServiceContext) (buildData, error) {
return buildData{
CreateAccountReq: member.CreateLoginUserRequest{
LoginID: req.LoginID,
Token: req.Credentials.Password,
Platform: mb.Digimon,
},
BindingUserReq: member.BindingUser{
LoginID: req.LoginID,
Type: mb.GetAccountTypeByCode(req.Credentials.AccountType),
},
CreateUserInfoRequest: member.CreateUserInfoRequest{
AlarmCategory: mb.AlarmNoAlert,
UserStatus: mb.AccountStatusUnverified,
PreferredLanguage: mb.LangTW.ToString(),
Currency: mb.CurrencyTWD.ToString(),
},
}, nil
}
func buildGoogleData(ctx context.Context, req *types.LoginReq, svc *svc.ServiceContext) (buildData, error) {
googleToken, err := svc.AccountUC.VerifyGoogleAuthResult(ctx, member.VerifyAuthResultRequest{
Account: req.LoginID,
Token: req.Platform.Token,
})
if err != nil {
return buildData{}, err
}
return buildData{
CreateAccountReq: member.CreateLoginUserRequest{
LoginID: googleToken.Email,
Token: "",
Platform: mb.Google,
},
BindingUserReq: member.BindingUser{
LoginID: req.LoginID,
Type: mb.AccountTypeNone,
},
CreateUserInfoRequest: member.CreateUserInfoRequest{
AvatarURL: proto.String(googleToken.Picture),
FullName: proto.String(googleToken.Name),
Nickname: proto.String(googleToken.Name),
Email: proto.String(googleToken.Email),
AlarmCategory: mb.AlarmNoAlert,
UserStatus: mb.AccountStatusUnverified,
PreferredLanguage: mb.LangTW.ToString(),
Currency: mb.CurrencyTWD.ToString(),
},
}, nil
}
func buildLineData(ctx context.Context, req *types.LoginReq, svc *svc.ServiceContext) (buildData, error) {
lineAccessToken, err := svc.AccountUC.LineCodeToAccessToken(ctx, req.LoginID)
if err != nil {
return buildData{}, err
}
userInfo, err := svc.AccountUC.LineGetProfileByAccessToken(ctx, lineAccessToken.AccessToken)
if err != nil {
return buildData{}, err
}
return buildData{
CreateAccountReq: member.CreateLoginUserRequest{
LoginID: userInfo.UserID,
Token: "",
Platform: mb.Line,
},
BindingUserReq: member.BindingUser{
LoginID: userInfo.UserID,
Type: mb.AccountTypeNone,
},
CreateUserInfoRequest: member.CreateUserInfoRequest{
AvatarURL: proto.String(userInfo.PictureURL),
FullName: proto.String(userInfo.DisplayName),
Nickname: proto.String(userInfo.DisplayName),
AlarmCategory: mb.AlarmNoAlert,
UserStatus: mb.AccountStatusUnverified,
PreferredLanguage: mb.LangTW.ToString(),
Currency: mb.CurrencyTWD.ToString(),
},
}, nil
}
type MockToken struct {
AccessToken string `json:"access_token"` // 訪問令牌
TokenType string `json:"token_type"` // 令牌類型
ExpiresIn int64 `json:"expires_in"` // 過期時間(秒)
RefreshToken string `json:"refresh_token"` // 刷新令牌
}
// 生成 Token
func (l *RegisterLogic) generateToken(req *types.LoginReq, uid string) (MockToken, error) {
//credentials := tokenModule.ClientCredentials
//role := "user"
//if isTruHeartEmail(req.Account) {
// role = "admin"
//}
//
//return l.svcCtx.TokenUseCase.NewToken(l.ctx, tokenModule.AuthorizationReq{
// GrantType: credentials.ToString(),
// DeviceID: req.DeviceID,
// Scope: domain.DefaultScope,
// IsRefreshToken: true,
// Expires: time.Now().UTC().Add(l.svcCtx.Config.Token.Expired).Unix(),
// Data: map[string]string{
// "uid": uid,
// "role": role,
// "account": req.Account,
// },
// Role: role,
//})
return MockToken{
AccessToken: "gg88g88",
TokenType: "Bearer",
ExpiresIn: time.Now().UTC().Add(100000000000).Unix(),
RefreshToken: "gg88g88",
}, nil
} }

View File

@ -13,6 +13,7 @@ type BaseReq struct {
type CredentialsPayload struct { type CredentialsPayload struct {
Password string `json:"password" validate:"required,min=8,max=128"` // 密碼 (後端應使用 bcrypt 進行雜湊) Password string `json:"password" validate:"required,min=8,max=128"` // 密碼 (後端應使用 bcrypt 進行雜湊)
PasswordConfirm string `json:"password_confirm" validate:"eqfield=Password"` // 確認密碼 PasswordConfirm string `json:"password_confirm" validate:"eqfield=Password"` // 確認密碼
AccountType string `json:"accountType" validate:"required,oneof=email phone any"`
} }
type ErrorResp struct { type ErrorResp struct {

View File

@ -0,0 +1,21 @@
package member
type Lang string
func (l Lang) ToString() string {
return string(l)
}
type Currency string
func (c Currency) ToString() string {
return string(c)
}
const (
LangTW Lang = "zh-tw"
)
const (
CurrencyTWD Currency = "TWD"
)

View File

@ -12,7 +12,7 @@ const (
) )
const ( const (
DigimonString = "platform" DigimonString = "credentials"
GoogleString = "google" GoogleString = "google"
LineString = "line" LineString = "line"
AppleString = "apple" AppleString = "apple"

View File

@ -4,6 +4,7 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"go.mongodb.org/mongo-driver/v2/mongo"
"math" "math"
"backend/pkg/member/domain" "backend/pkg/member/domain"
@ -82,7 +83,11 @@ func (use *MemberUseCase) processPasswordForPlatform(platform member.Platform, p
// insertAccount inserts the account into the database // insertAccount inserts the account into the database
func (use *MemberUseCase) insertAccount(ctx context.Context, account *entity.Account, req usecase.CreateLoginUserRequest) error { func (use *MemberUseCase) insertAccount(ctx context.Context, account *entity.Account, req usecase.CreateLoginUserRequest) error {
err := use.Account.Insert(ctx, account) err := use.Account.Insert(ctx, account)
if err != nil { if err != nil {
if mongo.IsDuplicateKeyError(err) {
return errs.DBDuplicate("account duplicate").Wrap(err)
}
return errs.DatabaseErrorWithScopeL( return errs.DatabaseErrorWithScopeL(
code.CloudEPMember, code.CloudEPMember,
domain.InsertAccountErrorCode, domain.InsertAccountErrorCode,
@ -92,7 +97,7 @@ func (use *MemberUseCase) insertAccount(ctx context.Context, account *entity.Acc
{Key: "func", Value: "Account.Insert"}, {Key: "func", Value: "Account.Insert"},
{Key: "err", Value: err.Error()}, {Key: "err", Value: err.Error()},
}, },
"account duplicate").Wrap(err) "failed to insert to database").Wrap(err)
} }
return nil return nil