From e375b6cc68f4a9b0e91b25479538dc76d1f1e620 Mon Sep 17 00:00:00 2001 From: wikiapiserver Date: Thu, 25 Jun 2026 14:40:16 +0200 Subject: refactor: extract Wikimedia auth into reusable function - WikimediaLogin is a standalone function: POSTs to auth.enterprise.wikimedia.com and returns the tokens. Can be called from any flow. - Register composes WikimediaLogin + CreateAccount - CreateAccount now takes tokens as arguments (pure DB insert) --- db/db.go | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) (limited to 'db/db.go') diff --git a/db/db.go b/db/db.go index 059f1df..ce0dbfd 100644 --- a/db/db.go +++ b/db/db.go @@ -80,7 +80,7 @@ type WikimediaTokens struct { // Wikimedialogin sends credentials to the Wikimedia Enterprise auth API // and returns the refresh and access tokens. -func Wikimedialogin(ctx context.Context, username, password string) (*WikimediaTokens, error) { +func WikimediaLogin(ctx context.Context, username, password string) (*WikimediaTokens, error) { body := fmt.Sprintf("username=%s&password=%s", url.PathEscape(username), url.PathEscape(password)) @@ -119,22 +119,29 @@ func isDupKeyError(err error) bool { // --- queries --- -// CreateAccount registers the user via the Wikimedia auth API, +// Register authenticates the user via the Wikimedia auth API, // then persists the account and tokens to the database. // If the Wikimedia API call fails, registration fails. -func (d *DB) CreateAccount(ctx context.Context, username, plaintextPW string) (*Account, error) { - // Obtain tokens from Wikimedia Enterprise auth API - tokens, err := Wikimedialogin(ctx, username, plaintextPW) +func (d *DB) Register(ctx context.Context, username, plaintextPW string) (*Account, error) { + tokens, err := WikimediaLogin(ctx, username, plaintextPW) if err != nil { return nil, fmt.Errorf("wikimedia login: %w", err) } + acct, err := d.CreateAccount(ctx, username, plaintextPW, tokens.RefreshToken, tokens.AccessToken) + if err != nil { + return nil, err + } + + return acct, nil +} + +// CreateAccount inserts an account row with the given tokens. +func (d *DB) CreateAccount(ctx context.Context, username, plaintextPW, refreshToken, accessToken string) (*Account, error) { res, err := d.conn.ExecContext(ctx, `INSERT INTO account (username, password, refresh_token, access_token, refresh_token_created, access_token_created) VALUES (?, ?, ?, ?, NOW(), NOW())`, - username, plaintextPW, - tokens.RefreshToken, - tokens.AccessToken, + username, plaintextPW, refreshToken, accessToken, ) if err != nil { if isDupKeyError(err) { @@ -152,8 +159,8 @@ func (d *DB) CreateAccount(ctx context.Context, username, plaintextPW string) (* return &Account{ ID: id, Username: username, - RefreshToken: tokens.RefreshToken, - AccessToken: tokens.AccessToken, + RefreshToken: refreshToken, + AccessToken: accessToken, AccessTokenExpiry: now.Add(accessTokenTTL), CreatedAt: now, }, nil -- cgit v1.2.3