feat: complete email binding and pending oauth verification flows
This commit is contained in:
@@ -16,6 +16,7 @@ import (
|
||||
"github.com/Wei-Shaw/sub2api/ent/predicate"
|
||||
dbuser "github.com/Wei-Shaw/sub2api/ent/user"
|
||||
infraerrors "github.com/Wei-Shaw/sub2api/internal/pkg/errors"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/ip"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/oauth"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/response"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
@@ -27,7 +28,7 @@ import (
|
||||
const (
|
||||
oauthPendingBrowserCookiePath = "/api/v1/auth/oauth"
|
||||
oauthPendingBrowserCookieName = "oauth_pending_browser_session"
|
||||
oauthPendingSessionCookiePath = "/api/v1/auth/oauth/pending"
|
||||
oauthPendingSessionCookiePath = "/api/v1/auth/oauth"
|
||||
oauthPendingSessionCookieName = "oauth_pending_session"
|
||||
oauthPendingCookieMaxAgeSec = 10 * 60
|
||||
|
||||
@@ -66,6 +67,13 @@ type createPendingOAuthAccountRequest struct {
|
||||
AdoptAvatar *bool `json:"adopt_avatar,omitempty"`
|
||||
}
|
||||
|
||||
type sendPendingOAuthVerifyCodeRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
TurnstileToken string `json:"turnstile_token,omitempty"`
|
||||
PendingAuthToken string `json:"pending_auth_token,omitempty"`
|
||||
PendingOAuthToken string `json:"pending_oauth_token,omitempty"`
|
||||
}
|
||||
|
||||
func (r bindPendingOAuthLoginRequest) adoptionDecision() oauthAdoptionDecisionRequest {
|
||||
return oauthAdoptionDecisionRequest{
|
||||
AdoptDisplayName: r.AdoptDisplayName,
|
||||
@@ -448,6 +456,43 @@ func (h *AuthHandler) CreatePendingOAuthAccount(c *gin.Context) {
|
||||
h.createPendingOAuthAccount(c, "")
|
||||
}
|
||||
|
||||
// SendPendingOAuthVerifyCode sends a verification code for a browser-bound
|
||||
// pending OAuth account-creation flow.
|
||||
// POST /api/v1/auth/oauth/pending/send-verify-code
|
||||
func (h *AuthHandler) SendPendingOAuthVerifyCode(c *gin.Context) {
|
||||
var req sendPendingOAuthVerifyCodeRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "Invalid request: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.authService.VerifyTurnstile(c.Request.Context(), req.TurnstileToken, ip.GetClientIP(c)); err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
_, session, _, err := readPendingOAuthBrowserSession(c, h)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
if err := ensurePendingOAuthCompleteRegistrationSession(session); err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
result, err := h.authService.SendPendingOAuthVerifyCode(c.Request.Context(), req.Email)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, SendVerifyCodeResponse{
|
||||
Message: "Verification code sent successfully",
|
||||
Countdown: result.Countdown,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *AuthHandler) upsertPendingOAuthAdoptionDecision(
|
||||
c *gin.Context,
|
||||
sessionID int64,
|
||||
@@ -1084,6 +1129,41 @@ func buildPendingOAuthSessionStatusPayload(session *dbent.PendingAuthSession) gi
|
||||
return payload
|
||||
}
|
||||
|
||||
func (h *AuthHandler) transitionPendingOAuthAccountToBindLogin(
|
||||
c *gin.Context,
|
||||
client *dbent.Client,
|
||||
session *dbent.PendingAuthSession,
|
||||
email string,
|
||||
decision oauthAdoptionDecisionRequest,
|
||||
) (*dbent.PendingAuthSession, error) {
|
||||
existingUser, err := findUserByNormalizedEmail(c.Request.Context(), client, email)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
completionResponse := mergePendingCompletionResponse(session, map[string]any{
|
||||
"step": "bind_login_required",
|
||||
"email": email,
|
||||
})
|
||||
session, err = updatePendingOAuthSessionProgress(
|
||||
c.Request.Context(),
|
||||
client,
|
||||
session,
|
||||
"adopt_existing_user_by_email",
|
||||
email,
|
||||
&existingUser.ID,
|
||||
completionResponse,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, infraerrors.InternalServer("PENDING_AUTH_SESSION_UPDATE_FAILED", "failed to update pending oauth session").WithCause(err)
|
||||
}
|
||||
|
||||
if _, err := h.ensurePendingOAuthAdoptionDecision(c, session.ID, decision); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func writeOAuthTokenPairResponse(c *gin.Context, tokenPair *service.TokenPair) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
"access_token": tokenPair.AccessToken,
|
||||
@@ -1199,29 +1279,11 @@ func (h *AuthHandler) createPendingOAuthAccount(c *gin.Context, provider string)
|
||||
return
|
||||
}
|
||||
if existingUser != nil {
|
||||
completionResponse := mergePendingCompletionResponse(session, map[string]any{
|
||||
"step": "bind_login_required",
|
||||
"email": email,
|
||||
})
|
||||
session, err = updatePendingOAuthSessionProgress(
|
||||
c.Request.Context(),
|
||||
client,
|
||||
session,
|
||||
"adopt_existing_user_by_email",
|
||||
email,
|
||||
&existingUser.ID,
|
||||
completionResponse,
|
||||
)
|
||||
session, err = h.transitionPendingOAuthAccountToBindLogin(c, client, session, email, req.adoptionDecision())
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, infraerrors.InternalServer("PENDING_AUTH_SESSION_UPDATE_FAILED", "failed to update pending oauth session").WithCause(err))
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := h.ensurePendingOAuthAdoptionDecision(c, session.ID, req.adoptionDecision()); err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, buildPendingOAuthSessionStatusPayload(session))
|
||||
return
|
||||
}
|
||||
@@ -1239,27 +1301,77 @@ func (h *AuthHandler) createPendingOAuthAccount(c *gin.Context, provider string)
|
||||
strings.TrimSpace(session.ProviderType),
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrEmailExists) {
|
||||
session, err = h.transitionPendingOAuthAccountToBindLogin(c, client, session, email, req.adoptionDecision())
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
c.JSON(http.StatusOK, buildPendingOAuthSessionStatusPayload(session))
|
||||
return
|
||||
}
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
rollbackCreatedUser := func(originalErr error) bool {
|
||||
if user == nil || user.ID <= 0 {
|
||||
return false
|
||||
}
|
||||
if rollbackErr := h.authService.RollbackOAuthEmailAccountCreation(
|
||||
c.Request.Context(),
|
||||
user.ID,
|
||||
strings.TrimSpace(req.InvitationCode),
|
||||
); rollbackErr != nil {
|
||||
response.ErrorFrom(c, infraerrors.InternalServer(
|
||||
"PENDING_AUTH_ACCOUNT_ROLLBACK_FAILED",
|
||||
"failed to rollback pending oauth account creation",
|
||||
).WithCause(fmt.Errorf("original error: %w; rollback error: %v", originalErr, rollbackErr)))
|
||||
return true
|
||||
}
|
||||
user = nil
|
||||
return false
|
||||
}
|
||||
|
||||
decision, err := h.ensurePendingOAuthAdoptionDecision(c, session.ID, req.adoptionDecision())
|
||||
if err != nil {
|
||||
if rollbackCreatedUser(err) {
|
||||
return
|
||||
}
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
if err := applyPendingOAuthBinding(c.Request.Context(), client, h.authService, h.userService, session, decision, &user.ID, true, false); err != nil {
|
||||
if rollbackCreatedUser(err) {
|
||||
return
|
||||
}
|
||||
response.ErrorFrom(c, infraerrors.InternalServer("PENDING_AUTH_BIND_APPLY_FAILED", "failed to bind pending oauth identity").WithCause(err))
|
||||
return
|
||||
}
|
||||
h.authService.RecordSuccessfulLogin(c.Request.Context(), user.ID)
|
||||
|
||||
if err := h.authService.FinalizeOAuthEmailAccount(
|
||||
c.Request.Context(),
|
||||
user,
|
||||
strings.TrimSpace(req.InvitationCode),
|
||||
strings.TrimSpace(session.ProviderType),
|
||||
); err != nil {
|
||||
if rollbackCreatedUser(err) {
|
||||
return
|
||||
}
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := pendingSvc.ConsumeBrowserSession(c.Request.Context(), session.SessionToken, session.BrowserSessionKey); err != nil {
|
||||
if rollbackCreatedUser(err) {
|
||||
return
|
||||
}
|
||||
clearCookies()
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
h.authService.RecordSuccessfulLogin(c.Request.Context(), user.ID)
|
||||
clearCookies()
|
||||
writeOAuthTokenPairResponse(c, tokenPair)
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
@@ -15,6 +16,7 @@ import (
|
||||
"github.com/Wei-Shaw/sub2api/ent/enttest"
|
||||
"github.com/Wei-Shaw/sub2api/ent/identityadoptiondecision"
|
||||
"github.com/Wei-Shaw/sub2api/ent/pendingauthsession"
|
||||
"github.com/Wei-Shaw/sub2api/ent/redeemcode"
|
||||
dbuser "github.com/Wei-Shaw/sub2api/ent/user"
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
@@ -61,6 +63,18 @@ func TestApplySuggestedProfileToCompletionResponseKeepsExistingPayloadValues(t *
|
||||
require.Equal(t, true, payload["adoption_required"])
|
||||
}
|
||||
|
||||
func TestSetOAuthPendingSessionCookieUsesProviderCompletionPathPrefix(t *testing.T) {
|
||||
recorder := httptest.NewRecorder()
|
||||
ginCtx, _ := gin.CreateTestContext(recorder)
|
||||
ginCtx.Request = httptest.NewRequest(http.MethodGet, "/api/v1/auth/oauth/oidc/callback", nil)
|
||||
|
||||
setOAuthPendingSessionCookie(ginCtx, "pending-session-token", false)
|
||||
|
||||
cookie := findCookie(recorder.Result().Cookies(), oauthPendingSessionCookieName)
|
||||
require.NotNil(t, cookie)
|
||||
require.Equal(t, "/api/v1/auth/oauth", cookie.Path)
|
||||
}
|
||||
|
||||
func TestExchangePendingOAuthCompletionPreviewThenFinalizeAppliesAdoptionDecision(t *testing.T) {
|
||||
handler, client := newOAuthPendingFlowTestHandler(t, false)
|
||||
ctx := context.Background()
|
||||
@@ -943,6 +957,81 @@ func TestCreateOIDCOAuthAccountBlocksBackendModeBeforeCreatingUser(t *testing.T)
|
||||
require.Nil(t, storedSession.ConsumedAt)
|
||||
}
|
||||
|
||||
func TestCreateOIDCOAuthAccountRollsBackCreatedUserWhenBindingFails(t *testing.T) {
|
||||
handler, client := newOAuthPendingFlowTestHandlerWithEmailVerification(t, true, "fresh@example.com", "246810")
|
||||
ctx := context.Background()
|
||||
|
||||
conflictOwner, err := client.User.Create().
|
||||
SetEmail("owner@example.com").
|
||||
SetUsername("owner-user").
|
||||
SetPasswordHash("hash").
|
||||
SetRole(service.RoleUser).
|
||||
SetStatus(service.StatusActive).
|
||||
Save(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = client.AuthIdentity.Create().
|
||||
SetUserID(conflictOwner.ID).
|
||||
SetProviderType("oidc").
|
||||
SetProviderKey("https://issuer.example").
|
||||
SetProviderSubject("oidc-conflict-123").
|
||||
SetMetadata(map[string]any{
|
||||
"username": "owner-user",
|
||||
}).
|
||||
Save(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
invitation, err := client.RedeemCode.Create().
|
||||
SetCode("INVITE123").
|
||||
SetType(service.RedeemTypeInvitation).
|
||||
SetStatus(service.StatusUnused).
|
||||
SetValue(0).
|
||||
Save(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
session, err := client.PendingAuthSession.Create().
|
||||
SetSessionToken("create-account-conflict-session-token").
|
||||
SetIntent("login").
|
||||
SetProviderType("oidc").
|
||||
SetProviderKey("https://issuer.example").
|
||||
SetProviderSubject("oidc-conflict-123").
|
||||
SetBrowserSessionKey("create-account-conflict-browser-session-key").
|
||||
SetUpstreamIdentityClaims(map[string]any{
|
||||
"username": "oidc_user",
|
||||
}).
|
||||
SetRedirectTo("/profile").
|
||||
SetExpiresAt(time.Now().UTC().Add(10 * time.Minute)).
|
||||
Save(ctx)
|
||||
require.NoError(t, err)
|
||||
|
||||
body := bytes.NewBufferString(`{"email":"fresh@example.com","verify_code":"246810","password":"secret-123","invitation_code":"INVITE123"}`)
|
||||
recorder := httptest.NewRecorder()
|
||||
ginCtx, _ := gin.CreateTestContext(recorder)
|
||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/oauth/oidc/create-account", body)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.AddCookie(&http.Cookie{Name: oauthPendingSessionCookieName, Value: encodeCookieValue(session.SessionToken)})
|
||||
req.AddCookie(&http.Cookie{Name: oauthPendingBrowserCookieName, Value: encodeCookieValue("create-account-conflict-browser-session-key")})
|
||||
ginCtx.Request = req
|
||||
|
||||
handler.CreateOIDCOAuthAccount(ginCtx)
|
||||
|
||||
require.Equal(t, http.StatusInternalServerError, recorder.Code)
|
||||
|
||||
userCount, err := client.User.Query().Where(dbuser.EmailEQ("fresh@example.com")).Count(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, userCount)
|
||||
|
||||
storedInvitation, err := client.RedeemCode.Get(ctx, invitation.ID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, service.StatusUnused, storedInvitation.Status)
|
||||
require.Nil(t, storedInvitation.UsedBy)
|
||||
require.Nil(t, storedInvitation.UsedAt)
|
||||
|
||||
storedSession, err := client.PendingAuthSession.Get(ctx, session.ID)
|
||||
require.NoError(t, err)
|
||||
require.Nil(t, storedSession.ConsumedAt)
|
||||
}
|
||||
|
||||
func TestBindOIDCOAuthLoginBindsExistingUserAndConsumesSession(t *testing.T) {
|
||||
handler, client := newOAuthPendingFlowTestHandler(t, false)
|
||||
ctx := context.Background()
|
||||
@@ -1529,6 +1618,8 @@ type oauthPendingFlowTestHandlerOptions struct {
|
||||
defaultSubAssigner service.DefaultSubscriptionAssigner
|
||||
totpCache service.TotpCache
|
||||
totpEncryptor service.SecretEncryptor
|
||||
redeemRepoFactory func(client *dbent.Client) service.RedeemCodeRepository
|
||||
userRepoOptions oauthPendingFlowUserRepoOptions
|
||||
}
|
||||
|
||||
func newOAuthPendingFlowTestHandlerWithDependencies(
|
||||
@@ -1590,7 +1681,17 @@ CREATE TABLE IF NOT EXISTS user_avatars (
|
||||
settingValues[key] = value
|
||||
}
|
||||
settingSvc := service.NewSettingService(&oauthPendingFlowSettingRepoStub{values: settingValues}, cfg)
|
||||
userRepo := &oauthPendingFlowUserRepo{client: client}
|
||||
userRepo := &oauthPendingFlowUserRepo{
|
||||
client: client,
|
||||
options: options.userRepoOptions,
|
||||
}
|
||||
redeemRepo := service.RedeemCodeRepository(nil)
|
||||
if options.redeemRepoFactory != nil {
|
||||
redeemRepo = options.redeemRepoFactory(client)
|
||||
}
|
||||
if redeemRepo == nil {
|
||||
redeemRepo = &oauthPendingFlowRedeemCodeRepo{client: client}
|
||||
}
|
||||
var emailService *service.EmailService
|
||||
if options.emailCache != nil {
|
||||
emailService = service.NewEmailService(&oauthPendingFlowSettingRepoStub{
|
||||
@@ -1602,7 +1703,7 @@ CREATE TABLE IF NOT EXISTS user_avatars (
|
||||
authSvc := service.NewAuthService(
|
||||
client,
|
||||
userRepo,
|
||||
nil,
|
||||
redeemRepo,
|
||||
&oauthPendingFlowRefreshTokenCacheStub{},
|
||||
cfg,
|
||||
settingSvc,
|
||||
@@ -1797,6 +1898,127 @@ func (s *oauthPendingFlowRefreshTokenCacheStub) IsTokenInFamily(context.Context,
|
||||
return false, nil
|
||||
}
|
||||
|
||||
type oauthPendingFlowRedeemCodeRepo struct {
|
||||
client *dbent.Client
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowRedeemCodeRepo) Create(context.Context, *service.RedeemCode) error {
|
||||
panic("unexpected Create call")
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowRedeemCodeRepo) CreateBatch(context.Context, []service.RedeemCode) error {
|
||||
panic("unexpected CreateBatch call")
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowRedeemCodeRepo) GetByID(context.Context, int64) (*service.RedeemCode, error) {
|
||||
panic("unexpected GetByID call")
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowRedeemCodeRepo) GetByCode(ctx context.Context, code string) (*service.RedeemCode, error) {
|
||||
entity, err := r.client.RedeemCode.Query().Where(redeemcode.CodeEQ(code)).Only(ctx)
|
||||
if err != nil {
|
||||
if dbent.IsNotFound(err) {
|
||||
return nil, service.ErrRedeemCodeNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
notes := ""
|
||||
if entity.Notes != nil {
|
||||
notes = *entity.Notes
|
||||
}
|
||||
return &service.RedeemCode{
|
||||
ID: entity.ID,
|
||||
Code: entity.Code,
|
||||
Type: entity.Type,
|
||||
Value: entity.Value,
|
||||
Status: entity.Status,
|
||||
UsedBy: entity.UsedBy,
|
||||
UsedAt: entity.UsedAt,
|
||||
Notes: notes,
|
||||
CreatedAt: entity.CreatedAt,
|
||||
GroupID: entity.GroupID,
|
||||
ValidityDays: entity.ValidityDays,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowRedeemCodeRepo) Update(ctx context.Context, code *service.RedeemCode) error {
|
||||
if code == nil {
|
||||
return nil
|
||||
}
|
||||
update := r.client.RedeemCode.UpdateOneID(code.ID).
|
||||
SetCode(code.Code).
|
||||
SetType(code.Type).
|
||||
SetValue(code.Value).
|
||||
SetStatus(code.Status).
|
||||
SetNotes(code.Notes).
|
||||
SetValidityDays(code.ValidityDays)
|
||||
if code.UsedBy != nil {
|
||||
update = update.SetUsedBy(*code.UsedBy)
|
||||
} else {
|
||||
update = update.ClearUsedBy()
|
||||
}
|
||||
if code.UsedAt != nil {
|
||||
update = update.SetUsedAt(*code.UsedAt)
|
||||
} else {
|
||||
update = update.ClearUsedAt()
|
||||
}
|
||||
if code.GroupID != nil {
|
||||
update = update.SetGroupID(*code.GroupID)
|
||||
} else {
|
||||
update = update.ClearGroupID()
|
||||
}
|
||||
_, err := update.Save(ctx)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowRedeemCodeRepo) Delete(context.Context, int64) error {
|
||||
panic("unexpected Delete call")
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowRedeemCodeRepo) Use(ctx context.Context, id, userID int64) error {
|
||||
affected, err := r.client.RedeemCode.Update().
|
||||
Where(redeemcode.IDEQ(id), redeemcode.StatusEQ(service.StatusUnused)).
|
||||
SetStatus(service.StatusUsed).
|
||||
SetUsedBy(userID).
|
||||
SetUsedAt(time.Now().UTC()).
|
||||
Save(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if affected == 0 {
|
||||
return service.ErrRedeemCodeUsed
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowRedeemCodeRepo) List(context.Context, pagination.PaginationParams) ([]service.RedeemCode, *pagination.PaginationResult, error) {
|
||||
panic("unexpected List call")
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowRedeemCodeRepo) ListWithFilters(context.Context, pagination.PaginationParams, string, string, string) ([]service.RedeemCode, *pagination.PaginationResult, error) {
|
||||
panic("unexpected ListWithFilters call")
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowRedeemCodeRepo) ListByUser(context.Context, int64, int) ([]service.RedeemCode, error) {
|
||||
panic("unexpected ListByUser call")
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowRedeemCodeRepo) ListByUserPaginated(context.Context, int64, pagination.PaginationParams, string) ([]service.RedeemCode, *pagination.PaginationResult, error) {
|
||||
panic("unexpected ListByUserPaginated call")
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowRedeemCodeRepo) SumPositiveBalanceByUser(context.Context, int64) (float64, error) {
|
||||
panic("unexpected SumPositiveBalanceByUser call")
|
||||
}
|
||||
|
||||
type oauthPendingFlowFailingUseRedeemRepo struct {
|
||||
*oauthPendingFlowRedeemCodeRepo
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowFailingUseRedeemRepo) Use(context.Context, int64, int64) error {
|
||||
return errors.New("forced invitation use failure")
|
||||
}
|
||||
|
||||
func decodeJSONResponseData(t *testing.T, recorder *httptest.ResponseRecorder) map[string]any {
|
||||
t.Helper()
|
||||
|
||||
@@ -1872,6 +2094,11 @@ func countProviderGrantRecords(
|
||||
|
||||
type oauthPendingFlowUserRepo struct {
|
||||
client *dbent.Client
|
||||
options oauthPendingFlowUserRepoOptions
|
||||
}
|
||||
|
||||
type oauthPendingFlowUserRepoOptions struct {
|
||||
rejectDeleteWhileAuthIdentityExists bool
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowUserRepo) Create(ctx context.Context, user *service.User) error {
|
||||
@@ -1953,6 +2180,15 @@ func (r *oauthPendingFlowUserRepo) Update(ctx context.Context, user *service.Use
|
||||
}
|
||||
|
||||
func (r *oauthPendingFlowUserRepo) Delete(ctx context.Context, id int64) error {
|
||||
if r.options.rejectDeleteWhileAuthIdentityExists {
|
||||
count, err := r.client.AuthIdentity.Query().Where(authidentity.UserIDEQ(id)).Count(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count > 0 {
|
||||
return errors.New("cannot delete user while auth identities still exist")
|
||||
}
|
||||
}
|
||||
return r.client.User.DeleteOneID(id).Exec(ctx)
|
||||
}
|
||||
|
||||
|
||||
@@ -15,14 +15,21 @@ import (
|
||||
// UserHandler handles user-related requests
|
||||
type UserHandler struct {
|
||||
userService *service.UserService
|
||||
authService *service.AuthService
|
||||
emailService *service.EmailService
|
||||
emailCache service.EmailCache
|
||||
}
|
||||
|
||||
// NewUserHandler creates a new UserHandler
|
||||
func NewUserHandler(userService *service.UserService, emailService *service.EmailService, emailCache service.EmailCache) *UserHandler {
|
||||
func NewUserHandler(
|
||||
userService *service.UserService,
|
||||
authService *service.AuthService,
|
||||
emailService *service.EmailService,
|
||||
emailCache service.EmailCache,
|
||||
) *UserHandler {
|
||||
return &UserHandler{
|
||||
userService: userService,
|
||||
authService: authService,
|
||||
emailService: emailService,
|
||||
emailCache: emailCache,
|
||||
}
|
||||
@@ -157,6 +164,16 @@ type StartIdentityBindingRequest struct {
|
||||
RedirectTo string `json:"redirect_to"`
|
||||
}
|
||||
|
||||
type BindEmailIdentityRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
VerifyCode string `json:"verify_code" binding:"required"`
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
}
|
||||
|
||||
type SendEmailBindingCodeRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
}
|
||||
|
||||
// StartIdentityBinding returns the backend authorize URL for starting a third-party identity bind flow.
|
||||
// POST /api/v1/user/auth-identities/bind/start
|
||||
func (h *UserHandler) StartIdentityBinding(c *gin.Context) {
|
||||
@@ -183,6 +200,73 @@ func (h *UserHandler) StartIdentityBinding(c *gin.Context) {
|
||||
response.Success(c, result)
|
||||
}
|
||||
|
||||
// BindEmailIdentity verifies and binds a local email identity for the current user.
|
||||
// POST /api/v1/user/account-bindings/email
|
||||
func (h *UserHandler) BindEmailIdentity(c *gin.Context) {
|
||||
subject, ok := middleware2.GetAuthSubjectFromContext(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "User not authenticated")
|
||||
return
|
||||
}
|
||||
if h.authService == nil {
|
||||
response.InternalError(c, "Auth service not configured")
|
||||
return
|
||||
}
|
||||
|
||||
var req BindEmailIdentityRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "Invalid request: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
updatedUser, err := h.authService.BindEmailIdentity(
|
||||
c.Request.Context(),
|
||||
subject.UserID,
|
||||
req.Email,
|
||||
req.VerifyCode,
|
||||
req.Password,
|
||||
)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
profileResp, err := h.buildUserProfileResponse(c.Request.Context(), subject.UserID, updatedUser)
|
||||
if err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, profileResp)
|
||||
}
|
||||
|
||||
// SendEmailBindingCode sends a verification code for the current user's email binding flow.
|
||||
// POST /api/v1/user/account-bindings/email/send-code
|
||||
func (h *UserHandler) SendEmailBindingCode(c *gin.Context) {
|
||||
subject, ok := middleware2.GetAuthSubjectFromContext(c)
|
||||
if !ok {
|
||||
response.Unauthorized(c, "User not authenticated")
|
||||
return
|
||||
}
|
||||
if h.authService == nil {
|
||||
response.InternalError(c, "Auth service not configured")
|
||||
return
|
||||
}
|
||||
|
||||
var req SendEmailBindingCodeRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "Invalid request: "+err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.authService.SendEmailIdentityBindCode(c.Request.Context(), subject.UserID, req.Email); err != nil {
|
||||
response.ErrorFrom(c, err)
|
||||
return
|
||||
}
|
||||
|
||||
response.Success(c, gin.H{"message": "Verification code sent successfully"})
|
||||
}
|
||||
|
||||
// SendNotifyEmailCodeRequest represents the request to send notify email verification code
|
||||
type SendNotifyEmailCodeRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/config"
|
||||
"github.com/Wei-Shaw/sub2api/internal/pkg/pagination"
|
||||
middleware2 "github.com/Wei-Shaw/sub2api/internal/server/middleware"
|
||||
"github.com/Wei-Shaw/sub2api/internal/service"
|
||||
@@ -122,7 +123,7 @@ func TestUserHandlerUpdateProfileReturnsAvatarURL(t *testing.T) {
|
||||
Status: service.StatusActive,
|
||||
},
|
||||
}
|
||||
handler := NewUserHandler(service.NewUserService(repo, nil, nil, nil), nil, nil)
|
||||
handler := NewUserHandler(service.NewUserService(repo, nil, nil, nil), nil, nil, nil)
|
||||
|
||||
body := []byte(`{"avatar_url":"https://cdn.example.com/avatar.png"}`)
|
||||
recorder := httptest.NewRecorder()
|
||||
@@ -180,7 +181,7 @@ func TestUserHandlerGetProfileReturnsIdentitySummaries(t *testing.T) {
|
||||
},
|
||||
},
|
||||
}
|
||||
handler := NewUserHandler(service.NewUserService(repo, nil, nil, nil), nil, nil)
|
||||
handler := NewUserHandler(service.NewUserService(repo, nil, nil, nil), nil, nil, nil)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
@@ -262,7 +263,7 @@ func TestUserHandlerGetProfileReturnsLegacyCompatibilityFields(t *testing.T) {
|
||||
},
|
||||
},
|
||||
}
|
||||
handler := NewUserHandler(service.NewUserService(repo, nil, nil, nil), nil, nil)
|
||||
handler := NewUserHandler(service.NewUserService(repo, nil, nil, nil), nil, nil, nil)
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
@@ -311,6 +312,116 @@ func TestUserHandlerGetProfileReturnsLegacyCompatibilityFields(t *testing.T) {
|
||||
require.Equal(t, "linuxdo", usernameSource["source"])
|
||||
}
|
||||
|
||||
type userHandlerEmailCacheStub struct {
|
||||
data *service.VerificationCodeData
|
||||
}
|
||||
|
||||
func (s *userHandlerEmailCacheStub) GetVerificationCode(context.Context, string) (*service.VerificationCodeData, error) {
|
||||
return s.data, nil
|
||||
}
|
||||
|
||||
func (s *userHandlerEmailCacheStub) SetVerificationCode(context.Context, string, *service.VerificationCodeData, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *userHandlerEmailCacheStub) DeleteVerificationCode(context.Context, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *userHandlerEmailCacheStub) GetNotifyVerifyCode(context.Context, string) (*service.VerificationCodeData, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *userHandlerEmailCacheStub) SetNotifyVerifyCode(context.Context, string, *service.VerificationCodeData, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *userHandlerEmailCacheStub) DeleteNotifyVerifyCode(context.Context, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *userHandlerEmailCacheStub) GetPasswordResetToken(context.Context, string) (*service.PasswordResetTokenData, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s *userHandlerEmailCacheStub) SetPasswordResetToken(context.Context, string, *service.PasswordResetTokenData, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *userHandlerEmailCacheStub) DeletePasswordResetToken(context.Context, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *userHandlerEmailCacheStub) IsPasswordResetEmailInCooldown(context.Context, string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *userHandlerEmailCacheStub) SetPasswordResetEmailCooldown(context.Context, string, time.Duration) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *userHandlerEmailCacheStub) GetNotifyCodeUserRate(context.Context, int64) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (s *userHandlerEmailCacheStub) IncrNotifyCodeUserRate(context.Context, int64, time.Duration) (int64, error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func TestUserHandlerBindEmailIdentityReturnsProfileResponse(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
repo := &userHandlerRepoStub{
|
||||
user: &service.User{
|
||||
ID: 11,
|
||||
Email: "legacy-user" + service.LinuxDoConnectSyntheticEmailDomain,
|
||||
Username: "legacy-user",
|
||||
Role: service.RoleUser,
|
||||
Status: service.StatusActive,
|
||||
},
|
||||
}
|
||||
emailCache := &userHandlerEmailCacheStub{
|
||||
data: &service.VerificationCodeData{
|
||||
Code: "123456",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
ExpiresAt: time.Now().UTC().Add(10 * time.Minute),
|
||||
},
|
||||
}
|
||||
cfg := &config.Config{
|
||||
JWT: config.JWTConfig{
|
||||
Secret: "test-secret",
|
||||
ExpireHour: 1,
|
||||
},
|
||||
}
|
||||
emailService := service.NewEmailService(nil, emailCache)
|
||||
authService := service.NewAuthService(nil, repo, nil, nil, cfg, nil, emailService, nil, nil, nil, nil)
|
||||
handler := NewUserHandler(service.NewUserService(repo, nil, nil, nil), authService, nil, nil)
|
||||
|
||||
body := []byte(`{"email":"new@example.com","verify_code":"123456","password":"new-password"}`)
|
||||
recorder := httptest.NewRecorder()
|
||||
c, _ := gin.CreateTestContext(recorder)
|
||||
c.Request = httptest.NewRequest(http.MethodPost, "/api/v1/user/account-bindings/email", bytes.NewReader(body))
|
||||
c.Request.Header.Set("Content-Type", "application/json")
|
||||
c.Params = gin.Params{{Key: "provider", Value: "email"}}
|
||||
c.Set(string(middleware2.ContextKeyUser), middleware2.AuthSubject{UserID: 11})
|
||||
|
||||
handler.BindEmailIdentity(c)
|
||||
|
||||
require.Equal(t, http.StatusOK, recorder.Code)
|
||||
|
||||
var resp struct {
|
||||
Code int `json:"code"`
|
||||
Data struct {
|
||||
Email string `json:"email"`
|
||||
EmailBound bool `json:"email_bound"`
|
||||
} `json:"data"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(recorder.Body.Bytes(), &resp))
|
||||
require.Equal(t, 0, resp.Code)
|
||||
require.Equal(t, "new@example.com", resp.Data.Email)
|
||||
require.True(t, resp.Data.EmailBound)
|
||||
}
|
||||
|
||||
func TestUserHandlerStartIdentityBindingReturnsAuthorizeURL(t *testing.T) {
|
||||
gin.SetMode(gin.TestMode)
|
||||
|
||||
@@ -323,7 +434,7 @@ func TestUserHandlerStartIdentityBindingReturnsAuthorizeURL(t *testing.T) {
|
||||
Status: service.StatusActive,
|
||||
},
|
||||
}
|
||||
handler := NewUserHandler(service.NewUserService(repo, nil, nil, nil), nil, nil)
|
||||
handler := NewUserHandler(service.NewUserService(repo, nil, nil, nil), nil, nil, nil)
|
||||
|
||||
body := []byte(`{"provider":"wechat","redirect_to":"/settings/profile"}`)
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
Reference in New Issue
Block a user