fix: correct sessions table column names from user_id to user_uuid

- Fixed CreateSession and GetSession SQL queries to use user_uuid instead of user_id
- Added unique constraint on sessions.token column for proper upsert support
- Created migration file to add the unique index to existing databases

This fixes the 500 error on /api/auth/login caused by session creation failure
This commit is contained in:
Haitao Pan 2026-02-05 11:00:57 +08:00
parent bc2562b877
commit dc348238f1
3 changed files with 9 additions and 2 deletions

View File

@ -1324,13 +1324,13 @@ func (s *postgresStore) DeleteStaleAgents(ctx context.Context, staleThreshold ti
}
func (s *postgresStore) CreateSession(ctx context.Context, token, userID string, expiresAt time.Time) error {
const query = "INSERT INTO sessions (token, user_id, expires_at) VALUES ($1, $2, $3) ON CONFLICT (token) DO UPDATE SET user_id = EXCLUDED.user_id, expires_at = EXCLUDED.expires_at"
const query = "INSERT INTO sessions (token, user_uuid, expires_at) VALUES ($1, $2, $3) ON CONFLICT (token) DO UPDATE SET user_uuid = EXCLUDED.user_uuid, expires_at = EXCLUDED.expires_at"
_, err := s.db.ExecContext(ctx, query, token, userID, expiresAt.UTC())
return err
}
func (s *postgresStore) GetSession(ctx context.Context, token string) (string, time.Time, error) {
const query = "SELECT user_id, expires_at FROM sessions WHERE token = $1"
const query = "SELECT user_uuid, expires_at FROM sessions WHERE token = $1"
var userID string
var expiresAt time.Time
err := s.db.QueryRowContext(ctx, query, token).Scan(&userID, &expiresAt)

View File

@ -0,0 +1,6 @@
-- Migration: Add unique constraint on sessions.token
-- Date: 2026-02-05
-- Description: Adds a unique index on the sessions.token column to support
-- the ON CONFLICT clause in session upsert operations.
CREATE UNIQUE INDEX IF NOT EXISTS sessions_token_uk ON public.sessions (token);

View File

@ -191,6 +191,7 @@ CREATE UNIQUE INDEX users_email_lower_uk ON public.users (lower(email)) WHERE em
CREATE UNIQUE INDEX users_single_root_role_uk ON public.users ((lower(role))) WHERE lower(role) = 'root';
CREATE INDEX idx_identities_user_uuid ON public.identities (user_uuid);
CREATE INDEX idx_sessions_user_uuid ON public.sessions (user_uuid);
CREATE UNIQUE INDEX sessions_token_uk ON public.sessions (token);
CREATE INDEX idx_admin_settings_version ON public.admin_settings (version);
CREATE INDEX idx_subscriptions_user_uuid ON public.subscriptions (user_uuid);
CREATE INDEX idx_subscriptions_status ON public.subscriptions (status);