Compare commits
No commits in common. "feat/device-sessions" and "main" have entirely different histories.
feat/devic
...
main
|
|
@ -13,8 +13,6 @@ MONGODB_URL=mongodb://root:secret@localhost:27021/?authSource=admin
|
||||||
JWT_KEY=REPLACE_WITH_A_LONG_RANDOM_SIGNING_SECRET
|
JWT_KEY=REPLACE_WITH_A_LONG_RANDOM_SIGNING_SECRET
|
||||||
ACCESS_EXPIRY=3600
|
ACCESS_EXPIRY=3600
|
||||||
REFRESH_EXPIRY=604800
|
REFRESH_EXPIRY=604800
|
||||||
MAX_LEARNER_DEVICES=2
|
|
||||||
DEVICE_LIMIT_ENFORCED=false
|
|
||||||
REPORT_EXPORT_PATH=./exports
|
REPORT_EXPORT_PATH=./exports
|
||||||
|
|
||||||
# PostgreSQL connection pool
|
# PostgreSQL connection pool
|
||||||
|
|
|
||||||
|
|
@ -124,7 +124,6 @@ func main() {
|
||||||
repository.NewTokenStore(store),
|
repository.NewTokenStore(store),
|
||||||
cfg.RefreshExpiry,
|
cfg.RefreshExpiry,
|
||||||
)
|
)
|
||||||
authSvc.ConfigureDeviceSessions(cfg.MaxLearnerDevices, cfg.DeviceLimitEnforced)
|
|
||||||
|
|
||||||
authSvc.InitGoogleOAuth(
|
authSvc.InitGoogleOAuth(
|
||||||
authentication.PrimaryGoogleClientID(cfg.GoogleOAuthClientID),
|
authentication.PrimaryGoogleClientID(cfg.GoogleOAuthClientID),
|
||||||
|
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
DROP INDEX IF EXISTS idx_device_login_challenges_user_id;
|
|
||||||
DROP TABLE IF EXISTS device_login_challenges;
|
|
||||||
|
|
||||||
DROP INDEX IF EXISTS idx_refresh_tokens_session_id;
|
|
||||||
ALTER TABLE refresh_tokens DROP COLUMN IF EXISTS session_id;
|
|
||||||
|
|
||||||
DROP INDEX IF EXISTS idx_user_sessions_active_device_key;
|
|
||||||
DROP INDEX IF EXISTS idx_user_sessions_active_user;
|
|
||||||
DROP TABLE IF EXISTS user_sessions;
|
|
||||||
|
|
@ -1,43 +0,0 @@
|
||||||
CREATE TABLE user_sessions (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
||||||
device_key TEXT,
|
|
||||||
device_label TEXT NOT NULL,
|
|
||||||
platform TEXT NOT NULL,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
last_seen_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
expires_at TIMESTAMPTZ NOT NULL,
|
|
||||||
revoked_at TIMESTAMPTZ,
|
|
||||||
revoked_reason TEXT,
|
|
||||||
CONSTRAINT user_sessions_device_key_length CHECK (device_key IS NULL OR char_length(device_key) <= 128),
|
|
||||||
CONSTRAINT user_sessions_platform_check CHECK (platform IN ('web', 'android', 'ios'))
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX idx_user_sessions_active_user
|
|
||||||
ON user_sessions (user_id, expires_at)
|
|
||||||
WHERE revoked_at IS NULL;
|
|
||||||
|
|
||||||
CREATE UNIQUE INDEX idx_user_sessions_active_device_key
|
|
||||||
ON user_sessions (user_id, device_key)
|
|
||||||
WHERE revoked_at IS NULL AND device_key IS NOT NULL;
|
|
||||||
|
|
||||||
ALTER TABLE refresh_tokens
|
|
||||||
ADD COLUMN session_id UUID REFERENCES user_sessions(id) ON DELETE CASCADE;
|
|
||||||
|
|
||||||
CREATE INDEX idx_refresh_tokens_session_id ON refresh_tokens (session_id);
|
|
||||||
|
|
||||||
CREATE TABLE device_login_challenges (
|
|
||||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
|
||||||
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
|
||||||
token_hash BYTEA NOT NULL UNIQUE,
|
|
||||||
device_key TEXT,
|
|
||||||
device_label TEXT NOT NULL,
|
|
||||||
platform TEXT NOT NULL,
|
|
||||||
expires_at TIMESTAMPTZ NOT NULL,
|
|
||||||
used_at TIMESTAMPTZ,
|
|
||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
||||||
CONSTRAINT device_login_challenges_device_key_length CHECK (device_key IS NULL OR char_length(device_key) <= 128),
|
|
||||||
CONSTRAINT device_login_challenges_platform_check CHECK (platform IN ('web', 'android', 'ios'))
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX idx_device_login_challenges_user_id ON device_login_challenges (user_id);
|
|
||||||
|
|
@ -1,6 +1,6 @@
|
||||||
-- name: CreateRefreshToken :exec
|
-- name: CreateRefreshToken :exec
|
||||||
INSERT INTO refresh_tokens (user_id, token, expires_at, created_at, revoked, session_id)
|
INSERT INTO refresh_tokens (user_id, token, expires_at, created_at, revoked)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6);
|
VALUES ($1, $2, $3, $4, $5);
|
||||||
-- name: GetRefreshToken :one
|
-- name: GetRefreshToken :one
|
||||||
SELECT *
|
SELECT *
|
||||||
FROM refresh_tokens
|
FROM refresh_tokens
|
||||||
|
|
|
||||||
|
|
@ -1,168 +0,0 @@
|
||||||
-- name: LockUserSessions :exec
|
|
||||||
SELECT pg_advisory_xact_lock($1);
|
|
||||||
|
|
||||||
-- name: ResolveRefreshTokenUserID :one
|
|
||||||
SELECT user_id
|
|
||||||
FROM refresh_tokens
|
|
||||||
WHERE token = $1;
|
|
||||||
|
|
||||||
-- name: ResolveDeviceLoginChallengeUserID :one
|
|
||||||
SELECT user_id
|
|
||||||
FROM device_login_challenges
|
|
||||||
WHERE token_hash = $1;
|
|
||||||
|
|
||||||
-- name: RevokeActiveSessionByDeviceKey :exec
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET revoked_at = NOW(), revoked_reason = 'device_relogin'
|
|
||||||
WHERE user_id = $1 AND device_key = $2 AND revoked_at IS NULL;
|
|
||||||
|
|
||||||
-- name: RevokeRefreshTokensByDeviceKey :exec
|
|
||||||
UPDATE refresh_tokens
|
|
||||||
SET revoked = TRUE
|
|
||||||
WHERE revoked = FALSE AND session_id IN (
|
|
||||||
SELECT us.id FROM user_sessions AS us
|
|
||||||
WHERE us.user_id = $1 AND us.device_key = $2 AND us.revoked_at IS NULL
|
|
||||||
);
|
|
||||||
|
|
||||||
-- name: CountActiveUserSessions :one
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM user_sessions
|
|
||||||
WHERE user_id = $1 AND revoked_at IS NULL AND expires_at > NOW();
|
|
||||||
|
|
||||||
-- name: CreateUserSession :one
|
|
||||||
INSERT INTO user_sessions (user_id, device_key, device_label, platform, expires_at)
|
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
|
||||||
RETURNING *;
|
|
||||||
|
|
||||||
-- name: CreateRefreshTokenForSession :exec
|
|
||||||
INSERT INTO refresh_tokens (user_id, token, expires_at, created_at, revoked, session_id)
|
|
||||||
VALUES ($1, $2, $3, $4, FALSE, $5);
|
|
||||||
|
|
||||||
-- name: CreateDeviceLoginChallenge :exec
|
|
||||||
INSERT INTO device_login_challenges
|
|
||||||
(user_id, token_hash, device_key, device_label, platform, expires_at)
|
|
||||||
VALUES ($1, $2, $3, $4, $5, $6);
|
|
||||||
|
|
||||||
-- name: ListActiveUserSessions :many
|
|
||||||
SELECT *
|
|
||||||
FROM user_sessions
|
|
||||||
WHERE user_id = $1 AND revoked_at IS NULL AND expires_at > NOW()
|
|
||||||
ORDER BY last_seen_at DESC, created_at DESC, id;
|
|
||||||
|
|
||||||
-- name: RevokeExcessUserSessionRefreshTokens :exec
|
|
||||||
WITH excess AS (
|
|
||||||
SELECT us.id
|
|
||||||
FROM user_sessions AS us
|
|
||||||
WHERE us.user_id = sqlc.arg(target_user_id)
|
|
||||||
AND us.id <> sqlc.arg(keep_session_id)
|
|
||||||
AND us.revoked_at IS NULL
|
|
||||||
AND us.expires_at > NOW()
|
|
||||||
ORDER BY us.last_seen_at DESC, us.created_at DESC, us.id
|
|
||||||
OFFSET GREATEST(sqlc.arg(max_devices)::bigint - 1, 0)
|
|
||||||
)
|
|
||||||
UPDATE refresh_tokens
|
|
||||||
SET revoked = TRUE
|
|
||||||
WHERE revoked = FALSE AND session_id IN (SELECT id FROM excess);
|
|
||||||
|
|
||||||
-- name: RevokeExcessUserSessions :exec
|
|
||||||
WITH excess AS (
|
|
||||||
SELECT us.id
|
|
||||||
FROM user_sessions AS us
|
|
||||||
WHERE us.user_id = sqlc.arg(target_user_id)
|
|
||||||
AND us.id <> sqlc.arg(keep_session_id)
|
|
||||||
AND us.revoked_at IS NULL
|
|
||||||
AND us.expires_at > NOW()
|
|
||||||
ORDER BY us.last_seen_at DESC, us.created_at DESC, us.id
|
|
||||||
OFFSET GREATEST(sqlc.arg(max_devices)::bigint - 1, 0)
|
|
||||||
)
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET revoked_at = NOW(), revoked_reason = 'over_device_limit'
|
|
||||||
WHERE id IN (SELECT id FROM excess);
|
|
||||||
|
|
||||||
-- name: GetActiveUserSession :one
|
|
||||||
SELECT *
|
|
||||||
FROM user_sessions
|
|
||||||
WHERE id = $1 AND revoked_at IS NULL AND expires_at > NOW();
|
|
||||||
|
|
||||||
-- name: GetActiveUserSessionForUser :one
|
|
||||||
SELECT *
|
|
||||||
FROM user_sessions
|
|
||||||
WHERE id = $1 AND user_id = $2 AND revoked_at IS NULL AND expires_at > NOW();
|
|
||||||
|
|
||||||
-- name: RevokeUserSessionForUser :one
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET revoked_at = NOW(), revoked_reason = $3
|
|
||||||
WHERE id = $1 AND user_id = $2 AND revoked_at IS NULL
|
|
||||||
RETURNING id;
|
|
||||||
|
|
||||||
-- name: RevokeUserSession :one
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET revoked_at = NOW(), revoked_reason = $2
|
|
||||||
WHERE id = $1 AND revoked_at IS NULL
|
|
||||||
RETURNING user_id;
|
|
||||||
|
|
||||||
-- name: RevokeRefreshTokensBySession :exec
|
|
||||||
UPDATE refresh_tokens SET revoked = TRUE WHERE session_id = $1 AND revoked = FALSE;
|
|
||||||
|
|
||||||
-- name: RevokeAllUserSessions :exec
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET revoked_at = NOW(), revoked_reason = $2
|
|
||||||
WHERE user_id = $1 AND revoked_at IS NULL;
|
|
||||||
|
|
||||||
-- name: RevokeAllUserRefreshTokens :exec
|
|
||||||
UPDATE refresh_tokens SET revoked = TRUE WHERE user_id = $1 AND revoked = FALSE;
|
|
||||||
|
|
||||||
-- name: RevokeSessionsForRoleExcludingUser :exec
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET revoked_at = NOW(), revoked_reason = 'bulk_deactivation'
|
|
||||||
WHERE revoked_at IS NULL AND user_id IN (
|
|
||||||
SELECT u.id FROM users AS u WHERE u.role = $1 AND u.id <> $2
|
|
||||||
);
|
|
||||||
|
|
||||||
-- name: RevokeRefreshTokensForRoleExcludingUser :exec
|
|
||||||
UPDATE refresh_tokens
|
|
||||||
SET revoked = TRUE
|
|
||||||
WHERE revoked = FALSE AND user_id IN (
|
|
||||||
SELECT u.id FROM users AS u WHERE u.role = $1 AND u.id <> $2
|
|
||||||
);
|
|
||||||
|
|
||||||
-- name: ListUserIDsForRoleExcludingUser :many
|
|
||||||
SELECT id
|
|
||||||
FROM users
|
|
||||||
WHERE role = $1 AND id <> $2
|
|
||||||
ORDER BY id;
|
|
||||||
|
|
||||||
-- name: InvalidateUserDeviceChallenges :exec
|
|
||||||
UPDATE device_login_challenges
|
|
||||||
SET used_at = NOW()
|
|
||||||
WHERE user_id = $1 AND used_at IS NULL;
|
|
||||||
|
|
||||||
-- name: InvalidateDeviceChallengesForRoleExcludingUser :exec
|
|
||||||
UPDATE device_login_challenges
|
|
||||||
SET used_at = NOW()
|
|
||||||
WHERE used_at IS NULL AND user_id IN (
|
|
||||||
SELECT u.id FROM users AS u WHERE u.role = $1 AND u.id <> $2
|
|
||||||
);
|
|
||||||
|
|
||||||
-- name: GetDeviceLoginChallengeForUpdate :one
|
|
||||||
SELECT *
|
|
||||||
FROM device_login_challenges
|
|
||||||
WHERE token_hash = $1
|
|
||||||
FOR UPDATE;
|
|
||||||
|
|
||||||
-- name: UseDeviceLoginChallenge :exec
|
|
||||||
UPDATE device_login_challenges SET used_at = NOW() WHERE id = $1 AND used_at IS NULL;
|
|
||||||
|
|
||||||
-- name: GetRefreshTokenForUpdate :one
|
|
||||||
SELECT * FROM refresh_tokens WHERE token = $1 FOR UPDATE;
|
|
||||||
|
|
||||||
-- name: RotateRefreshToken :exec
|
|
||||||
UPDATE refresh_tokens SET revoked = TRUE WHERE id = $1 AND revoked = FALSE;
|
|
||||||
|
|
||||||
-- name: TouchUserSession :exec
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET last_seen_at = NOW(), expires_at = $2
|
|
||||||
WHERE id = $1 AND revoked_at IS NULL AND expires_at > NOW();
|
|
||||||
|
|
||||||
-- name: AttachRefreshTokenToSession :exec
|
|
||||||
UPDATE refresh_tokens SET session_id = $2 WHERE id = $1 AND session_id IS NULL;
|
|
||||||
55
docs/docs.go
55
docs/docs.go
|
|
@ -16875,27 +16875,6 @@ const docTemplate = `{
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"/api/v1/admin/users/{user_id}/sessions": {
|
|
||||||
"get": {
|
|
||||||
"tags": ["admin"],
|
|
||||||
"summary": "List a user's active device sessions",
|
|
||||||
"parameters": [{"type": "integer", "description": "User ID", "name": "user_id", "in": "path", "required": true}],
|
|
||||||
"responses": {"200": {"description": "OK", "schema": {"type": "object", "properties": {"message": {"type": "string"}, "data": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "label": {"type": "string"}, "platform": {"type": "string"}, "last_seen_at": {"type": "string"}}}}}}}},
|
|
||||||
"security": [{"Bearer": []}]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/api/v1/admin/users/{user_id}/sessions/{id}": {
|
|
||||||
"delete": {
|
|
||||||
"tags": ["admin"],
|
|
||||||
"summary": "Remove a user's active device session",
|
|
||||||
"parameters": [
|
|
||||||
{"type": "integer", "description": "User ID", "name": "user_id", "in": "path", "required": true},
|
|
||||||
{"type": "string", "description": "Session UUID", "name": "id", "in": "path", "required": true}
|
|
||||||
],
|
|
||||||
"responses": {"200": {"description": "OK", "schema": {"type": "object", "properties": {"message": {"type": "string"}}}}, "404": {"description": "Not Found", "schema": {"$ref": "#/definitions/domain.ErrorResponse"}}},
|
|
||||||
"security": [{"Bearer": []}]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/api/v1/admin/users/{user_id}/subscriptions": {
|
"/api/v1/admin/users/{user_id}/subscriptions": {
|
||||||
"get": {
|
"get": {
|
||||||
"security": [
|
"security": [
|
||||||
|
|
@ -18472,22 +18451,6 @@ const docTemplate = `{
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"/api/v1/auth/sessions/replace": {
|
|
||||||
"post": {
|
|
||||||
"consumes": ["application/json"],
|
|
||||||
"produces": ["application/json"],
|
|
||||||
"tags": ["auth"],
|
|
||||||
"summary": "Replace an active learner device session",
|
|
||||||
"parameters": [{
|
|
||||||
"description": "Session replacement challenge and active session ID",
|
|
||||||
"name": "body",
|
|
||||||
"in": "body",
|
|
||||||
"required": true,
|
|
||||||
"schema": {"type": "object", "required": ["challenge_token", "session_id"], "properties": {"challenge_token": {"type": "string"}, "session_id": {"type": "string"}}}
|
|
||||||
}],
|
|
||||||
"responses": {"200": {"description": "OK", "schema": {"type": "object", "properties": {"message": {"type": "string"}, "data": {"$ref": "#/definitions/handlers.loginUserRes"}}}}, "401": {"description": "Unauthorized", "schema": {"$ref": "#/definitions/domain.ErrorResponse"}}}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/api/v1/auth/customer-login": {
|
"/api/v1/auth/customer-login": {
|
||||||
"post": {
|
"post": {
|
||||||
"description": "Login user",
|
"description": "Login user",
|
||||||
|
|
@ -25346,24 +25309,6 @@ const docTemplate = `{
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"/api/v1/user/me/sessions": {
|
|
||||||
"get": {
|
|
||||||
"produces": ["application/json"],
|
|
||||||
"tags": ["user"],
|
|
||||||
"summary": "List the current learner's active device sessions",
|
|
||||||
"responses": {"200": {"description": "OK", "schema": {"type": "object", "properties": {"message": {"type": "string"}, "data": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "label": {"type": "string"}, "platform": {"type": "string"}, "last_seen_at": {"type": "string"}, "is_current": {"type": "boolean"}}}}}}}},
|
|
||||||
"security": [{"Bearer": []}]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/api/v1/user/me/sessions/{id}": {
|
|
||||||
"delete": {
|
|
||||||
"tags": ["user"],
|
|
||||||
"summary": "Remove one of the current learner's device sessions",
|
|
||||||
"parameters": [{"type": "string", "description": "Session UUID", "name": "id", "in": "path", "required": true}],
|
|
||||||
"responses": {"200": {"description": "OK", "schema": {"type": "object", "properties": {"message": {"type": "string"}}}}, "404": {"description": "Not Found", "schema": {"$ref": "#/definitions/domain.ErrorResponse"}}},
|
|
||||||
"security": [{"Bearer": []}]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/api/v1/user/user-profile": {
|
"/api/v1/user/user-profile": {
|
||||||
"get": {
|
"get": {
|
||||||
"security": [
|
"security": [
|
||||||
|
|
|
||||||
|
|
@ -97,8 +97,6 @@ The app loads `.env` from its working directory using `godotenv.Load()`. Existin
|
||||||
| `JWT_KEY` | Secret used to sign HS256 access tokens. Generate a strong random secret for each environment. |
|
| `JWT_KEY` | Secret used to sign HS256 access tokens. Generate a strong random secret for each environment. |
|
||||||
| `ACCESS_EXPIRY` | Positive integer: access-token lifetime in **seconds**, for example `3600`. |
|
| `ACCESS_EXPIRY` | Positive integer: access-token lifetime in **seconds**, for example `3600`. |
|
||||||
| `REFRESH_EXPIRY` | Positive integer: refresh-token lifetime in **seconds**, for example `604800`. |
|
| `REFRESH_EXPIRY` | Positive integer: refresh-token lifetime in **seconds**, for example `604800`. |
|
||||||
| `MAX_LEARNER_DEVICES` | Optional positive integer; maximum concurrent learner sessions. Defaults to `2`. |
|
|
||||||
| `DEVICE_LIMIT_ENFORCED` | Optional boolean. Defaults to `false`; sessions are still tracked and revocable while over-limit logins are allowed. |
|
|
||||||
| `LOG_LEVEL` | Exactly `debug`, `info`, `warn`, or `error`. |
|
| `LOG_LEVEL` | Exactly `debug`, `info`, `warn`, or `error`. |
|
||||||
| `REPORT_EXPORT_PATH` | Nonempty report export directory, for example `./exports`. Required even though report-worker initialization is currently commented out. |
|
| `REPORT_EXPORT_PATH` | Nonempty report export directory, for example `./exports`. Required even though report-worker initialization is currently commented out. |
|
||||||
| `AFRO_SMS_API_KEY` | AfroMessage API bearer token. Required even if SMS is not being used. |
|
| `AFRO_SMS_API_KEY` | AfroMessage API bearer token. Required even if SMS is not being used. |
|
||||||
|
|
|
||||||
|
|
@ -16867,27 +16867,6 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"/api/v1/admin/users/{user_id}/sessions": {
|
|
||||||
"get": {
|
|
||||||
"tags": ["admin"],
|
|
||||||
"summary": "List a user's active device sessions",
|
|
||||||
"parameters": [{"type": "integer", "description": "User ID", "name": "user_id", "in": "path", "required": true}],
|
|
||||||
"responses": {"200": {"description": "OK", "schema": {"type": "object", "properties": {"message": {"type": "string"}, "data": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "label": {"type": "string"}, "platform": {"type": "string"}, "last_seen_at": {"type": "string"}}}}}}}},
|
|
||||||
"security": [{"Bearer": []}]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/api/v1/admin/users/{user_id}/sessions/{id}": {
|
|
||||||
"delete": {
|
|
||||||
"tags": ["admin"],
|
|
||||||
"summary": "Remove a user's active device session",
|
|
||||||
"parameters": [
|
|
||||||
{"type": "integer", "description": "User ID", "name": "user_id", "in": "path", "required": true},
|
|
||||||
{"type": "string", "description": "Session UUID", "name": "id", "in": "path", "required": true}
|
|
||||||
],
|
|
||||||
"responses": {"200": {"description": "OK", "schema": {"type": "object", "properties": {"message": {"type": "string"}}}}, "404": {"description": "Not Found", "schema": {"$ref": "#/definitions/domain.ErrorResponse"}}},
|
|
||||||
"security": [{"Bearer": []}]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/api/v1/admin/users/{user_id}/subscriptions": {
|
"/api/v1/admin/users/{user_id}/subscriptions": {
|
||||||
"get": {
|
"get": {
|
||||||
"security": [
|
"security": [
|
||||||
|
|
@ -18464,22 +18443,6 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"/api/v1/auth/sessions/replace": {
|
|
||||||
"post": {
|
|
||||||
"consumes": ["application/json"],
|
|
||||||
"produces": ["application/json"],
|
|
||||||
"tags": ["auth"],
|
|
||||||
"summary": "Replace an active learner device session",
|
|
||||||
"parameters": [{
|
|
||||||
"description": "Session replacement challenge and active session ID",
|
|
||||||
"name": "body",
|
|
||||||
"in": "body",
|
|
||||||
"required": true,
|
|
||||||
"schema": {"type": "object", "required": ["challenge_token", "session_id"], "properties": {"challenge_token": {"type": "string"}, "session_id": {"type": "string"}}}
|
|
||||||
}],
|
|
||||||
"responses": {"200": {"description": "OK", "schema": {"type": "object", "properties": {"message": {"type": "string"}, "data": {"$ref": "#/definitions/handlers.loginUserRes"}}}}, "401": {"description": "Unauthorized", "schema": {"$ref": "#/definitions/domain.ErrorResponse"}}}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/api/v1/auth/customer-login": {
|
"/api/v1/auth/customer-login": {
|
||||||
"post": {
|
"post": {
|
||||||
"description": "Login user",
|
"description": "Login user",
|
||||||
|
|
@ -25338,24 +25301,6 @@
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"/api/v1/user/me/sessions": {
|
|
||||||
"get": {
|
|
||||||
"produces": ["application/json"],
|
|
||||||
"tags": ["user"],
|
|
||||||
"summary": "List the current learner's active device sessions",
|
|
||||||
"responses": {"200": {"description": "OK", "schema": {"type": "object", "properties": {"message": {"type": "string"}, "data": {"type": "array", "items": {"type": "object", "properties": {"id": {"type": "string"}, "label": {"type": "string"}, "platform": {"type": "string"}, "last_seen_at": {"type": "string"}, "is_current": {"type": "boolean"}}}}}}}},
|
|
||||||
"security": [{"Bearer": []}]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/api/v1/user/me/sessions/{id}": {
|
|
||||||
"delete": {
|
|
||||||
"tags": ["user"],
|
|
||||||
"summary": "Remove one of the current learner's device sessions",
|
|
||||||
"parameters": [{"type": "string", "description": "Session UUID", "name": "id", "in": "path", "required": true}],
|
|
||||||
"responses": {"200": {"description": "OK", "schema": {"type": "object", "properties": {"message": {"type": "string"}}}}, "404": {"description": "Not Found", "schema": {"$ref": "#/definitions/domain.ErrorResponse"}}},
|
|
||||||
"security": [{"Bearer": []}]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"/api/v1/user/user-profile": {
|
"/api/v1/user/user-profile": {
|
||||||
"get": {
|
"get": {
|
||||||
"security": [
|
"security": [
|
||||||
|
|
|
||||||
|
|
@ -16853,70 +16853,6 @@ paths:
|
||||||
summary: Recent activity timeline for a user (admin)
|
summary: Recent activity timeline for a user (admin)
|
||||||
tags:
|
tags:
|
||||||
- lms
|
- lms
|
||||||
/api/v1/admin/users/{user_id}/sessions:
|
|
||||||
get:
|
|
||||||
parameters:
|
|
||||||
- description: User ID
|
|
||||||
in: path
|
|
||||||
name: user_id
|
|
||||||
required: true
|
|
||||||
type: integer
|
|
||||||
responses:
|
|
||||||
"200":
|
|
||||||
description: OK
|
|
||||||
schema:
|
|
||||||
properties:
|
|
||||||
data:
|
|
||||||
items:
|
|
||||||
properties:
|
|
||||||
id:
|
|
||||||
type: string
|
|
||||||
label:
|
|
||||||
type: string
|
|
||||||
last_seen_at:
|
|
||||||
type: string
|
|
||||||
platform:
|
|
||||||
type: string
|
|
||||||
type: object
|
|
||||||
type: array
|
|
||||||
message:
|
|
||||||
type: string
|
|
||||||
type: object
|
|
||||||
security:
|
|
||||||
- Bearer: []
|
|
||||||
summary: List a user's active device sessions
|
|
||||||
tags:
|
|
||||||
- admin
|
|
||||||
/api/v1/admin/users/{user_id}/sessions/{id}:
|
|
||||||
delete:
|
|
||||||
parameters:
|
|
||||||
- description: User ID
|
|
||||||
in: path
|
|
||||||
name: user_id
|
|
||||||
required: true
|
|
||||||
type: integer
|
|
||||||
- description: Session UUID
|
|
||||||
in: path
|
|
||||||
name: id
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
responses:
|
|
||||||
"200":
|
|
||||||
description: OK
|
|
||||||
schema:
|
|
||||||
properties:
|
|
||||||
message:
|
|
||||||
type: string
|
|
||||||
type: object
|
|
||||||
"404":
|
|
||||||
description: Not Found
|
|
||||||
schema:
|
|
||||||
$ref: '#/definitions/domain.ErrorResponse'
|
|
||||||
security:
|
|
||||||
- Bearer: []
|
|
||||||
summary: Remove a user's active device session
|
|
||||||
tags:
|
|
||||||
- admin
|
|
||||||
/api/v1/admin/users/{user_id}/subscriptions:
|
/api/v1/admin/users/{user_id}/subscriptions:
|
||||||
get:
|
get:
|
||||||
description: Returns display status, active plans by category, full subscription
|
description: Returns display status, active plans by category, full subscription
|
||||||
|
|
@ -18291,44 +18227,6 @@ paths:
|
||||||
summary: Refresh token
|
summary: Refresh token
|
||||||
tags:
|
tags:
|
||||||
- auth
|
- auth
|
||||||
/api/v1/auth/sessions/replace:
|
|
||||||
post:
|
|
||||||
consumes:
|
|
||||||
- application/json
|
|
||||||
parameters:
|
|
||||||
- description: Session replacement challenge and active session ID
|
|
||||||
in: body
|
|
||||||
name: body
|
|
||||||
required: true
|
|
||||||
schema:
|
|
||||||
properties:
|
|
||||||
challenge_token:
|
|
||||||
type: string
|
|
||||||
session_id:
|
|
||||||
type: string
|
|
||||||
required:
|
|
||||||
- challenge_token
|
|
||||||
- session_id
|
|
||||||
type: object
|
|
||||||
produces:
|
|
||||||
- application/json
|
|
||||||
responses:
|
|
||||||
"200":
|
|
||||||
description: OK
|
|
||||||
schema:
|
|
||||||
properties:
|
|
||||||
data:
|
|
||||||
$ref: '#/definitions/handlers.loginUserRes'
|
|
||||||
message:
|
|
||||||
type: string
|
|
||||||
type: object
|
|
||||||
"401":
|
|
||||||
description: Unauthorized
|
|
||||||
schema:
|
|
||||||
$ref: '#/definitions/domain.ErrorResponse'
|
|
||||||
summary: Replace an active learner device session
|
|
||||||
tags:
|
|
||||||
- auth
|
|
||||||
/api/v1/catalog/courses:
|
/api/v1/catalog/courses:
|
||||||
get:
|
get:
|
||||||
description: 'Public discovery only: titles, descriptions, thumbnails, access
|
description: 'Public discovery only: titles, descriptions, thumbnails, access
|
||||||
|
|
@ -22440,63 +22338,6 @@ paths:
|
||||||
summary: Cancel my account deletion request
|
summary: Cancel my account deletion request
|
||||||
tags:
|
tags:
|
||||||
- user
|
- user
|
||||||
/api/v1/user/me/sessions:
|
|
||||||
get:
|
|
||||||
produces:
|
|
||||||
- application/json
|
|
||||||
responses:
|
|
||||||
"200":
|
|
||||||
description: OK
|
|
||||||
schema:
|
|
||||||
properties:
|
|
||||||
data:
|
|
||||||
items:
|
|
||||||
properties:
|
|
||||||
id:
|
|
||||||
type: string
|
|
||||||
is_current:
|
|
||||||
type: boolean
|
|
||||||
label:
|
|
||||||
type: string
|
|
||||||
last_seen_at:
|
|
||||||
type: string
|
|
||||||
platform:
|
|
||||||
type: string
|
|
||||||
type: object
|
|
||||||
type: array
|
|
||||||
message:
|
|
||||||
type: string
|
|
||||||
type: object
|
|
||||||
security:
|
|
||||||
- Bearer: []
|
|
||||||
summary: List the current learner's active device sessions
|
|
||||||
tags:
|
|
||||||
- user
|
|
||||||
/api/v1/user/me/sessions/{id}:
|
|
||||||
delete:
|
|
||||||
parameters:
|
|
||||||
- description: Session UUID
|
|
||||||
in: path
|
|
||||||
name: id
|
|
||||||
required: true
|
|
||||||
type: string
|
|
||||||
responses:
|
|
||||||
"200":
|
|
||||||
description: OK
|
|
||||||
schema:
|
|
||||||
properties:
|
|
||||||
message:
|
|
||||||
type: string
|
|
||||||
type: object
|
|
||||||
"404":
|
|
||||||
description: Not Found
|
|
||||||
schema:
|
|
||||||
$ref: '#/definitions/domain.ErrorResponse'
|
|
||||||
security:
|
|
||||||
- Bearer: []
|
|
||||||
summary: Remove one of the current learner's device sessions
|
|
||||||
tags:
|
|
||||||
- user
|
|
||||||
/api/v1/user/register:
|
/api/v1/user/register:
|
||||||
post:
|
post:
|
||||||
consumes:
|
consumes:
|
||||||
|
|
|
||||||
|
|
@ -8,13 +8,12 @@ package dbgen
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
)
|
)
|
||||||
|
|
||||||
const CreateRefreshToken = `-- name: CreateRefreshToken :exec
|
const CreateRefreshToken = `-- name: CreateRefreshToken :exec
|
||||||
INSERT INTO refresh_tokens (user_id, token, expires_at, created_at, revoked, session_id)
|
INSERT INTO refresh_tokens (user_id, token, expires_at, created_at, revoked)
|
||||||
VALUES ($1, $2, $3, $4, $5, $6)
|
VALUES ($1, $2, $3, $4, $5)
|
||||||
`
|
`
|
||||||
|
|
||||||
type CreateRefreshTokenParams struct {
|
type CreateRefreshTokenParams struct {
|
||||||
|
|
@ -23,7 +22,6 @@ type CreateRefreshTokenParams struct {
|
||||||
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
|
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
|
||||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||||
Revoked bool `json:"revoked"`
|
Revoked bool `json:"revoked"`
|
||||||
SessionID uuid.NullUUID `json:"session_id"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (q *Queries) CreateRefreshToken(ctx context.Context, arg CreateRefreshTokenParams) error {
|
func (q *Queries) CreateRefreshToken(ctx context.Context, arg CreateRefreshTokenParams) error {
|
||||||
|
|
@ -33,13 +31,12 @@ func (q *Queries) CreateRefreshToken(ctx context.Context, arg CreateRefreshToken
|
||||||
arg.ExpiresAt,
|
arg.ExpiresAt,
|
||||||
arg.CreatedAt,
|
arg.CreatedAt,
|
||||||
arg.Revoked,
|
arg.Revoked,
|
||||||
arg.SessionID,
|
|
||||||
)
|
)
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
const GetRefreshToken = `-- name: GetRefreshToken :one
|
const GetRefreshToken = `-- name: GetRefreshToken :one
|
||||||
SELECT id, user_id, token, expires_at, revoked, created_at, session_id
|
SELECT id, user_id, token, expires_at, revoked, created_at
|
||||||
FROM refresh_tokens
|
FROM refresh_tokens
|
||||||
WHERE token = $1
|
WHERE token = $1
|
||||||
`
|
`
|
||||||
|
|
@ -54,13 +51,12 @@ func (q *Queries) GetRefreshToken(ctx context.Context, token string) (RefreshTok
|
||||||
&i.ExpiresAt,
|
&i.ExpiresAt,
|
||||||
&i.Revoked,
|
&i.Revoked,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SessionID,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
||||||
const GetRefreshTokenByUserID = `-- name: GetRefreshTokenByUserID :one
|
const GetRefreshTokenByUserID = `-- name: GetRefreshTokenByUserID :one
|
||||||
SELECT id, user_id, token, expires_at, revoked, created_at, session_id
|
SELECT id, user_id, token, expires_at, revoked, created_at
|
||||||
FROM refresh_tokens
|
FROM refresh_tokens
|
||||||
WHERE user_id = $1
|
WHERE user_id = $1
|
||||||
`
|
`
|
||||||
|
|
@ -75,7 +71,6 @@ func (q *Queries) GetRefreshTokenByUserID(ctx context.Context, userID int64) (Re
|
||||||
&i.ExpiresAt,
|
&i.ExpiresAt,
|
||||||
&i.Revoked,
|
&i.Revoked,
|
||||||
&i.CreatedAt,
|
&i.CreatedAt,
|
||||||
&i.SessionID,
|
|
||||||
)
|
)
|
||||||
return i, err
|
return i, err
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -5,7 +5,6 @@
|
||||||
package dbgen
|
package dbgen
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
"github.com/jackc/pgx/v5/pgtype"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -118,18 +117,6 @@ type Device struct {
|
||||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type DeviceLoginChallenge struct {
|
|
||||||
ID uuid.UUID `json:"id"`
|
|
||||||
UserID int64 `json:"user_id"`
|
|
||||||
TokenHash []byte `json:"token_hash"`
|
|
||||||
DeviceKey pgtype.Text `json:"device_key"`
|
|
||||||
DeviceLabel string `json:"device_label"`
|
|
||||||
Platform string `json:"platform"`
|
|
||||||
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
|
|
||||||
UsedAt pgtype.Timestamptz `json:"used_at"`
|
|
||||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type EmailTemplate struct {
|
type EmailTemplate struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
Slug string `json:"slug"`
|
Slug string `json:"slug"`
|
||||||
|
|
@ -636,7 +623,6 @@ type RefreshToken struct {
|
||||||
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
|
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
|
||||||
Revoked bool `json:"revoked"`
|
Revoked bool `json:"revoked"`
|
||||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||||
SessionID uuid.NullUUID `json:"session_id"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ReportedIssue struct {
|
type ReportedIssue struct {
|
||||||
|
|
@ -863,19 +849,6 @@ type UserReferral struct {
|
||||||
AttributedUntil pgtype.Timestamptz `json:"attributed_until"`
|
AttributedUntil pgtype.Timestamptz `json:"attributed_until"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type UserSession struct {
|
|
||||||
ID uuid.UUID `json:"id"`
|
|
||||||
UserID int64 `json:"user_id"`
|
|
||||||
DeviceKey pgtype.Text `json:"device_key"`
|
|
||||||
DeviceLabel string `json:"device_label"`
|
|
||||||
Platform string `json:"platform"`
|
|
||||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
|
||||||
LastSeenAt pgtype.Timestamptz `json:"last_seen_at"`
|
|
||||||
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
|
|
||||||
RevokedAt pgtype.Timestamptz `json:"revoked_at"`
|
|
||||||
RevokedReason pgtype.Text `json:"revoked_reason"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type UserSubscription struct {
|
type UserSubscription struct {
|
||||||
ID int64 `json:"id"`
|
ID int64 `json:"id"`
|
||||||
UserID int64 `json:"user_id"`
|
UserID int64 `json:"user_id"`
|
||||||
|
|
|
||||||
|
|
@ -1,591 +0,0 @@
|
||||||
// Code generated by sqlc. DO NOT EDIT.
|
|
||||||
// versions:
|
|
||||||
// sqlc v1.30.0
|
|
||||||
// source: user_sessions.sql
|
|
||||||
|
|
||||||
package dbgen
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
|
||||||
)
|
|
||||||
|
|
||||||
const AttachRefreshTokenToSession = `-- name: AttachRefreshTokenToSession :exec
|
|
||||||
UPDATE refresh_tokens SET session_id = $2 WHERE id = $1 AND session_id IS NULL
|
|
||||||
`
|
|
||||||
|
|
||||||
type AttachRefreshTokenToSessionParams struct {
|
|
||||||
ID int64 `json:"id"`
|
|
||||||
SessionID uuid.NullUUID `json:"session_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) AttachRefreshTokenToSession(ctx context.Context, arg AttachRefreshTokenToSessionParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, AttachRefreshTokenToSession, arg.ID, arg.SessionID)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const CountActiveUserSessions = `-- name: CountActiveUserSessions :one
|
|
||||||
SELECT COUNT(*)
|
|
||||||
FROM user_sessions
|
|
||||||
WHERE user_id = $1 AND revoked_at IS NULL AND expires_at > NOW()
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) CountActiveUserSessions(ctx context.Context, userID int64) (int64, error) {
|
|
||||||
row := q.db.QueryRow(ctx, CountActiveUserSessions, userID)
|
|
||||||
var count int64
|
|
||||||
err := row.Scan(&count)
|
|
||||||
return count, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const CreateDeviceLoginChallenge = `-- name: CreateDeviceLoginChallenge :exec
|
|
||||||
INSERT INTO device_login_challenges
|
|
||||||
(user_id, token_hash, device_key, device_label, platform, expires_at)
|
|
||||||
VALUES ($1, $2, $3, $4, $5, $6)
|
|
||||||
`
|
|
||||||
|
|
||||||
type CreateDeviceLoginChallengeParams struct {
|
|
||||||
UserID int64 `json:"user_id"`
|
|
||||||
TokenHash []byte `json:"token_hash"`
|
|
||||||
DeviceKey pgtype.Text `json:"device_key"`
|
|
||||||
DeviceLabel string `json:"device_label"`
|
|
||||||
Platform string `json:"platform"`
|
|
||||||
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) CreateDeviceLoginChallenge(ctx context.Context, arg CreateDeviceLoginChallengeParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, CreateDeviceLoginChallenge,
|
|
||||||
arg.UserID,
|
|
||||||
arg.TokenHash,
|
|
||||||
arg.DeviceKey,
|
|
||||||
arg.DeviceLabel,
|
|
||||||
arg.Platform,
|
|
||||||
arg.ExpiresAt,
|
|
||||||
)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const CreateRefreshTokenForSession = `-- name: CreateRefreshTokenForSession :exec
|
|
||||||
INSERT INTO refresh_tokens (user_id, token, expires_at, created_at, revoked, session_id)
|
|
||||||
VALUES ($1, $2, $3, $4, FALSE, $5)
|
|
||||||
`
|
|
||||||
|
|
||||||
type CreateRefreshTokenForSessionParams struct {
|
|
||||||
UserID int64 `json:"user_id"`
|
|
||||||
Token string `json:"token"`
|
|
||||||
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
|
|
||||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
|
||||||
SessionID uuid.NullUUID `json:"session_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) CreateRefreshTokenForSession(ctx context.Context, arg CreateRefreshTokenForSessionParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, CreateRefreshTokenForSession,
|
|
||||||
arg.UserID,
|
|
||||||
arg.Token,
|
|
||||||
arg.ExpiresAt,
|
|
||||||
arg.CreatedAt,
|
|
||||||
arg.SessionID,
|
|
||||||
)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const CreateUserSession = `-- name: CreateUserSession :one
|
|
||||||
INSERT INTO user_sessions (user_id, device_key, device_label, platform, expires_at)
|
|
||||||
VALUES ($1, $2, $3, $4, $5)
|
|
||||||
RETURNING id, user_id, device_key, device_label, platform, created_at, last_seen_at, expires_at, revoked_at, revoked_reason
|
|
||||||
`
|
|
||||||
|
|
||||||
type CreateUserSessionParams struct {
|
|
||||||
UserID int64 `json:"user_id"`
|
|
||||||
DeviceKey pgtype.Text `json:"device_key"`
|
|
||||||
DeviceLabel string `json:"device_label"`
|
|
||||||
Platform string `json:"platform"`
|
|
||||||
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) CreateUserSession(ctx context.Context, arg CreateUserSessionParams) (UserSession, error) {
|
|
||||||
row := q.db.QueryRow(ctx, CreateUserSession,
|
|
||||||
arg.UserID,
|
|
||||||
arg.DeviceKey,
|
|
||||||
arg.DeviceLabel,
|
|
||||||
arg.Platform,
|
|
||||||
arg.ExpiresAt,
|
|
||||||
)
|
|
||||||
var i UserSession
|
|
||||||
err := row.Scan(
|
|
||||||
&i.ID,
|
|
||||||
&i.UserID,
|
|
||||||
&i.DeviceKey,
|
|
||||||
&i.DeviceLabel,
|
|
||||||
&i.Platform,
|
|
||||||
&i.CreatedAt,
|
|
||||||
&i.LastSeenAt,
|
|
||||||
&i.ExpiresAt,
|
|
||||||
&i.RevokedAt,
|
|
||||||
&i.RevokedReason,
|
|
||||||
)
|
|
||||||
return i, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const GetActiveUserSession = `-- name: GetActiveUserSession :one
|
|
||||||
SELECT id, user_id, device_key, device_label, platform, created_at, last_seen_at, expires_at, revoked_at, revoked_reason
|
|
||||||
FROM user_sessions
|
|
||||||
WHERE id = $1 AND revoked_at IS NULL AND expires_at > NOW()
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) GetActiveUserSession(ctx context.Context, id uuid.UUID) (UserSession, error) {
|
|
||||||
row := q.db.QueryRow(ctx, GetActiveUserSession, id)
|
|
||||||
var i UserSession
|
|
||||||
err := row.Scan(
|
|
||||||
&i.ID,
|
|
||||||
&i.UserID,
|
|
||||||
&i.DeviceKey,
|
|
||||||
&i.DeviceLabel,
|
|
||||||
&i.Platform,
|
|
||||||
&i.CreatedAt,
|
|
||||||
&i.LastSeenAt,
|
|
||||||
&i.ExpiresAt,
|
|
||||||
&i.RevokedAt,
|
|
||||||
&i.RevokedReason,
|
|
||||||
)
|
|
||||||
return i, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const GetActiveUserSessionForUser = `-- name: GetActiveUserSessionForUser :one
|
|
||||||
SELECT id, user_id, device_key, device_label, platform, created_at, last_seen_at, expires_at, revoked_at, revoked_reason
|
|
||||||
FROM user_sessions
|
|
||||||
WHERE id = $1 AND user_id = $2 AND revoked_at IS NULL AND expires_at > NOW()
|
|
||||||
`
|
|
||||||
|
|
||||||
type GetActiveUserSessionForUserParams struct {
|
|
||||||
ID uuid.UUID `json:"id"`
|
|
||||||
UserID int64 `json:"user_id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) GetActiveUserSessionForUser(ctx context.Context, arg GetActiveUserSessionForUserParams) (UserSession, error) {
|
|
||||||
row := q.db.QueryRow(ctx, GetActiveUserSessionForUser, arg.ID, arg.UserID)
|
|
||||||
var i UserSession
|
|
||||||
err := row.Scan(
|
|
||||||
&i.ID,
|
|
||||||
&i.UserID,
|
|
||||||
&i.DeviceKey,
|
|
||||||
&i.DeviceLabel,
|
|
||||||
&i.Platform,
|
|
||||||
&i.CreatedAt,
|
|
||||||
&i.LastSeenAt,
|
|
||||||
&i.ExpiresAt,
|
|
||||||
&i.RevokedAt,
|
|
||||||
&i.RevokedReason,
|
|
||||||
)
|
|
||||||
return i, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const GetDeviceLoginChallengeForUpdate = `-- name: GetDeviceLoginChallengeForUpdate :one
|
|
||||||
SELECT id, user_id, token_hash, device_key, device_label, platform, expires_at, used_at, created_at
|
|
||||||
FROM device_login_challenges
|
|
||||||
WHERE token_hash = $1
|
|
||||||
FOR UPDATE
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) GetDeviceLoginChallengeForUpdate(ctx context.Context, tokenHash []byte) (DeviceLoginChallenge, error) {
|
|
||||||
row := q.db.QueryRow(ctx, GetDeviceLoginChallengeForUpdate, tokenHash)
|
|
||||||
var i DeviceLoginChallenge
|
|
||||||
err := row.Scan(
|
|
||||||
&i.ID,
|
|
||||||
&i.UserID,
|
|
||||||
&i.TokenHash,
|
|
||||||
&i.DeviceKey,
|
|
||||||
&i.DeviceLabel,
|
|
||||||
&i.Platform,
|
|
||||||
&i.ExpiresAt,
|
|
||||||
&i.UsedAt,
|
|
||||||
&i.CreatedAt,
|
|
||||||
)
|
|
||||||
return i, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const GetRefreshTokenForUpdate = `-- name: GetRefreshTokenForUpdate :one
|
|
||||||
SELECT id, user_id, token, expires_at, revoked, created_at, session_id FROM refresh_tokens WHERE token = $1 FOR UPDATE
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) GetRefreshTokenForUpdate(ctx context.Context, token string) (RefreshToken, error) {
|
|
||||||
row := q.db.QueryRow(ctx, GetRefreshTokenForUpdate, token)
|
|
||||||
var i RefreshToken
|
|
||||||
err := row.Scan(
|
|
||||||
&i.ID,
|
|
||||||
&i.UserID,
|
|
||||||
&i.Token,
|
|
||||||
&i.ExpiresAt,
|
|
||||||
&i.Revoked,
|
|
||||||
&i.CreatedAt,
|
|
||||||
&i.SessionID,
|
|
||||||
)
|
|
||||||
return i, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const InvalidateDeviceChallengesForRoleExcludingUser = `-- name: InvalidateDeviceChallengesForRoleExcludingUser :exec
|
|
||||||
UPDATE device_login_challenges
|
|
||||||
SET used_at = NOW()
|
|
||||||
WHERE used_at IS NULL AND user_id IN (
|
|
||||||
SELECT u.id FROM users AS u WHERE u.role = $1 AND u.id <> $2
|
|
||||||
)
|
|
||||||
`
|
|
||||||
|
|
||||||
type InvalidateDeviceChallengesForRoleExcludingUserParams struct {
|
|
||||||
Role string `json:"role"`
|
|
||||||
ID int64 `json:"id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) InvalidateDeviceChallengesForRoleExcludingUser(ctx context.Context, arg InvalidateDeviceChallengesForRoleExcludingUserParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, InvalidateDeviceChallengesForRoleExcludingUser, arg.Role, arg.ID)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const InvalidateUserDeviceChallenges = `-- name: InvalidateUserDeviceChallenges :exec
|
|
||||||
UPDATE device_login_challenges
|
|
||||||
SET used_at = NOW()
|
|
||||||
WHERE user_id = $1 AND used_at IS NULL
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) InvalidateUserDeviceChallenges(ctx context.Context, userID int64) error {
|
|
||||||
_, err := q.db.Exec(ctx, InvalidateUserDeviceChallenges, userID)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const ListActiveUserSessions = `-- name: ListActiveUserSessions :many
|
|
||||||
SELECT id, user_id, device_key, device_label, platform, created_at, last_seen_at, expires_at, revoked_at, revoked_reason
|
|
||||||
FROM user_sessions
|
|
||||||
WHERE user_id = $1 AND revoked_at IS NULL AND expires_at > NOW()
|
|
||||||
ORDER BY last_seen_at DESC, created_at DESC, id
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) ListActiveUserSessions(ctx context.Context, userID int64) ([]UserSession, error) {
|
|
||||||
rows, err := q.db.Query(ctx, ListActiveUserSessions, userID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var items []UserSession
|
|
||||||
for rows.Next() {
|
|
||||||
var i UserSession
|
|
||||||
if err := rows.Scan(
|
|
||||||
&i.ID,
|
|
||||||
&i.UserID,
|
|
||||||
&i.DeviceKey,
|
|
||||||
&i.DeviceLabel,
|
|
||||||
&i.Platform,
|
|
||||||
&i.CreatedAt,
|
|
||||||
&i.LastSeenAt,
|
|
||||||
&i.ExpiresAt,
|
|
||||||
&i.RevokedAt,
|
|
||||||
&i.RevokedReason,
|
|
||||||
); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
items = append(items, i)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return items, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const ListUserIDsForRoleExcludingUser = `-- name: ListUserIDsForRoleExcludingUser :many
|
|
||||||
SELECT id
|
|
||||||
FROM users
|
|
||||||
WHERE role = $1 AND id <> $2
|
|
||||||
ORDER BY id
|
|
||||||
`
|
|
||||||
|
|
||||||
type ListUserIDsForRoleExcludingUserParams struct {
|
|
||||||
Role string `json:"role"`
|
|
||||||
ID int64 `json:"id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) ListUserIDsForRoleExcludingUser(ctx context.Context, arg ListUserIDsForRoleExcludingUserParams) ([]int64, error) {
|
|
||||||
rows, err := q.db.Query(ctx, ListUserIDsForRoleExcludingUser, arg.Role, arg.ID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
defer rows.Close()
|
|
||||||
var items []int64
|
|
||||||
for rows.Next() {
|
|
||||||
var id int64
|
|
||||||
if err := rows.Scan(&id); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
items = append(items, id)
|
|
||||||
}
|
|
||||||
if err := rows.Err(); err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return items, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
const LockUserSessions = `-- name: LockUserSessions :exec
|
|
||||||
SELECT pg_advisory_xact_lock($1)
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) LockUserSessions(ctx context.Context, pgAdvisoryXactLock int64) error {
|
|
||||||
_, err := q.db.Exec(ctx, LockUserSessions, pgAdvisoryXactLock)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const ResolveDeviceLoginChallengeUserID = `-- name: ResolveDeviceLoginChallengeUserID :one
|
|
||||||
SELECT user_id
|
|
||||||
FROM device_login_challenges
|
|
||||||
WHERE token_hash = $1
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) ResolveDeviceLoginChallengeUserID(ctx context.Context, tokenHash []byte) (int64, error) {
|
|
||||||
row := q.db.QueryRow(ctx, ResolveDeviceLoginChallengeUserID, tokenHash)
|
|
||||||
var user_id int64
|
|
||||||
err := row.Scan(&user_id)
|
|
||||||
return user_id, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const ResolveRefreshTokenUserID = `-- name: ResolveRefreshTokenUserID :one
|
|
||||||
SELECT user_id
|
|
||||||
FROM refresh_tokens
|
|
||||||
WHERE token = $1
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) ResolveRefreshTokenUserID(ctx context.Context, token string) (int64, error) {
|
|
||||||
row := q.db.QueryRow(ctx, ResolveRefreshTokenUserID, token)
|
|
||||||
var user_id int64
|
|
||||||
err := row.Scan(&user_id)
|
|
||||||
return user_id, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const RevokeActiveSessionByDeviceKey = `-- name: RevokeActiveSessionByDeviceKey :exec
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET revoked_at = NOW(), revoked_reason = 'device_relogin'
|
|
||||||
WHERE user_id = $1 AND device_key = $2 AND revoked_at IS NULL
|
|
||||||
`
|
|
||||||
|
|
||||||
type RevokeActiveSessionByDeviceKeyParams struct {
|
|
||||||
UserID int64 `json:"user_id"`
|
|
||||||
DeviceKey pgtype.Text `json:"device_key"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) RevokeActiveSessionByDeviceKey(ctx context.Context, arg RevokeActiveSessionByDeviceKeyParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, RevokeActiveSessionByDeviceKey, arg.UserID, arg.DeviceKey)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const RevokeAllUserRefreshTokens = `-- name: RevokeAllUserRefreshTokens :exec
|
|
||||||
UPDATE refresh_tokens SET revoked = TRUE WHERE user_id = $1 AND revoked = FALSE
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) RevokeAllUserRefreshTokens(ctx context.Context, userID int64) error {
|
|
||||||
_, err := q.db.Exec(ctx, RevokeAllUserRefreshTokens, userID)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const RevokeAllUserSessions = `-- name: RevokeAllUserSessions :exec
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET revoked_at = NOW(), revoked_reason = $2
|
|
||||||
WHERE user_id = $1 AND revoked_at IS NULL
|
|
||||||
`
|
|
||||||
|
|
||||||
type RevokeAllUserSessionsParams struct {
|
|
||||||
UserID int64 `json:"user_id"`
|
|
||||||
RevokedReason pgtype.Text `json:"revoked_reason"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) RevokeAllUserSessions(ctx context.Context, arg RevokeAllUserSessionsParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, RevokeAllUserSessions, arg.UserID, arg.RevokedReason)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const RevokeExcessUserSessionRefreshTokens = `-- name: RevokeExcessUserSessionRefreshTokens :exec
|
|
||||||
WITH excess AS (
|
|
||||||
SELECT us.id
|
|
||||||
FROM user_sessions AS us
|
|
||||||
WHERE us.user_id = $1
|
|
||||||
AND us.id <> $2
|
|
||||||
AND us.revoked_at IS NULL
|
|
||||||
AND us.expires_at > NOW()
|
|
||||||
ORDER BY us.last_seen_at DESC, us.created_at DESC, us.id
|
|
||||||
OFFSET GREATEST($3::bigint - 1, 0)
|
|
||||||
)
|
|
||||||
UPDATE refresh_tokens
|
|
||||||
SET revoked = TRUE
|
|
||||||
WHERE revoked = FALSE AND session_id IN (SELECT id FROM excess)
|
|
||||||
`
|
|
||||||
|
|
||||||
type RevokeExcessUserSessionRefreshTokensParams struct {
|
|
||||||
TargetUserID int64 `json:"target_user_id"`
|
|
||||||
KeepSessionID uuid.UUID `json:"keep_session_id"`
|
|
||||||
MaxDevices int64 `json:"max_devices"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) RevokeExcessUserSessionRefreshTokens(ctx context.Context, arg RevokeExcessUserSessionRefreshTokensParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, RevokeExcessUserSessionRefreshTokens, arg.TargetUserID, arg.KeepSessionID, arg.MaxDevices)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const RevokeExcessUserSessions = `-- name: RevokeExcessUserSessions :exec
|
|
||||||
WITH excess AS (
|
|
||||||
SELECT us.id
|
|
||||||
FROM user_sessions AS us
|
|
||||||
WHERE us.user_id = $1
|
|
||||||
AND us.id <> $2
|
|
||||||
AND us.revoked_at IS NULL
|
|
||||||
AND us.expires_at > NOW()
|
|
||||||
ORDER BY us.last_seen_at DESC, us.created_at DESC, us.id
|
|
||||||
OFFSET GREATEST($3::bigint - 1, 0)
|
|
||||||
)
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET revoked_at = NOW(), revoked_reason = 'over_device_limit'
|
|
||||||
WHERE id IN (SELECT id FROM excess)
|
|
||||||
`
|
|
||||||
|
|
||||||
type RevokeExcessUserSessionsParams struct {
|
|
||||||
TargetUserID int64 `json:"target_user_id"`
|
|
||||||
KeepSessionID uuid.UUID `json:"keep_session_id"`
|
|
||||||
MaxDevices int64 `json:"max_devices"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) RevokeExcessUserSessions(ctx context.Context, arg RevokeExcessUserSessionsParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, RevokeExcessUserSessions, arg.TargetUserID, arg.KeepSessionID, arg.MaxDevices)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const RevokeRefreshTokensByDeviceKey = `-- name: RevokeRefreshTokensByDeviceKey :exec
|
|
||||||
UPDATE refresh_tokens
|
|
||||||
SET revoked = TRUE
|
|
||||||
WHERE revoked = FALSE AND session_id IN (
|
|
||||||
SELECT us.id FROM user_sessions AS us
|
|
||||||
WHERE us.user_id = $1 AND us.device_key = $2 AND us.revoked_at IS NULL
|
|
||||||
)
|
|
||||||
`
|
|
||||||
|
|
||||||
type RevokeRefreshTokensByDeviceKeyParams struct {
|
|
||||||
UserID int64 `json:"user_id"`
|
|
||||||
DeviceKey pgtype.Text `json:"device_key"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) RevokeRefreshTokensByDeviceKey(ctx context.Context, arg RevokeRefreshTokensByDeviceKeyParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, RevokeRefreshTokensByDeviceKey, arg.UserID, arg.DeviceKey)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const RevokeRefreshTokensBySession = `-- name: RevokeRefreshTokensBySession :exec
|
|
||||||
UPDATE refresh_tokens SET revoked = TRUE WHERE session_id = $1 AND revoked = FALSE
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) RevokeRefreshTokensBySession(ctx context.Context, sessionID uuid.NullUUID) error {
|
|
||||||
_, err := q.db.Exec(ctx, RevokeRefreshTokensBySession, sessionID)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const RevokeRefreshTokensForRoleExcludingUser = `-- name: RevokeRefreshTokensForRoleExcludingUser :exec
|
|
||||||
UPDATE refresh_tokens
|
|
||||||
SET revoked = TRUE
|
|
||||||
WHERE revoked = FALSE AND user_id IN (
|
|
||||||
SELECT u.id FROM users AS u WHERE u.role = $1 AND u.id <> $2
|
|
||||||
)
|
|
||||||
`
|
|
||||||
|
|
||||||
type RevokeRefreshTokensForRoleExcludingUserParams struct {
|
|
||||||
Role string `json:"role"`
|
|
||||||
ID int64 `json:"id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) RevokeRefreshTokensForRoleExcludingUser(ctx context.Context, arg RevokeRefreshTokensForRoleExcludingUserParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, RevokeRefreshTokensForRoleExcludingUser, arg.Role, arg.ID)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const RevokeSessionsForRoleExcludingUser = `-- name: RevokeSessionsForRoleExcludingUser :exec
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET revoked_at = NOW(), revoked_reason = 'bulk_deactivation'
|
|
||||||
WHERE revoked_at IS NULL AND user_id IN (
|
|
||||||
SELECT u.id FROM users AS u WHERE u.role = $1 AND u.id <> $2
|
|
||||||
)
|
|
||||||
`
|
|
||||||
|
|
||||||
type RevokeSessionsForRoleExcludingUserParams struct {
|
|
||||||
Role string `json:"role"`
|
|
||||||
ID int64 `json:"id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) RevokeSessionsForRoleExcludingUser(ctx context.Context, arg RevokeSessionsForRoleExcludingUserParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, RevokeSessionsForRoleExcludingUser, arg.Role, arg.ID)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const RevokeUserSession = `-- name: RevokeUserSession :one
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET revoked_at = NOW(), revoked_reason = $2
|
|
||||||
WHERE id = $1 AND revoked_at IS NULL
|
|
||||||
RETURNING user_id
|
|
||||||
`
|
|
||||||
|
|
||||||
type RevokeUserSessionParams struct {
|
|
||||||
ID uuid.UUID `json:"id"`
|
|
||||||
RevokedReason pgtype.Text `json:"revoked_reason"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) RevokeUserSession(ctx context.Context, arg RevokeUserSessionParams) (int64, error) {
|
|
||||||
row := q.db.QueryRow(ctx, RevokeUserSession, arg.ID, arg.RevokedReason)
|
|
||||||
var user_id int64
|
|
||||||
err := row.Scan(&user_id)
|
|
||||||
return user_id, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const RevokeUserSessionForUser = `-- name: RevokeUserSessionForUser :one
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET revoked_at = NOW(), revoked_reason = $3
|
|
||||||
WHERE id = $1 AND user_id = $2 AND revoked_at IS NULL
|
|
||||||
RETURNING id
|
|
||||||
`
|
|
||||||
|
|
||||||
type RevokeUserSessionForUserParams struct {
|
|
||||||
ID uuid.UUID `json:"id"`
|
|
||||||
UserID int64 `json:"user_id"`
|
|
||||||
RevokedReason pgtype.Text `json:"revoked_reason"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) RevokeUserSessionForUser(ctx context.Context, arg RevokeUserSessionForUserParams) (uuid.UUID, error) {
|
|
||||||
row := q.db.QueryRow(ctx, RevokeUserSessionForUser, arg.ID, arg.UserID, arg.RevokedReason)
|
|
||||||
var id uuid.UUID
|
|
||||||
err := row.Scan(&id)
|
|
||||||
return id, err
|
|
||||||
}
|
|
||||||
|
|
||||||
const RotateRefreshToken = `-- name: RotateRefreshToken :exec
|
|
||||||
UPDATE refresh_tokens SET revoked = TRUE WHERE id = $1 AND revoked = FALSE
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) RotateRefreshToken(ctx context.Context, id int64) error {
|
|
||||||
_, err := q.db.Exec(ctx, RotateRefreshToken, id)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const TouchUserSession = `-- name: TouchUserSession :exec
|
|
||||||
UPDATE user_sessions
|
|
||||||
SET last_seen_at = NOW(), expires_at = $2
|
|
||||||
WHERE id = $1 AND revoked_at IS NULL AND expires_at > NOW()
|
|
||||||
`
|
|
||||||
|
|
||||||
type TouchUserSessionParams struct {
|
|
||||||
ID uuid.UUID `json:"id"`
|
|
||||||
ExpiresAt pgtype.Timestamptz `json:"expires_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func (q *Queries) TouchUserSession(ctx context.Context, arg TouchUserSessionParams) error {
|
|
||||||
_, err := q.db.Exec(ctx, TouchUserSession, arg.ID, arg.ExpiresAt)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
const UseDeviceLoginChallenge = `-- name: UseDeviceLoginChallenge :exec
|
|
||||||
UPDATE device_login_challenges SET used_at = NOW() WHERE id = $1 AND used_at IS NULL
|
|
||||||
`
|
|
||||||
|
|
||||||
func (q *Queries) UseDeviceLoginChallenge(ctx context.Context, id uuid.UUID) error {
|
|
||||||
_, err := q.db.Exec(ctx, UseDeviceLoginChallenge, id)
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
@ -160,8 +160,6 @@ type Config struct {
|
||||||
DBResetReseedEnabled bool
|
DBResetReseedEnabled bool
|
||||||
DBResetReseedToken string
|
DBResetReseedToken string
|
||||||
DBSeedDir string
|
DBSeedDir string
|
||||||
MaxLearnerDevices int
|
|
||||||
DeviceLimitEnforced bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewConfig() (*Config, error) {
|
func NewConfig() (*Config, error) {
|
||||||
|
|
@ -189,17 +187,6 @@ func (c *Config) loadEnv() error {
|
||||||
c.GoogleOAuthClientSecret = os.Getenv("GOOGLE_OAUTH_CLIENT_SECRET")
|
c.GoogleOAuthClientSecret = os.Getenv("GOOGLE_OAUTH_CLIENT_SECRET")
|
||||||
c.GoogleOAuthRedirectURL = os.Getenv("GOOGLE_OAUTH_REDIRECT_URL")
|
c.GoogleOAuthRedirectURL = os.Getenv("GOOGLE_OAUTH_REDIRECT_URL")
|
||||||
c.AppleSignInClientIDs = os.Getenv("APPLE_SIGN_IN_CLIENT_IDS")
|
c.AppleSignInClientIDs = os.Getenv("APPLE_SIGN_IN_CLIENT_IDS")
|
||||||
c.MaxLearnerDevices = 2
|
|
||||||
if raw := strings.TrimSpace(os.Getenv("MAX_LEARNER_DEVICES")); raw != "" {
|
|
||||||
if value, parseErr := strconv.Atoi(raw); parseErr == nil && value > 0 {
|
|
||||||
c.MaxLearnerDevices = value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if raw := strings.TrimSpace(os.Getenv("DEVICE_LIMIT_ENFORCED")); raw != "" {
|
|
||||||
if value, parseErr := strconv.ParseBool(raw); parseErr == nil {
|
|
||||||
c.DeviceLimitEnforced = value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
c.APP_VERSION = os.Getenv("APP_VERSION")
|
c.APP_VERSION = os.Getenv("APP_VERSION")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,6 @@ package domain
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type GoogleUser struct {
|
type GoogleUser struct {
|
||||||
|
|
@ -28,7 +26,6 @@ type LoginSuccess struct {
|
||||||
UserId int64
|
UserId int64
|
||||||
Role Role
|
Role Role
|
||||||
RfToken string
|
RfToken string
|
||||||
SessionID uuid.UUID
|
|
||||||
IsNewAccount bool
|
IsNewAccount bool
|
||||||
// WelcomeEmailEligible is true when a learner completed email-based registration OTP verification.
|
// WelcomeEmailEligible is true when a learner completed email-based registration OTP verification.
|
||||||
WelcomeEmailEligible bool
|
WelcomeEmailEligible bool
|
||||||
|
|
@ -48,64 +45,6 @@ type RefreshToken struct {
|
||||||
ExpiresAt time.Time
|
ExpiresAt time.Time
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
Revoked bool
|
Revoked bool
|
||||||
SessionID uuid.NullUUID
|
|
||||||
}
|
|
||||||
|
|
||||||
type DeviceInfo struct {
|
|
||||||
Key string
|
|
||||||
Label string
|
|
||||||
Platform string
|
|
||||||
}
|
|
||||||
|
|
||||||
type UserSession struct {
|
|
||||||
ID uuid.UUID `json:"id"`
|
|
||||||
UserID int64 `json:"-"`
|
|
||||||
Label string `json:"label"`
|
|
||||||
Platform string `json:"platform"`
|
|
||||||
CreatedAt time.Time `json:"created_at,omitempty"`
|
|
||||||
LastSeenAt time.Time `json:"last_seen_at"`
|
|
||||||
ExpiresAt time.Time `json:"expires_at,omitempty"`
|
|
||||||
IsCurrent bool `json:"is_current"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type SessionIssueParams struct {
|
|
||||||
UserID int64
|
|
||||||
Device DeviceInfo
|
|
||||||
SessionExpires time.Time
|
|
||||||
RefreshToken string
|
|
||||||
RefreshExpires time.Time
|
|
||||||
MaxDevices int
|
|
||||||
EnforceLimit bool
|
|
||||||
ChallengeHash []byte
|
|
||||||
ChallengeExpiry time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
type SessionIssueResult struct {
|
|
||||||
Session UserSession
|
|
||||||
RefreshToken string
|
|
||||||
LimitReached bool
|
|
||||||
ChallengeToken string
|
|
||||||
ChallengeExpires time.Time
|
|
||||||
Devices []UserSession
|
|
||||||
}
|
|
||||||
|
|
||||||
type SessionReplaceParams struct {
|
|
||||||
ChallengeHash []byte
|
|
||||||
SessionID uuid.UUID
|
|
||||||
RefreshToken string
|
|
||||||
RefreshExpires time.Time
|
|
||||||
MaxDevices int
|
|
||||||
EnforceLimit bool
|
|
||||||
}
|
|
||||||
|
|
||||||
type SessionRefreshParams struct {
|
|
||||||
OldToken string
|
|
||||||
NewToken string
|
|
||||||
RefreshExpires time.Time
|
|
||||||
Device DeviceInfo
|
|
||||||
IsLearner bool
|
|
||||||
MaxDevices int
|
|
||||||
EnforceLimit bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// I used this because i was getting an error with the ValidInt64
|
// I used this because i was getting an error with the ValidInt64
|
||||||
|
|
|
||||||
|
|
@ -3,8 +3,6 @@ package ports
|
||||||
import (
|
import (
|
||||||
"Rezina-Backend/internal/domain"
|
"Rezina-Backend/internal/domain"
|
||||||
"context"
|
"context"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type TokenStore interface {
|
type TokenStore interface {
|
||||||
|
|
@ -13,16 +11,3 @@ type TokenStore interface {
|
||||||
GetRefreshTokenByUserID(ctx context.Context, id int64) (domain.RefreshToken, error)
|
GetRefreshTokenByUserID(ctx context.Context, id int64) (domain.RefreshToken, error)
|
||||||
RevokeRefreshToken(ctx context.Context, token string) error
|
RevokeRefreshToken(ctx context.Context, token string) error
|
||||||
}
|
}
|
||||||
|
|
||||||
type SessionStore interface {
|
|
||||||
IssueUserSession(ctx context.Context, params domain.SessionIssueParams) (domain.SessionIssueResult, error)
|
|
||||||
ReplaceUserSession(ctx context.Context, params domain.SessionReplaceParams) (domain.UserSession, error)
|
|
||||||
RotateSessionRefreshToken(ctx context.Context, params domain.SessionRefreshParams) (domain.RefreshToken, error)
|
|
||||||
LogoutSession(ctx context.Context, refreshToken string) error
|
|
||||||
IsUserSessionActive(ctx context.Context, sessionID uuid.UUID, userID int64) (bool, error)
|
|
||||||
ListUserSessions(ctx context.Context, userID int64) ([]domain.UserSession, error)
|
|
||||||
RevokeOwnUserSession(ctx context.Context, userID int64, sessionID uuid.UUID, reason string) error
|
|
||||||
RevokeUserSession(ctx context.Context, userID int64, sessionID uuid.UUID, reason string) error
|
|
||||||
RevokeAllUserSessionsAndTokens(ctx context.Context, userID int64, reason string) error
|
|
||||||
RevokeSessionsForRoleExcludingUser(ctx context.Context, role string, excludeUserID int64) error
|
|
||||||
}
|
|
||||||
|
|
|
||||||
|
|
@ -41,8 +41,7 @@ func (s *Store) CreateRefreshToken(ctx context.Context, rt domain.RefreshToken)
|
||||||
Time: createdAt,
|
Time: createdAt,
|
||||||
Valid: true,
|
Valid: true,
|
||||||
},
|
},
|
||||||
Revoked: rt.Revoked,
|
Revoked: rt.Revoked,
|
||||||
SessionID: rt.SessionID,
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -62,7 +61,6 @@ func (s *Store) GetRefreshToken(ctx context.Context, token string) (domain.Refre
|
||||||
CreatedAt: rf.CreatedAt.Time,
|
CreatedAt: rf.CreatedAt.Time,
|
||||||
ExpiresAt: rf.ExpiresAt.Time,
|
ExpiresAt: rf.ExpiresAt.Time,
|
||||||
Revoked: rf.Revoked,
|
Revoked: rf.Revoked,
|
||||||
SessionID: rf.SessionID,
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -82,7 +80,6 @@ func (s *Store) GetRefreshTokenByUserID(ctx context.Context, id int64) (domain.R
|
||||||
CreatedAt: rf.CreatedAt.Time,
|
CreatedAt: rf.CreatedAt.Time,
|
||||||
ExpiresAt: rf.ExpiresAt.Time,
|
ExpiresAt: rf.ExpiresAt.Time,
|
||||||
Revoked: rf.Revoked,
|
Revoked: rf.Revoked,
|
||||||
SessionID: rf.SessionID,
|
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,389 +0,0 @@
|
||||||
package repository
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
dbgen "Rezina-Backend/gen/db"
|
|
||||||
"Rezina-Backend/internal/domain"
|
|
||||||
"Rezina-Backend/internal/services/authentication"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/jackc/pgx/v5"
|
|
||||||
"github.com/jackc/pgx/v5/pgtype"
|
|
||||||
)
|
|
||||||
|
|
||||||
func pgText(value string) pgtype.Text {
|
|
||||||
return pgtype.Text{String: value, Valid: value != ""}
|
|
||||||
}
|
|
||||||
|
|
||||||
func pgTime(value time.Time) pgtype.Timestamptz {
|
|
||||||
return pgtype.Timestamptz{Time: value, Valid: true}
|
|
||||||
}
|
|
||||||
|
|
||||||
func nullableUUID(value uuid.UUID) uuid.NullUUID {
|
|
||||||
return uuid.NullUUID{UUID: value, Valid: value != uuid.Nil}
|
|
||||||
}
|
|
||||||
|
|
||||||
func mapUserSession(row dbgen.UserSession) domain.UserSession {
|
|
||||||
return domain.UserSession{
|
|
||||||
ID: row.ID, UserID: row.UserID, Label: row.DeviceLabel, Platform: row.Platform,
|
|
||||||
CreatedAt: row.CreatedAt.Time, LastSeenAt: row.LastSeenAt.Time, ExpiresAt: row.ExpiresAt.Time,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func listUserSessions(ctx context.Context, q *dbgen.Queries, userID int64) ([]domain.UserSession, error) {
|
|
||||||
rows, err := q.ListActiveUserSessions(ctx, userID)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
out := make([]domain.UserSession, 0, len(rows))
|
|
||||||
for _, row := range rows {
|
|
||||||
out = append(out, mapUserSession(row))
|
|
||||||
}
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func revokeMatchingDevice(ctx context.Context, q *dbgen.Queries, userID int64, deviceKey string) error {
|
|
||||||
if deviceKey == "" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
arg := dbgen.RevokeRefreshTokensByDeviceKeyParams{UserID: userID, DeviceKey: pgText(deviceKey)}
|
|
||||||
if err := q.RevokeRefreshTokensByDeviceKey(ctx, arg); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return q.RevokeActiveSessionByDeviceKey(ctx, dbgen.RevokeActiveSessionByDeviceKeyParams{
|
|
||||||
UserID: userID, DeviceKey: pgText(deviceKey),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func createSessionAndToken(ctx context.Context, q *dbgen.Queries, userID int64, device domain.DeviceInfo, token string, expires time.Time) (domain.UserSession, error) {
|
|
||||||
row, err := q.CreateUserSession(ctx, dbgen.CreateUserSessionParams{
|
|
||||||
UserID: userID, DeviceKey: pgText(device.Key), DeviceLabel: device.Label,
|
|
||||||
Platform: device.Platform, ExpiresAt: pgTime(expires),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return domain.UserSession{}, err
|
|
||||||
}
|
|
||||||
if err := q.CreateRefreshTokenForSession(ctx, dbgen.CreateRefreshTokenForSessionParams{
|
|
||||||
UserID: userID, Token: token, ExpiresAt: pgTime(expires), CreatedAt: pgTime(time.Now()),
|
|
||||||
SessionID: nullableUUID(row.ID),
|
|
||||||
}); err != nil {
|
|
||||||
return domain.UserSession{}, err
|
|
||||||
}
|
|
||||||
return mapUserSession(row), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func revokeExcessSessions(ctx context.Context, q *dbgen.Queries, userID int64, keepSessionID uuid.UUID, maxDevices int) error {
|
|
||||||
params := dbgen.RevokeExcessUserSessionRefreshTokensParams{
|
|
||||||
TargetUserID: userID, KeepSessionID: keepSessionID, MaxDevices: int64(maxDevices),
|
|
||||||
}
|
|
||||||
if err := q.RevokeExcessUserSessionRefreshTokens(ctx, params); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return q.RevokeExcessUserSessions(ctx, dbgen.RevokeExcessUserSessionsParams(params))
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) IssueUserSession(ctx context.Context, params domain.SessionIssueParams) (domain.SessionIssueResult, error) {
|
|
||||||
q, tx, err := s.BeginTx(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return domain.SessionIssueResult{}, err
|
|
||||||
}
|
|
||||||
defer tx.Rollback(ctx)
|
|
||||||
if err := q.LockUserSessions(ctx, params.UserID); err != nil {
|
|
||||||
return domain.SessionIssueResult{}, err
|
|
||||||
}
|
|
||||||
if err := revokeMatchingDevice(ctx, q, params.UserID, params.Device.Key); err != nil {
|
|
||||||
return domain.SessionIssueResult{}, err
|
|
||||||
}
|
|
||||||
count, err := q.CountActiveUserSessions(ctx, params.UserID)
|
|
||||||
if err != nil {
|
|
||||||
return domain.SessionIssueResult{}, err
|
|
||||||
}
|
|
||||||
if params.EnforceLimit && count >= int64(params.MaxDevices) {
|
|
||||||
if err := q.CreateDeviceLoginChallenge(ctx, dbgen.CreateDeviceLoginChallengeParams{
|
|
||||||
UserID: params.UserID, TokenHash: params.ChallengeHash, DeviceKey: pgText(params.Device.Key),
|
|
||||||
DeviceLabel: params.Device.Label, Platform: params.Device.Platform, ExpiresAt: pgTime(params.ChallengeExpiry),
|
|
||||||
}); err != nil {
|
|
||||||
return domain.SessionIssueResult{}, err
|
|
||||||
}
|
|
||||||
devices, err := listUserSessions(ctx, q, params.UserID)
|
|
||||||
if err != nil {
|
|
||||||
return domain.SessionIssueResult{}, err
|
|
||||||
}
|
|
||||||
if err := tx.Commit(ctx); err != nil {
|
|
||||||
return domain.SessionIssueResult{}, err
|
|
||||||
}
|
|
||||||
return domain.SessionIssueResult{LimitReached: true, ChallengeExpires: params.ChallengeExpiry, Devices: devices}, nil
|
|
||||||
}
|
|
||||||
session, err := createSessionAndToken(ctx, q, params.UserID, params.Device, params.RefreshToken, params.RefreshExpires)
|
|
||||||
if err != nil {
|
|
||||||
return domain.SessionIssueResult{}, err
|
|
||||||
}
|
|
||||||
if err := tx.Commit(ctx); err != nil {
|
|
||||||
return domain.SessionIssueResult{}, err
|
|
||||||
}
|
|
||||||
return domain.SessionIssueResult{Session: session}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) ReplaceUserSession(ctx context.Context, params domain.SessionReplaceParams) (domain.UserSession, error) {
|
|
||||||
q, tx, err := s.BeginTx(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return domain.UserSession{}, err
|
|
||||||
}
|
|
||||||
defer tx.Rollback(ctx)
|
|
||||||
userID, err := q.ResolveDeviceLoginChallengeUserID(ctx, params.ChallengeHash)
|
|
||||||
if err != nil {
|
|
||||||
return domain.UserSession{}, authentication.ErrInvalidDeviceChallenge
|
|
||||||
}
|
|
||||||
if err := q.LockUserSessions(ctx, userID); err != nil {
|
|
||||||
return domain.UserSession{}, err
|
|
||||||
}
|
|
||||||
challenge, err := q.GetDeviceLoginChallengeForUpdate(ctx, params.ChallengeHash)
|
|
||||||
if err != nil || challenge.UserID != userID {
|
|
||||||
return domain.UserSession{}, authentication.ErrInvalidDeviceChallenge
|
|
||||||
}
|
|
||||||
if challenge.UsedAt.Valid || !challenge.ExpiresAt.Valid || !challenge.ExpiresAt.Time.After(time.Now()) {
|
|
||||||
return domain.UserSession{}, authentication.ErrInvalidDeviceChallenge
|
|
||||||
}
|
|
||||||
if challenge.DeviceKey.Valid {
|
|
||||||
if err := revokeMatchingDevice(ctx, q, challenge.UserID, challenge.DeviceKey.String); err != nil {
|
|
||||||
return domain.UserSession{}, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if _, err := q.GetActiveUserSessionForUser(ctx, dbgen.GetActiveUserSessionForUserParams{ID: params.SessionID, UserID: challenge.UserID}); err != nil {
|
|
||||||
return domain.UserSession{}, authentication.ErrInvalidDeviceChallenge
|
|
||||||
}
|
|
||||||
if err := q.UseDeviceLoginChallenge(ctx, challenge.ID); err != nil {
|
|
||||||
return domain.UserSession{}, authentication.ErrInvalidDeviceChallenge
|
|
||||||
}
|
|
||||||
if err := q.RevokeRefreshTokensBySession(ctx, nullableUUID(params.SessionID)); err != nil {
|
|
||||||
return domain.UserSession{}, err
|
|
||||||
}
|
|
||||||
if _, err := q.RevokeUserSessionForUser(ctx, dbgen.RevokeUserSessionForUserParams{ID: params.SessionID, UserID: challenge.UserID, RevokedReason: pgText("device_replaced")}); err != nil {
|
|
||||||
return domain.UserSession{}, authentication.ErrInvalidDeviceChallenge
|
|
||||||
}
|
|
||||||
device := domain.DeviceInfo{Label: challenge.DeviceLabel, Platform: challenge.Platform}
|
|
||||||
if challenge.DeviceKey.Valid {
|
|
||||||
device.Key = challenge.DeviceKey.String
|
|
||||||
}
|
|
||||||
session, err := createSessionAndToken(ctx, q, challenge.UserID, device, params.RefreshToken, params.RefreshExpires)
|
|
||||||
if err != nil {
|
|
||||||
return domain.UserSession{}, err
|
|
||||||
}
|
|
||||||
if params.EnforceLimit {
|
|
||||||
if err := revokeExcessSessions(ctx, q, challenge.UserID, session.ID, params.MaxDevices); err != nil {
|
|
||||||
return domain.UserSession{}, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := tx.Commit(ctx); err != nil {
|
|
||||||
return domain.UserSession{}, err
|
|
||||||
}
|
|
||||||
return session, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) RotateSessionRefreshToken(ctx context.Context, params domain.SessionRefreshParams) (domain.RefreshToken, error) {
|
|
||||||
q, tx, err := s.BeginTx(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
defer tx.Rollback(ctx)
|
|
||||||
userID, err := q.ResolveRefreshTokenUserID(ctx, params.OldToken)
|
|
||||||
if err != nil {
|
|
||||||
return domain.RefreshToken{}, authentication.ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
if err := q.LockUserSessions(ctx, userID); err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
old, err := q.GetRefreshTokenForUpdate(ctx, params.OldToken)
|
|
||||||
if err != nil || old.UserID != userID || old.Revoked || !old.ExpiresAt.Valid || !old.ExpiresAt.Time.After(time.Now()) {
|
|
||||||
return domain.RefreshToken{}, authentication.ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
sessionID := uuid.Nil
|
|
||||||
if old.SessionID.Valid {
|
|
||||||
session, err := q.GetActiveUserSessionForUser(ctx, dbgen.GetActiveUserSessionForUserParams{ID: old.SessionID.UUID, UserID: old.UserID})
|
|
||||||
if err != nil {
|
|
||||||
return domain.RefreshToken{}, authentication.ErrSessionRevoked
|
|
||||||
}
|
|
||||||
sessionID = session.ID
|
|
||||||
if params.IsLearner && params.EnforceLimit {
|
|
||||||
activeSessions, err := q.ListActiveUserSessions(ctx, old.UserID)
|
|
||||||
if err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
withinLimit := false
|
|
||||||
for i, activeSession := range activeSessions {
|
|
||||||
if i >= params.MaxDevices {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if activeSession.ID == sessionID {
|
|
||||||
withinLimit = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !withinLimit {
|
|
||||||
if err := q.RevokeRefreshTokensBySession(ctx, nullableUUID(sessionID)); err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
if _, err := q.RevokeUserSessionForUser(ctx, dbgen.RevokeUserSessionForUserParams{
|
|
||||||
ID: sessionID, UserID: old.UserID, RevokedReason: pgText("over_device_limit"),
|
|
||||||
}); err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
if err := tx.Commit(ctx); err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
return domain.RefreshToken{}, authentication.ErrSessionRevoked
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := q.TouchUserSession(ctx, dbgen.TouchUserSessionParams{ID: sessionID, ExpiresAt: pgTime(params.RefreshExpires)}); err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
} else if params.IsLearner {
|
|
||||||
if err := revokeMatchingDevice(ctx, q, old.UserID, params.Device.Key); err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
count, err := q.CountActiveUserSessions(ctx, old.UserID)
|
|
||||||
if err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
if params.EnforceLimit && count >= int64(params.MaxDevices) {
|
|
||||||
return domain.RefreshToken{}, authentication.ErrDeviceLimitReached
|
|
||||||
}
|
|
||||||
row, err := q.CreateUserSession(ctx, dbgen.CreateUserSessionParams{UserID: old.UserID, DeviceKey: pgText(params.Device.Key), DeviceLabel: params.Device.Label, Platform: params.Device.Platform, ExpiresAt: pgTime(params.RefreshExpires)})
|
|
||||||
if err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
sessionID = row.ID
|
|
||||||
}
|
|
||||||
if err := q.RotateRefreshToken(ctx, old.ID); err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
if err := q.CreateRefreshTokenForSession(ctx, dbgen.CreateRefreshTokenForSessionParams{UserID: old.UserID, Token: params.NewToken, ExpiresAt: pgTime(params.RefreshExpires), CreatedAt: pgTime(time.Now()), SessionID: nullableUUID(sessionID)}); err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
if err := tx.Commit(ctx); err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
return domain.RefreshToken{UserID: old.UserID, Token: params.NewToken, CreatedAt: time.Now(), ExpiresAt: params.RefreshExpires, SessionID: nullableUUID(sessionID)}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) LogoutSession(ctx context.Context, refreshToken string) error {
|
|
||||||
q, tx, err := s.BeginTx(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer tx.Rollback(ctx)
|
|
||||||
userID, err := q.ResolveRefreshTokenUserID(ctx, refreshToken)
|
|
||||||
if err != nil {
|
|
||||||
return authentication.ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
if err := q.LockUserSessions(ctx, userID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
token, err := q.GetRefreshTokenForUpdate(ctx, refreshToken)
|
|
||||||
if err != nil || token.UserID != userID || token.Revoked {
|
|
||||||
return authentication.ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
if err := q.RotateRefreshToken(ctx, token.ID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if token.SessionID.Valid {
|
|
||||||
_, err = q.RevokeUserSessionForUser(ctx, dbgen.RevokeUserSessionForUserParams{ID: token.SessionID.UUID, UserID: token.UserID, RevokedReason: pgText("logout")})
|
|
||||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := q.RevokeRefreshTokensBySession(ctx, token.SessionID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return tx.Commit(ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) IsUserSessionActive(ctx context.Context, sessionID uuid.UUID, userID int64) (bool, error) {
|
|
||||||
_, err := s.queries.GetActiveUserSessionForUser(ctx, dbgen.GetActiveUserSessionForUserParams{ID: sessionID, UserID: userID})
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return false, nil
|
|
||||||
}
|
|
||||||
return err == nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) ListUserSessions(ctx context.Context, userID int64) ([]domain.UserSession, error) {
|
|
||||||
return listUserSessions(ctx, s.queries, userID)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) RevokeOwnUserSession(ctx context.Context, userID int64, sessionID uuid.UUID, reason string) error {
|
|
||||||
q, tx, err := s.BeginTx(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer tx.Rollback(ctx)
|
|
||||||
if err := q.LockUserSessions(ctx, userID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if _, err := q.RevokeUserSessionForUser(ctx, dbgen.RevokeUserSessionForUserParams{ID: sessionID, UserID: userID, RevokedReason: pgText(reason)}); err != nil {
|
|
||||||
if errors.Is(err, pgx.ErrNoRows) {
|
|
||||||
return authentication.ErrSessionNotFound
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := q.RevokeRefreshTokensBySession(ctx, nullableUUID(sessionID)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return tx.Commit(ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) RevokeUserSession(ctx context.Context, userID int64, sessionID uuid.UUID, reason string) error {
|
|
||||||
return s.RevokeOwnUserSession(ctx, userID, sessionID, reason)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) RevokeAllUserSessionsAndTokens(ctx context.Context, userID int64, reason string) error {
|
|
||||||
q, tx, err := s.BeginTx(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer tx.Rollback(ctx)
|
|
||||||
if err := q.LockUserSessions(ctx, userID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := q.RevokeAllUserSessions(ctx, dbgen.RevokeAllUserSessionsParams{UserID: userID, RevokedReason: pgText(reason)}); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := q.RevokeAllUserRefreshTokens(ctx, userID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
// A challenge issued before a password reset or suspension must not outlive it.
|
|
||||||
if err := q.InvalidateUserDeviceChallenges(ctx, userID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return tx.Commit(ctx)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) RevokeSessionsForRoleExcludingUser(ctx context.Context, role string, excludeUserID int64) error {
|
|
||||||
q, tx, err := s.BeginTx(ctx)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer tx.Rollback(ctx)
|
|
||||||
params := dbgen.RevokeSessionsForRoleExcludingUserParams{Role: role, ID: excludeUserID}
|
|
||||||
userIDs, err := q.ListUserIDsForRoleExcludingUser(ctx, dbgen.ListUserIDsForRoleExcludingUserParams(params))
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
for _, userID := range userIDs {
|
|
||||||
if err := q.LockUserSessions(ctx, userID); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := q.RevokeSessionsForRoleExcludingUser(ctx, params); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := q.RevokeRefreshTokensForRoleExcludingUser(ctx, dbgen.RevokeRefreshTokensForRoleExcludingUserParams{Role: role, ID: excludeUserID}); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
if err := q.InvalidateDeviceChallengesForRoleExcludingUser(ctx, dbgen.InvalidateDeviceChallengesForRoleExcludingUserParams{Role: role, ID: excludeUserID}); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return tx.Commit(ctx)
|
|
||||||
}
|
|
||||||
|
|
@ -168,15 +168,32 @@ func (s *Service) LoginWithApple(
|
||||||
if err := domain.ValidateUserCanAuthenticate(user.Status); err != nil {
|
if err := domain.ValidateUserCanAuthenticate(user.Status); err != nil {
|
||||||
return domain.LoginSuccess{}, err
|
return domain.LoginSuccess{}, err
|
||||||
}
|
}
|
||||||
if user.Role.IsCustomerLearnerRole() {
|
|
||||||
return domain.LoginSuccess{UserId: user.ID, Role: user.Role, IsNewAccount: isNewAccount}, nil
|
oldToken, err := s.tokenStore.GetRefreshTokenByUserID(ctx, user.ID)
|
||||||
|
if err != nil {
|
||||||
|
if !errors.Is(err, ErrRefreshTokenNotFound) {
|
||||||
|
return domain.LoginSuccess{}, err
|
||||||
|
}
|
||||||
|
} else if !oldToken.Revoked {
|
||||||
|
if err := s.tokenStore.RevokeRefreshToken(ctx, oldToken.Token); err != nil {
|
||||||
|
return domain.LoginSuccess{}, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
refreshToken, err := s.issueLegacyRefreshToken(ctx, user.ID)
|
refreshToken, err := generateRefreshToken()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return domain.LoginSuccess{}, err
|
return domain.LoginSuccess{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := s.tokenStore.CreateRefreshToken(ctx, domain.RefreshToken{
|
||||||
|
Token: refreshToken,
|
||||||
|
UserID: user.ID,
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
ExpiresAt: time.Now().Add(time.Duration(s.RefreshExpiry) * time.Second),
|
||||||
|
}); err != nil {
|
||||||
|
return domain.LoginSuccess{}, err
|
||||||
|
}
|
||||||
|
|
||||||
return domain.LoginSuccess{
|
return domain.LoginSuccess{
|
||||||
UserId: user.ID,
|
UserId: user.ID,
|
||||||
Role: user.Role,
|
Role: user.Role,
|
||||||
|
|
|
||||||
|
|
@ -1,607 +0,0 @@
|
||||||
package authentication
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"sort"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"Rezina-Backend/internal/domain"
|
|
||||||
"Rezina-Backend/internal/ports"
|
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
|
||||||
)
|
|
||||||
|
|
||||||
type sessionTestUserStore struct {
|
|
||||||
ports.UserStore
|
|
||||||
users map[int64]domain.User
|
|
||||||
googleIDs map[string]int64
|
|
||||||
appleIDs map[string]int64
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s sessionTestUserStore) GetUserByID(_ context.Context, id int64) (domain.User, error) {
|
|
||||||
return s.users[id], nil
|
|
||||||
}
|
|
||||||
func (s sessionTestUserStore) GetUserByGoogleID(_ context.Context, googleID string) (domain.User, error) {
|
|
||||||
id, ok := s.googleIDs[googleID]
|
|
||||||
if !ok {
|
|
||||||
return domain.User{}, domain.ErrUserNotFound
|
|
||||||
}
|
|
||||||
return s.users[id], nil
|
|
||||||
}
|
|
||||||
func (s sessionTestUserStore) GetUserByAppleID(_ context.Context, appleID string) (domain.User, error) {
|
|
||||||
id, ok := s.appleIDs[appleID]
|
|
||||||
if !ok {
|
|
||||||
return domain.User{}, domain.ErrUserNotFound
|
|
||||||
}
|
|
||||||
return s.users[id], nil
|
|
||||||
}
|
|
||||||
func (s sessionTestUserStore) GetUserByEmailPhone(_ context.Context, email, phone string) (domain.User, error) {
|
|
||||||
for _, u := range s.users {
|
|
||||||
if u.Email == email || u.PhoneNumber == phone {
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return domain.User{}, ErrUserNotFound
|
|
||||||
}
|
|
||||||
|
|
||||||
type fakeChallenge struct {
|
|
||||||
userID int64
|
|
||||||
device domain.DeviceInfo
|
|
||||||
expires time.Time
|
|
||||||
used bool
|
|
||||||
}
|
|
||||||
type fakeSession struct {
|
|
||||||
item domain.UserSession
|
|
||||||
key string
|
|
||||||
active bool
|
|
||||||
reason string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *memorySessionStore) activeSortedLocked(userID int64, except uuid.UUID) []*fakeSession {
|
|
||||||
items := make([]*fakeSession, 0)
|
|
||||||
for _, item := range s.sessions {
|
|
||||||
if item.active && item.item.UserID == userID && item.item.ID != except {
|
|
||||||
items = append(items, item)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sort.Slice(items, func(i, j int) bool {
|
|
||||||
if !items[i].item.LastSeenAt.Equal(items[j].item.LastSeenAt) {
|
|
||||||
return items[i].item.LastSeenAt.After(items[j].item.LastSeenAt)
|
|
||||||
}
|
|
||||||
if !items[i].item.CreatedAt.Equal(items[j].item.CreatedAt) {
|
|
||||||
return items[i].item.CreatedAt.After(items[j].item.CreatedAt)
|
|
||||||
}
|
|
||||||
return items[i].item.ID.String() < items[j].item.ID.String()
|
|
||||||
})
|
|
||||||
return items
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) revokeSessionTokensLocked(sessionID uuid.UUID) {
|
|
||||||
for token, value := range s.tokens {
|
|
||||||
if value.SessionID.Valid && value.SessionID.UUID == sessionID {
|
|
||||||
value.Revoked = true
|
|
||||||
s.tokens[token] = value
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type memorySessionStore struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
sessions map[uuid.UUID]*fakeSession
|
|
||||||
challenges map[string]*fakeChallenge
|
|
||||||
tokens map[string]domain.RefreshToken
|
|
||||||
}
|
|
||||||
|
|
||||||
func newMemorySessionStore() *memorySessionStore {
|
|
||||||
return &memorySessionStore{sessions: map[uuid.UUID]*fakeSession{}, challenges: map[string]*fakeChallenge{}, tokens: map[string]domain.RefreshToken{}}
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) CreateRefreshToken(_ context.Context, rt domain.RefreshToken) error {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
s.tokens[rt.Token] = rt
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) GetRefreshToken(_ context.Context, token string) (domain.RefreshToken, error) {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
rt, ok := s.tokens[token]
|
|
||||||
if !ok {
|
|
||||||
return domain.RefreshToken{}, ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
return rt, nil
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) GetRefreshTokenByUserID(_ context.Context, id int64) (domain.RefreshToken, error) {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
for _, v := range s.tokens {
|
|
||||||
if v.UserID == id {
|
|
||||||
return v, nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return domain.RefreshToken{}, ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) RevokeRefreshToken(_ context.Context, token string) error {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
rt := s.tokens[token]
|
|
||||||
rt.Revoked = true
|
|
||||||
s.tokens[token] = rt
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *memorySessionStore) IssueUserSession(_ context.Context, p domain.SessionIssueParams) (domain.SessionIssueResult, error) {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
for _, v := range s.sessions {
|
|
||||||
if v.active && p.Device.Key != "" && v.key == p.Device.Key && v.item.UserID == p.UserID {
|
|
||||||
v.active = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
count := 0
|
|
||||||
for _, v := range s.sessions {
|
|
||||||
if v.active && v.item.UserID == p.UserID {
|
|
||||||
count++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if p.EnforceLimit && count >= p.MaxDevices {
|
|
||||||
s.challenges[string(p.ChallengeHash)] = &fakeChallenge{userID: p.UserID, device: p.Device, expires: p.ChallengeExpiry}
|
|
||||||
return domain.SessionIssueResult{LimitReached: true, ChallengeExpires: p.ChallengeExpiry, Devices: s.listLocked(p.UserID)}, nil
|
|
||||||
}
|
|
||||||
id := uuid.New()
|
|
||||||
item := domain.UserSession{ID: id, UserID: p.UserID, Label: p.Device.Label, Platform: p.Device.Platform, CreatedAt: time.Now(), LastSeenAt: time.Now(), ExpiresAt: p.RefreshExpires}
|
|
||||||
s.sessions[id] = &fakeSession{item: item, key: p.Device.Key, active: true}
|
|
||||||
s.tokens[p.RefreshToken] = domain.RefreshToken{UserID: p.UserID, Token: p.RefreshToken, ExpiresAt: p.RefreshExpires, SessionID: uuid.NullUUID{UUID: id, Valid: true}}
|
|
||||||
return domain.SessionIssueResult{Session: item}, nil
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) listLocked(userID int64) []domain.UserSession {
|
|
||||||
out := []domain.UserSession{}
|
|
||||||
for _, v := range s.sessions {
|
|
||||||
if v.active && v.item.UserID == userID {
|
|
||||||
out = append(out, v.item)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) ReplaceUserSession(_ context.Context, p domain.SessionReplaceParams) (domain.UserSession, error) {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
ch := s.challenges[string(p.ChallengeHash)]
|
|
||||||
if ch == nil || ch.used || !ch.expires.After(time.Now()) {
|
|
||||||
return domain.UserSession{}, ErrInvalidDeviceChallenge
|
|
||||||
}
|
|
||||||
old := s.sessions[p.SessionID]
|
|
||||||
if old == nil || !old.active || old.item.UserID != ch.userID {
|
|
||||||
return domain.UserSession{}, ErrInvalidDeviceChallenge
|
|
||||||
}
|
|
||||||
ch.used = true
|
|
||||||
old.active = false
|
|
||||||
id := uuid.New()
|
|
||||||
item := domain.UserSession{ID: id, UserID: ch.userID, Label: ch.device.Label, Platform: ch.device.Platform, LastSeenAt: time.Now(), ExpiresAt: p.RefreshExpires}
|
|
||||||
item.CreatedAt = item.LastSeenAt
|
|
||||||
s.sessions[id] = &fakeSession{item: item, key: ch.device.Key, active: true}
|
|
||||||
s.tokens[p.RefreshToken] = domain.RefreshToken{UserID: ch.userID, Token: p.RefreshToken, ExpiresAt: p.RefreshExpires, SessionID: uuid.NullUUID{UUID: id, Valid: true}}
|
|
||||||
if p.EnforceLimit {
|
|
||||||
others := s.activeSortedLocked(ch.userID, id)
|
|
||||||
keepOthers := p.MaxDevices - 1
|
|
||||||
if keepOthers < 0 {
|
|
||||||
keepOthers = 0
|
|
||||||
}
|
|
||||||
if keepOthers > len(others) {
|
|
||||||
keepOthers = len(others)
|
|
||||||
}
|
|
||||||
for _, excess := range others[keepOthers:] {
|
|
||||||
excess.active = false
|
|
||||||
excess.reason = "over_device_limit"
|
|
||||||
s.revokeSessionTokensLocked(excess.item.ID)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return item, nil
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) RotateSessionRefreshToken(_ context.Context, p domain.SessionRefreshParams) (domain.RefreshToken, error) {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
old, ok := s.tokens[p.OldToken]
|
|
||||||
if !ok || old.Revoked {
|
|
||||||
return domain.RefreshToken{}, ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
sid := old.SessionID
|
|
||||||
if sid.Valid {
|
|
||||||
ss := s.sessions[sid.UUID]
|
|
||||||
if ss == nil || !ss.active {
|
|
||||||
return domain.RefreshToken{}, ErrSessionRevoked
|
|
||||||
}
|
|
||||||
if p.IsLearner && p.EnforceLimit {
|
|
||||||
ranked := s.activeSortedLocked(old.UserID, uuid.Nil)
|
|
||||||
withinLimit := false
|
|
||||||
for i, item := range ranked {
|
|
||||||
if i >= p.MaxDevices {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if item.item.ID == sid.UUID {
|
|
||||||
withinLimit = true
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !withinLimit {
|
|
||||||
ss.active = false
|
|
||||||
ss.reason = "over_device_limit"
|
|
||||||
s.revokeSessionTokensLocked(sid.UUID)
|
|
||||||
return domain.RefreshToken{}, ErrSessionRevoked
|
|
||||||
}
|
|
||||||
}
|
|
||||||
ss.item.LastSeenAt = time.Now()
|
|
||||||
ss.item.ExpiresAt = p.RefreshExpires
|
|
||||||
} else if p.IsLearner {
|
|
||||||
count := 0
|
|
||||||
for _, v := range s.sessions {
|
|
||||||
if v.active && v.item.UserID == old.UserID {
|
|
||||||
count++
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if p.EnforceLimit && count >= p.MaxDevices {
|
|
||||||
return domain.RefreshToken{}, ErrDeviceLimitReached
|
|
||||||
}
|
|
||||||
id := uuid.New()
|
|
||||||
sid = uuid.NullUUID{UUID: id, Valid: true}
|
|
||||||
s.sessions[id] = &fakeSession{item: domain.UserSession{ID: id, UserID: old.UserID, Label: p.Device.Label, Platform: p.Device.Platform, ExpiresAt: p.RefreshExpires}, key: p.Device.Key, active: true}
|
|
||||||
}
|
|
||||||
old.Revoked = true
|
|
||||||
s.tokens[p.OldToken] = old
|
|
||||||
next := domain.RefreshToken{UserID: old.UserID, Token: p.NewToken, ExpiresAt: p.RefreshExpires, SessionID: sid}
|
|
||||||
s.tokens[p.NewToken] = next
|
|
||||||
return next, nil
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) LogoutSession(_ context.Context, token string) error {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
rt, ok := s.tokens[token]
|
|
||||||
if !ok || rt.Revoked {
|
|
||||||
return ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
rt.Revoked = true
|
|
||||||
s.tokens[token] = rt
|
|
||||||
if rt.SessionID.Valid {
|
|
||||||
s.sessions[rt.SessionID.UUID].active = false
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) IsUserSessionActive(_ context.Context, id uuid.UUID, userID int64) (bool, error) {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
v := s.sessions[id]
|
|
||||||
return v != nil && v.active && v.item.UserID == userID, nil
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) ListUserSessions(_ context.Context, userID int64) ([]domain.UserSession, error) {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
return s.listLocked(userID), nil
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) RevokeOwnUserSession(_ context.Context, userID int64, id uuid.UUID, _ string) error {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
v := s.sessions[id]
|
|
||||||
if v == nil || !v.active || v.item.UserID != userID {
|
|
||||||
return ErrSessionNotFound
|
|
||||||
}
|
|
||||||
v.active = false
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) RevokeUserSession(ctx context.Context, userID int64, id uuid.UUID, reason string) error {
|
|
||||||
return s.RevokeOwnUserSession(ctx, userID, id, reason)
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) RevokeAllUserSessionsAndTokens(_ context.Context, userID int64, _ string) error {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
for _, v := range s.sessions {
|
|
||||||
if v.item.UserID == userID {
|
|
||||||
v.active = false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
for k, v := range s.tokens {
|
|
||||||
if v.UserID == userID {
|
|
||||||
v.Revoked = true
|
|
||||||
s.tokens[k] = v
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
func (s *memorySessionStore) RevokeSessionsForRoleExcludingUser(context.Context, string, int64) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func newSessionTestService(store *memorySessionStore) *Service {
|
|
||||||
return NewService(nil, sessionTestUserStore{users: map[int64]domain.User{7: {ID: 7, Role: domain.RoleStudent}, 8: {ID: 8, Role: domain.RoleStudent}}}, nil, store, 3600)
|
|
||||||
}
|
|
||||||
func issue(t *testing.T, svc *Service, key string) (domain.SessionIssueResult, error) {
|
|
||||||
t.Helper()
|
|
||||||
return svc.IssueLearnerSession(context.Background(), 7, domain.RoleStudent, domain.DeviceInfo{Key: key, Label: "Chrome on Android", Platform: "android"})
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestLearnerDeviceLimitAndSameDevice(t *testing.T) {
|
|
||||||
store := newMemorySessionStore()
|
|
||||||
svc := newSessionTestService(store)
|
|
||||||
svc.ConfigureDeviceSessions(2, true)
|
|
||||||
first, err := issue(t, svc, "one")
|
|
||||||
if err != nil || first.LimitReached {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
second, err := issue(t, svc, "two")
|
|
||||||
if err != nil || second.LimitReached {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
third, err := issue(t, svc, "three")
|
|
||||||
if err != nil || !third.LimitReached || third.ChallengeToken == "" || len(third.Devices) != 2 {
|
|
||||||
t.Fatalf("unexpected third login: %#v %v", third, err)
|
|
||||||
}
|
|
||||||
again, err := issue(t, svc, "one")
|
|
||||||
if err != nil || again.LimitReached {
|
|
||||||
t.Fatalf("same-device relogin used another slot: %#v %v", again, err)
|
|
||||||
}
|
|
||||||
active, _ := store.ListUserSessions(context.Background(), 7)
|
|
||||||
if len(active) != 2 {
|
|
||||||
t.Fatalf("active=%d", len(active))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
func TestDeviceLimitEnforcementOff(t *testing.T) {
|
|
||||||
store := newMemorySessionStore()
|
|
||||||
svc := newSessionTestService(store)
|
|
||||||
svc.ConfigureDeviceSessions(2, false)
|
|
||||||
for _, key := range []string{"one", "two", "three"} {
|
|
||||||
got, err := issue(t, svc, key)
|
|
||||||
if err != nil || got.LimitReached {
|
|
||||||
t.Fatalf("%s: %#v %v", key, got, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
func TestParallelLoginGuard(t *testing.T) {
|
|
||||||
store := newMemorySessionStore()
|
|
||||||
svc := newSessionTestService(store)
|
|
||||||
svc.ConfigureDeviceSessions(2, true)
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
for i := 0; i < 12; i++ {
|
|
||||||
wg.Add(1)
|
|
||||||
go func() { defer wg.Done(); _, _ = issue(t, svc, uuid.NewString()) }()
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
active, _ := store.ListUserSessions(context.Background(), 7)
|
|
||||||
if len(active) != 2 {
|
|
||||||
t.Fatalf("parallel logins created %d sessions", len(active))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
func TestChallengeSuccessReuseExpiryAndOwnership(t *testing.T) {
|
|
||||||
store := newMemorySessionStore()
|
|
||||||
svc := newSessionTestService(store)
|
|
||||||
svc.ConfigureDeviceSessions(2, true)
|
|
||||||
one, _ := issue(t, svc, "one")
|
|
||||||
_, _ = issue(t, svc, "two")
|
|
||||||
challenge, _ := issue(t, svc, "three")
|
|
||||||
login, err := svc.ReplaceLearnerSession(context.Background(), challenge.ChallengeToken, one.Session.ID)
|
|
||||||
if err != nil || login.SessionID == uuid.Nil || login.RfToken == "" {
|
|
||||||
t.Fatalf("replace: %#v %v", login, err)
|
|
||||||
}
|
|
||||||
if _, err = svc.ReplaceLearnerSession(context.Background(), challenge.ChallengeToken, one.Session.ID); !errors.Is(err, ErrInvalidDeviceChallenge) {
|
|
||||||
t.Fatalf("reuse err=%v", err)
|
|
||||||
}
|
|
||||||
expired, _ := issue(t, svc, "four")
|
|
||||||
hash, _ := hashDeviceChallenge(expired.ChallengeToken)
|
|
||||||
store.mu.Lock()
|
|
||||||
store.challenges[string(hash)].expires = time.Now().Add(-time.Second)
|
|
||||||
store.mu.Unlock()
|
|
||||||
if _, err = svc.ReplaceLearnerSession(context.Background(), expired.ChallengeToken, login.SessionID); !errors.Is(err, ErrInvalidDeviceChallenge) {
|
|
||||||
t.Fatalf("expiry err=%v", err)
|
|
||||||
}
|
|
||||||
wrong, _ := issue(t, svc, "five")
|
|
||||||
otherID := uuid.New()
|
|
||||||
store.mu.Lock()
|
|
||||||
store.sessions[otherID] = &fakeSession{item: domain.UserSession{ID: otherID, UserID: 8}, active: true}
|
|
||||||
store.mu.Unlock()
|
|
||||||
if _, err = svc.ReplaceLearnerSession(context.Background(), wrong.ChallengeToken, otherID); !errors.Is(err, ErrInvalidDeviceChallenge) {
|
|
||||||
t.Fatalf("ownership err=%v", err)
|
|
||||||
}
|
|
||||||
if _, err = svc.ReplaceLearnerSession(context.Background(), "not-a-token", otherID); !errors.Is(err, ErrInvalidDeviceChallenge) {
|
|
||||||
t.Fatalf("invalid err=%v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
func TestRefreshRevocationLegacyAdoptionAndLogout(t *testing.T) {
|
|
||||||
store := newMemorySessionStore()
|
|
||||||
svc := newSessionTestService(store)
|
|
||||||
svc.ConfigureDeviceSessions(2, true)
|
|
||||||
created, _ := issue(t, svc, "one")
|
|
||||||
store.mu.Lock()
|
|
||||||
store.sessions[created.Session.ID].active = false
|
|
||||||
store.mu.Unlock()
|
|
||||||
if _, err := svc.RefreshTokenForDevice(context.Background(), created.RefreshToken, domain.DeviceInfo{Platform: "web", Label: "Browser on Web"}); !errors.Is(err, ErrSessionRevoked) {
|
|
||||||
t.Fatalf("revoked refresh err=%v", err)
|
|
||||||
}
|
|
||||||
legacy := "legacy"
|
|
||||||
store.tokens[legacy] = domain.RefreshToken{UserID: 7, Token: legacy, ExpiresAt: time.Now().Add(time.Hour)}
|
|
||||||
rotated, err := svc.RefreshTokenForDevice(context.Background(), legacy, domain.DeviceInfo{Key: "legacy-device", Platform: "web", Label: "Chrome on Web"})
|
|
||||||
if err != nil || !rotated.SessionID.Valid {
|
|
||||||
t.Fatalf("legacy adoption: %#v %v", rotated, err)
|
|
||||||
}
|
|
||||||
if err := svc.Logout(context.Background(), rotated.Token); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
active, _ := store.IsUserSessionActive(context.Background(), rotated.SessionID.UUID, 7)
|
|
||||||
if active {
|
|
||||||
t.Fatal("logout left session active")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestEnforcementTrimsExistingSessionsOnRefreshAndPersistsRevocation(t *testing.T) {
|
|
||||||
store := newMemorySessionStore()
|
|
||||||
svc := newSessionTestService(store)
|
|
||||||
svc.ConfigureDeviceSessions(2, false)
|
|
||||||
issued := make([]domain.SessionIssueResult, 0, 3)
|
|
||||||
for _, key := range []string{"oldest", "middle", "newest"} {
|
|
||||||
result, err := issue(t, svc, key)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
issued = append(issued, result)
|
|
||||||
}
|
|
||||||
store.mu.Lock()
|
|
||||||
base := time.Now().Add(-time.Hour)
|
|
||||||
for i, result := range issued {
|
|
||||||
store.sessions[result.Session.ID].item.LastSeenAt = base.Add(time.Duration(i) * time.Minute)
|
|
||||||
store.sessions[result.Session.ID].item.CreatedAt = base.Add(time.Duration(i) * time.Minute)
|
|
||||||
}
|
|
||||||
store.mu.Unlock()
|
|
||||||
|
|
||||||
svc.ConfigureDeviceSessions(2, true)
|
|
||||||
_, err := svc.RefreshTokenForDevice(context.Background(), issued[0].RefreshToken, domain.DeviceInfo{Platform: "web"})
|
|
||||||
if !errors.Is(err, ErrSessionRevoked) {
|
|
||||||
t.Fatalf("refresh error = %v", err)
|
|
||||||
}
|
|
||||||
store.mu.Lock()
|
|
||||||
defer store.mu.Unlock()
|
|
||||||
if store.sessions[issued[0].Session.ID].active || store.sessions[issued[0].Session.ID].reason != "over_device_limit" {
|
|
||||||
t.Fatalf("session revocation did not persist: %#v", store.sessions[issued[0].Session.ID])
|
|
||||||
}
|
|
||||||
if !store.tokens[issued[0].RefreshToken].Revoked {
|
|
||||||
t.Fatal("refresh token revocation did not persist")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestReplacementTrimsExistingSessionsAndKeepsNewSession(t *testing.T) {
|
|
||||||
store := newMemorySessionStore()
|
|
||||||
svc := newSessionTestService(store)
|
|
||||||
svc.ConfigureDeviceSessions(2, false)
|
|
||||||
issued := make([]domain.SessionIssueResult, 0, 3)
|
|
||||||
for _, key := range []string{"one", "two", "three"} {
|
|
||||||
result, err := issue(t, svc, key)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
issued = append(issued, result)
|
|
||||||
}
|
|
||||||
svc.ConfigureDeviceSessions(2, true)
|
|
||||||
challenge, err := issue(t, svc, "replacement")
|
|
||||||
if err != nil || !challenge.LimitReached {
|
|
||||||
t.Fatalf("challenge: %#v, %v", challenge, err)
|
|
||||||
}
|
|
||||||
login, err := svc.ReplaceLearnerSession(context.Background(), challenge.ChallengeToken, issued[0].Session.ID)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
active, _ := store.ListUserSessions(context.Background(), 7)
|
|
||||||
if len(active) != 2 {
|
|
||||||
t.Fatalf("active sessions = %d, want 2", len(active))
|
|
||||||
}
|
|
||||||
newActive, _ := store.IsUserSessionActive(context.Background(), login.SessionID, 7)
|
|
||||||
if !newActive {
|
|
||||||
t.Fatal("replacement trimming revoked the new session")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRefreshDoesNotTrimWhenEnforcementIsOff(t *testing.T) {
|
|
||||||
store := newMemorySessionStore()
|
|
||||||
svc := newSessionTestService(store)
|
|
||||||
svc.ConfigureDeviceSessions(2, false)
|
|
||||||
issued := make([]domain.SessionIssueResult, 0, 3)
|
|
||||||
for _, key := range []string{"one", "two", "three"} {
|
|
||||||
result, err := issue(t, svc, key)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
issued = append(issued, result)
|
|
||||||
}
|
|
||||||
if _, err := svc.RefreshTokenForDevice(context.Background(), issued[0].RefreshToken, domain.DeviceInfo{Platform: "web"}); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
active, _ := store.ListUserSessions(context.Background(), 7)
|
|
||||||
if len(active) != 3 {
|
|
||||||
t.Fatalf("active sessions = %d, want 3", len(active))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type sessionTestOtpStore struct {
|
|
||||||
ports.OtpStore
|
|
||||||
otp domain.Otp
|
|
||||||
used bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *sessionTestOtpStore) GetOtpByCode(_ context.Context, userID int64, code string) (domain.Otp, error) {
|
|
||||||
if s.otp.UserID != userID || s.otp.Otp != code {
|
|
||||||
return domain.Otp{}, domain.ErrOtpNotFound
|
|
||||||
}
|
|
||||||
return s.otp, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *sessionTestOtpStore) MarkOtpAsUsed(_ context.Context, otp domain.Otp) error {
|
|
||||||
s.otp = otp
|
|
||||||
s.used = true
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestNonLearnerOTPGoogleAndAppleKeepLegacyRefreshTokens(t *testing.T) {
|
|
||||||
admin := domain.User{ID: 9, Email: "admin@example.com", PhoneNumber: "+251900000009", Role: domain.RoleAdmin, Status: domain.UserStatusActive}
|
|
||||||
userStore := sessionTestUserStore{
|
|
||||||
users: map[int64]domain.User{9: admin}, googleIDs: map[string]int64{"google-admin": 9}, appleIDs: map[string]int64{"apple-admin": 9},
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Run("OTP", func(t *testing.T) {
|
|
||||||
tokens := newMemorySessionStore()
|
|
||||||
otpStore := &sessionTestOtpStore{otp: domain.Otp{UserID: 9, Otp: "123456", ExpiresAt: time.Now().Add(time.Minute)}}
|
|
||||||
svc := NewService(otpStore, userStore, nil, tokens, 3600)
|
|
||||||
login, err := svc.VerifyOtp(context.Background(), admin.Email, "", "123456")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if !otpStore.used || login.RfToken == "" || login.SessionID != uuid.Nil {
|
|
||||||
t.Fatalf("login = %#v, otp used = %v", login, otpStore.used)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
for _, test := range []struct {
|
|
||||||
name string
|
|
||||||
login func(*Service) (domain.LoginSuccess, error)
|
|
||||||
}{
|
|
||||||
{name: "Google", login: func(svc *Service) (domain.LoginSuccess, error) {
|
|
||||||
return svc.LoginWithGoogle(context.Background(), domain.GoogleUser{ID: "google-admin", Email: admin.Email})
|
|
||||||
}},
|
|
||||||
{name: "Apple", login: func(svc *Service) (domain.LoginSuccess, error) {
|
|
||||||
return svc.LoginWithApple(context.Background(), domain.AppleUser{ID: "apple-admin", Email: admin.Email})
|
|
||||||
}},
|
|
||||||
} {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
tokens := newMemorySessionStore()
|
|
||||||
svc := NewService(nil, userStore, nil, tokens, 3600)
|
|
||||||
login, err := test.login(svc)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if login.RfToken == "" || login.SessionID != uuid.Nil {
|
|
||||||
t.Fatalf("login = %#v", login)
|
|
||||||
}
|
|
||||||
active, _ := tokens.ListUserSessions(context.Background(), admin.ID)
|
|
||||||
if len(active) != 0 {
|
|
||||||
t.Fatalf("non-learner received %d sessions", len(active))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestAdminLoginFlowRemainsNonSessionBased(t *testing.T) {
|
|
||||||
store := newMemorySessionStore()
|
|
||||||
hash, err := bcrypt.GenerateFromPassword([]byte("secret"), bcrypt.MinCost)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
users := sessionTestUserStore{users: map[int64]domain.User{9: {ID: 9, Email: "admin@example.com", Password: hash, Role: domain.RoleAdmin, Status: domain.UserStatusActive}}}
|
|
||||||
svc := NewService(nil, users, nil, store, 3600)
|
|
||||||
login, err := svc.Login(context.Background(), domain.LoginRequest{Email: "admin@example.com", Password: "secret"})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if login.RfToken == "" || login.SessionID != uuid.Nil {
|
|
||||||
t.Fatalf("admin login changed: %#v", login)
|
|
||||||
}
|
|
||||||
active, _ := store.ListUserSessions(context.Background(), 9)
|
|
||||||
if len(active) != 0 {
|
|
||||||
t.Fatalf("admin received %d learner sessions", len(active))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -9,6 +9,7 @@ import (
|
||||||
"io"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strings"
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"cloud.google.com/go/auth/credentials/idtoken"
|
"cloud.google.com/go/auth/credentials/idtoken"
|
||||||
"golang.org/x/oauth2"
|
"golang.org/x/oauth2"
|
||||||
|
|
@ -196,15 +197,32 @@ func (s *Service) LoginWithGoogle(
|
||||||
if err := domain.ValidateUserCanAuthenticate(user.Status); err != nil {
|
if err := domain.ValidateUserCanAuthenticate(user.Status); err != nil {
|
||||||
return domain.LoginSuccess{}, err
|
return domain.LoginSuccess{}, err
|
||||||
}
|
}
|
||||||
if user.Role.IsCustomerLearnerRole() {
|
|
||||||
return domain.LoginSuccess{UserId: user.ID, Role: user.Role, IsNewAccount: isNewAccount}, nil
|
oldToken, err := s.tokenStore.GetRefreshTokenByUserID(ctx, user.ID)
|
||||||
|
if err != nil {
|
||||||
|
if !errors.Is(err, ErrRefreshTokenNotFound) {
|
||||||
|
return domain.LoginSuccess{}, err
|
||||||
|
}
|
||||||
|
} else if !oldToken.Revoked {
|
||||||
|
if err := s.tokenStore.RevokeRefreshToken(ctx, oldToken.Token); err != nil {
|
||||||
|
return domain.LoginSuccess{}, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
refreshToken, err := s.issueLegacyRefreshToken(ctx, user.ID)
|
refreshToken, err := generateRefreshToken()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return domain.LoginSuccess{}, err
|
return domain.LoginSuccess{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if err := s.tokenStore.CreateRefreshToken(ctx, domain.RefreshToken{
|
||||||
|
Token: refreshToken,
|
||||||
|
UserID: user.ID,
|
||||||
|
CreatedAt: time.Now(),
|
||||||
|
ExpiresAt: time.Now().Add(time.Duration(s.RefreshExpiry) * time.Second),
|
||||||
|
}); err != nil {
|
||||||
|
return domain.LoginSuccess{}, err
|
||||||
|
}
|
||||||
|
|
||||||
return domain.LoginSuccess{
|
return domain.LoginSuccess{
|
||||||
UserId: user.ID,
|
UserId: user.ID,
|
||||||
Role: user.Role,
|
Role: user.Role,
|
||||||
|
|
|
||||||
|
|
@ -3,27 +3,20 @@ package authentication
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/base32"
|
"encoding/base32"
|
||||||
"encoding/base64"
|
|
||||||
"errors"
|
"errors"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"Rezina-Backend/internal/domain"
|
"Rezina-Backend/internal/domain"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"golang.org/x/crypto/bcrypt"
|
"golang.org/x/crypto/bcrypt"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
ErrInvalidPassword = errors.New("incorrect password")
|
ErrInvalidPassword = errors.New("incorrect password")
|
||||||
ErrUserNotFound = errors.New("user not found")
|
ErrUserNotFound = errors.New("user not found")
|
||||||
ErrExpiredToken = errors.New("token expired")
|
ErrExpiredToken = errors.New("token expired")
|
||||||
ErrRefreshTokenNotFound = errors.New("refresh token not found") // i.e login again
|
ErrRefreshTokenNotFound = errors.New("refresh token not found") // i.e login again
|
||||||
ErrDeviceLimitReached = errors.New("device limit reached")
|
|
||||||
ErrInvalidDeviceChallenge = errors.New("invalid device login challenge")
|
|
||||||
ErrSessionRevoked = errors.New("session revoked")
|
|
||||||
ErrSessionNotFound = errors.New("session not found")
|
|
||||||
// ErrUserSuspended is kept for backward compatibility with existing handlers.
|
// ErrUserSuspended is kept for backward compatibility with existing handlers.
|
||||||
ErrUserSuspended = domain.ErrUserAccountLocked
|
ErrUserSuspended = domain.ErrUserAccountLocked
|
||||||
)
|
)
|
||||||
|
|
@ -47,9 +40,6 @@ func (s *Service) Login(
|
||||||
if err := matchPassword(req.Password, user.Password); err != nil {
|
if err := matchPassword(req.Password, user.Password); err != nil {
|
||||||
return domain.LoginSuccess{}, err
|
return domain.LoginSuccess{}, err
|
||||||
}
|
}
|
||||||
if user.Role.IsCustomerLearnerRole() {
|
|
||||||
return domain.LoginSuccess{UserId: user.ID, Role: user.Role}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
oldRefreshToken, err := s.tokenStore.GetRefreshTokenByUserID(ctx, user.ID)
|
oldRefreshToken, err := s.tokenStore.GetRefreshTokenByUserID(ctx, user.ID)
|
||||||
if err != nil && !errors.Is(err, ErrRefreshTokenNotFound) {
|
if err != nil && !errors.Is(err, ErrRefreshTokenNotFound) {
|
||||||
|
|
@ -145,12 +135,7 @@ func (s *Service) VerifyOtp(
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if user.Role.IsCustomerLearnerRole() {
|
// 7. Handle existing refresh token
|
||||||
welcomeEmailEligible := wasPending && storedOtp.For == domain.OtpRegister && storedOtp.Medium == domain.OtpMediumEmail
|
|
||||||
return domain.LoginSuccess{UserId: user.ID, Role: user.Role, WelcomeEmailEligible: welcomeEmailEligible}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// 7. Handle existing refresh token for non-learner callers.
|
|
||||||
oldRefreshToken, err := s.tokenStore.GetRefreshTokenByUserID(ctx, user.ID)
|
oldRefreshToken, err := s.tokenStore.GetRefreshTokenByUserID(ctx, user.ID)
|
||||||
if err != nil && !errors.Is(err, ErrRefreshTokenNotFound) {
|
if err != nil && !errors.Is(err, ErrRefreshTokenNotFound) {
|
||||||
return domain.LoginSuccess{}, err
|
return domain.LoginSuccess{}, err
|
||||||
|
|
@ -190,29 +175,6 @@ func (s *Service) VerifyOtp(
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) issueLegacyRefreshToken(ctx context.Context, userID int64) (string, error) {
|
|
||||||
oldRefreshToken, err := s.tokenStore.GetRefreshTokenByUserID(ctx, userID)
|
|
||||||
if err != nil && !errors.Is(err, ErrRefreshTokenNotFound) {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if err == nil && !oldRefreshToken.Revoked {
|
|
||||||
if err := s.tokenStore.RevokeRefreshToken(ctx, oldRefreshToken.Token); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
refreshToken, err := generateRefreshToken()
|
|
||||||
if err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
if err := s.tokenStore.CreateRefreshToken(ctx, domain.RefreshToken{
|
|
||||||
Token: refreshToken, UserID: userID, CreatedAt: time.Now(),
|
|
||||||
ExpiresAt: time.Now().Add(time.Duration(s.RefreshExpiry) * time.Second),
|
|
||||||
}); err != nil {
|
|
||||||
return "", err
|
|
||||||
}
|
|
||||||
return refreshToken, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// helper function to get a pointer to time.Time
|
// helper function to get a pointer to time.Time
|
||||||
func timePtr(t time.Time) time.Time {
|
func timePtr(t time.Time) time.Time {
|
||||||
return t
|
return t
|
||||||
|
|
@ -222,33 +184,6 @@ func (s *Service) RefreshToken(
|
||||||
ctx context.Context,
|
ctx context.Context,
|
||||||
refToken string,
|
refToken string,
|
||||||
) (domain.RefreshToken, error) {
|
) (domain.RefreshToken, error) {
|
||||||
return s.RefreshTokenForDevice(ctx, refToken, domain.DeviceInfo{Label: "Unknown browser", Platform: "web"})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Service) RefreshTokenForDevice(ctx context.Context, refToken string, device domain.DeviceInfo) (domain.RefreshToken, error) {
|
|
||||||
if s.sessionStore == nil {
|
|
||||||
return s.refreshTokenLegacy(ctx, refToken)
|
|
||||||
}
|
|
||||||
old, err := s.tokenStore.GetRefreshToken(ctx, refToken)
|
|
||||||
if err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
user, err := s.userStore.GetUserByID(ctx, old.UserID)
|
|
||||||
if err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
newValue, err := generateRefreshToken()
|
|
||||||
if err != nil {
|
|
||||||
return domain.RefreshToken{}, err
|
|
||||||
}
|
|
||||||
expires := time.Now().Add(time.Duration(s.RefreshExpiry) * time.Second)
|
|
||||||
return s.sessionStore.RotateSessionRefreshToken(ctx, domain.SessionRefreshParams{
|
|
||||||
OldToken: refToken, NewToken: newValue, RefreshExpires: expires, Device: device,
|
|
||||||
IsLearner: user.Role.IsCustomerLearnerRole(), MaxDevices: s.maxLearnerDevices, EnforceLimit: s.deviceLimitEnforced,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Service) refreshTokenLegacy(ctx context.Context, refToken string) (domain.RefreshToken, error) {
|
|
||||||
|
|
||||||
// 1. Load refresh token
|
// 1. Load refresh token
|
||||||
token, err := s.tokenStore.GetRefreshToken(ctx, refToken)
|
token, err := s.tokenStore.GetRefreshToken(ctx, refToken)
|
||||||
|
|
@ -303,9 +238,6 @@ func (s *Service) GetLastLogin(ctx context.Context, user_id int64) (*time.Time,
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) Logout(ctx context.Context, refToken string) error {
|
func (s *Service) Logout(ctx context.Context, refToken string) error {
|
||||||
if s.sessionStore != nil {
|
|
||||||
return s.sessionStore.LogoutSession(ctx, refToken)
|
|
||||||
}
|
|
||||||
token, err := s.tokenStore.GetRefreshToken(ctx, refToken)
|
token, err := s.tokenStore.GetRefreshToken(ctx, refToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
|
|
@ -320,81 +252,6 @@ func (s *Service) Logout(ctx context.Context, refToken string) error {
|
||||||
return s.tokenStore.RevokeRefreshToken(ctx, refToken)
|
return s.tokenStore.RevokeRefreshToken(ctx, refToken)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) IssueLearnerSession(ctx context.Context, userID int64, role domain.Role, device domain.DeviceInfo) (domain.SessionIssueResult, error) {
|
|
||||||
if !role.IsCustomerLearnerRole() || s.sessionStore == nil {
|
|
||||||
return domain.SessionIssueResult{}, errors.New("learner session store unavailable")
|
|
||||||
}
|
|
||||||
refreshToken, err := generateRefreshToken()
|
|
||||||
if err != nil {
|
|
||||||
return domain.SessionIssueResult{}, err
|
|
||||||
}
|
|
||||||
rawChallenge, challengeHash, err := generateDeviceChallenge()
|
|
||||||
if err != nil {
|
|
||||||
return domain.SessionIssueResult{}, err
|
|
||||||
}
|
|
||||||
now := time.Now()
|
|
||||||
expires := now.Add(time.Duration(s.RefreshExpiry) * time.Second)
|
|
||||||
result, err := s.sessionStore.IssueUserSession(ctx, domain.SessionIssueParams{
|
|
||||||
UserID: userID, Device: device, SessionExpires: expires,
|
|
||||||
RefreshToken: refreshToken, RefreshExpires: expires,
|
|
||||||
MaxDevices: s.maxLearnerDevices, EnforceLimit: s.deviceLimitEnforced,
|
|
||||||
ChallengeHash: challengeHash, ChallengeExpiry: now.Add(5 * time.Minute),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return domain.SessionIssueResult{}, err
|
|
||||||
}
|
|
||||||
if result.LimitReached {
|
|
||||||
result.ChallengeToken = rawChallenge
|
|
||||||
}
|
|
||||||
if !result.LimitReached {
|
|
||||||
result.RefreshToken = refreshToken
|
|
||||||
}
|
|
||||||
return result, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Service) ReplaceLearnerSession(ctx context.Context, challengeToken string, sessionID uuid.UUID) (domain.LoginSuccess, error) {
|
|
||||||
hash, err := hashDeviceChallenge(challengeToken)
|
|
||||||
if err != nil || s.sessionStore == nil {
|
|
||||||
return domain.LoginSuccess{}, ErrInvalidDeviceChallenge
|
|
||||||
}
|
|
||||||
refreshToken, err := generateRefreshToken()
|
|
||||||
if err != nil {
|
|
||||||
return domain.LoginSuccess{}, err
|
|
||||||
}
|
|
||||||
expires := time.Now().Add(time.Duration(s.RefreshExpiry) * time.Second)
|
|
||||||
session, err := s.sessionStore.ReplaceUserSession(ctx, domain.SessionReplaceParams{
|
|
||||||
ChallengeHash: hash, SessionID: sessionID, RefreshToken: refreshToken, RefreshExpires: expires,
|
|
||||||
MaxDevices: s.maxLearnerDevices, EnforceLimit: s.deviceLimitEnforced,
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
return domain.LoginSuccess{}, err
|
|
||||||
}
|
|
||||||
user, err := s.userStore.GetUserByID(ctx, session.UserID)
|
|
||||||
if err != nil || !user.Role.IsCustomerLearnerRole() {
|
|
||||||
return domain.LoginSuccess{}, ErrInvalidDeviceChallenge
|
|
||||||
}
|
|
||||||
return domain.LoginSuccess{UserId: user.ID, Role: user.Role, RfToken: refreshToken, SessionID: session.ID}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func generateDeviceChallenge() (string, []byte, error) {
|
|
||||||
b := make([]byte, 32)
|
|
||||||
if _, err := rand.Read(b); err != nil {
|
|
||||||
return "", nil, err
|
|
||||||
}
|
|
||||||
raw := base64.RawURLEncoding.EncodeToString(b)
|
|
||||||
h := sha256.Sum256([]byte(raw))
|
|
||||||
return raw, h[:], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func hashDeviceChallenge(raw string) ([]byte, error) {
|
|
||||||
decoded, err := base64.RawURLEncoding.DecodeString(raw)
|
|
||||||
if err != nil || len(decoded) < 32 {
|
|
||||||
return nil, ErrInvalidDeviceChallenge
|
|
||||||
}
|
|
||||||
h := sha256.Sum256([]byte(raw))
|
|
||||||
return h[:], nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func matchPassword(plaintextPassword string, hash []byte) error {
|
func matchPassword(plaintextPassword string, hash []byte) error {
|
||||||
err := bcrypt.CompareHashAndPassword(hash, []byte(plaintextPassword))
|
err := bcrypt.CompareHashAndPassword(hash, []byte(plaintextPassword))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
|
||||||
|
|
@ -14,37 +14,19 @@ type Tokens struct {
|
||||||
RefreshToken string
|
RefreshToken string
|
||||||
}
|
}
|
||||||
type Service struct {
|
type Service struct {
|
||||||
otpStore ports.OtpStore
|
otpStore ports.OtpStore
|
||||||
userStore ports.UserStore
|
userStore ports.UserStore
|
||||||
UserSvc *user.Service
|
UserSvc *user.Service
|
||||||
tokenStore ports.TokenStore
|
tokenStore ports.TokenStore
|
||||||
sessionStore ports.SessionStore
|
RefreshExpiry int
|
||||||
RefreshExpiry int
|
|
||||||
maxLearnerDevices int
|
|
||||||
deviceLimitEnforced bool
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewService(otpStore ports.OtpStore, userStore ports.UserStore, userSvc *user.Service, tokenStore ports.TokenStore, RefreshExpiry int) *Service {
|
func NewService(otpStore ports.OtpStore, userStore ports.UserStore, userSvc *user.Service, tokenStore ports.TokenStore, RefreshExpiry int) *Service {
|
||||||
s := &Service{
|
return &Service{
|
||||||
otpStore: otpStore,
|
otpStore: otpStore,
|
||||||
userStore: userStore,
|
userStore: userStore,
|
||||||
UserSvc: userSvc,
|
UserSvc: userSvc,
|
||||||
tokenStore: tokenStore,
|
tokenStore: tokenStore,
|
||||||
RefreshExpiry: RefreshExpiry,
|
RefreshExpiry: RefreshExpiry,
|
||||||
maxLearnerDevices: 2,
|
|
||||||
}
|
}
|
||||||
if sessions, ok := tokenStore.(ports.SessionStore); ok {
|
|
||||||
s.sessionStore = sessions
|
|
||||||
}
|
|
||||||
return s
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *Service) ConfigureDeviceSessions(maxDevices int, enforced bool) {
|
|
||||||
if maxDevices <= 0 {
|
|
||||||
maxDevices = 2
|
|
||||||
}
|
|
||||||
s.maxLearnerDevices = maxDevices
|
|
||||||
s.deviceLimitEnforced = enforced
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Service) SessionStore() ports.SessionStore { return s.sessionStore }
|
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ package user
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"Rezina-Backend/internal/domain"
|
"Rezina-Backend/internal/domain"
|
||||||
"Rezina-Backend/internal/ports"
|
|
||||||
"context"
|
"context"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
@ -101,14 +100,6 @@ func (s *Service) UpdateUserStatus(ctx context.Context, req domain.UpdateUserSta
|
||||||
if err := s.userStore.UpdateUserStatus(ctx, req); err != nil {
|
if err := s.userStore.UpdateUserStatus(ctx, req); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
status := domain.UserStatus(req.Status)
|
|
||||||
if status == domain.UserStatusSuspended || status == domain.UserStatusDeactivated {
|
|
||||||
if sessions, ok := s.tokenStore.(ports.SessionStore); ok {
|
|
||||||
if err := sessions.RevokeAllUserSessionsAndTokens(ctx, req.UserID, "account_"+strings.ToLower(req.Status)); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
s.authStatusCache.invalidate(req.UserID)
|
s.authStatusCache.invalidate(req.UserID)
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
@ -118,11 +109,6 @@ func (s *Service) BulkDeactivateUsersByRole(ctx context.Context, role string, ex
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
if sessions, ok := s.tokenStore.(ports.SessionStore); ok {
|
|
||||||
if err := sessions.RevokeSessionsForRoleExcludingUser(ctx, role, excludeUserID); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
s.authStatusCache.invalidateAll()
|
s.authStatusCache.invalidateAll()
|
||||||
return n, nil
|
return n, nil
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ package user
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"Rezina-Backend/internal/domain"
|
"Rezina-Backend/internal/domain"
|
||||||
"Rezina-Backend/internal/ports"
|
|
||||||
"context"
|
"context"
|
||||||
"crypto/subtle"
|
"crypto/subtle"
|
||||||
"errors"
|
"errors"
|
||||||
|
|
@ -83,11 +82,6 @@ func (s *Service) ResetPassword(ctx context.Context, resetReq domain.ResetPasswo
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if sessions, ok := s.tokenStore.(ports.SessionStore); ok {
|
|
||||||
if err := sessions.RevokeAllUserSessionsAndTokens(ctx, user.ID, "password_reset"); err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Mark OTP as used to prevent replay attacks
|
// Mark OTP as used to prevent replay attacks
|
||||||
err = s.otpStore.MarkOtpAsUsed(ctx, otp)
|
err = s.otpStore.MarkOtpAsUsed(ctx, otp)
|
||||||
|
|
|
||||||
|
|
@ -32,31 +32,6 @@ type loginUserRes struct {
|
||||||
UserID int64 `json:"user_id"`
|
UserID int64 `json:"user_id"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) respondLegacyOAuthLogin(c *fiber.Ctx, login domain.LoginSuccess, activityDescription string) error {
|
|
||||||
accessToken, err := jwtutil.CreateJwt(
|
|
||||||
login.UserId,
|
|
||||||
login.Role,
|
|
||||||
h.jwtConfig.JwtAccessKey,
|
|
||||||
h.jwtConfig.JwtAccessExpiry,
|
|
||||||
)
|
|
||||||
if err != nil {
|
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
|
||||||
Message: "Token generation failed",
|
|
||||||
Error: err.Error(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
userID := login.UserId
|
|
||||||
h.recordActivityAs(c, userID, login.Role, domain.ActionAuthLogin, domain.ResourceAuth, &userID, activityDescription, nil)
|
|
||||||
return c.Status(fiber.StatusOK).JSON(domain.Response{
|
|
||||||
Message: "Login successful",
|
|
||||||
Data: loginUserRes{
|
|
||||||
AccessToken: accessToken, RefreshToken: login.RfToken,
|
|
||||||
Role: string(login.Role), UserID: login.UserId,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// GoogleAndroidLogin godoc
|
// GoogleAndroidLogin godoc
|
||||||
// @Summary Login via Google Android ID Token
|
// @Summary Login via Google Android ID Token
|
||||||
// @Tags auth
|
// @Tags auth
|
||||||
|
|
@ -96,10 +71,33 @@ func (h *Handler) GoogleAndroidLogin(c *fiber.Ctx) error {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
h.notifyWelcomeIfNewAccount(loginRes)
|
h.notifyWelcomeIfNewAccount(loginRes)
|
||||||
if loginRes.Role.IsCustomerLearnerRole() {
|
|
||||||
return h.respondLearnerLogin(c, loginRes, "Login successful", fmt.Sprintf("Google Android login (user ID: %d)", loginRes.UserId))
|
// Issue backend JWT
|
||||||
|
accessToken, err := jwtutil.CreateJwt(
|
||||||
|
loginRes.UserId,
|
||||||
|
loginRes.Role,
|
||||||
|
h.jwtConfig.JwtAccessKey,
|
||||||
|
h.jwtConfig.JwtAccessExpiry,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Token generation failed",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
return h.respondLegacyOAuthLogin(c, loginRes, fmt.Sprintf("Google Android login (user ID: %d)", loginRes.UserId))
|
|
||||||
|
userID := loginRes.UserId
|
||||||
|
h.recordActivityAs(c, userID, loginRes.Role, domain.ActionAuthLogin, domain.ResourceAuth, &userID, fmt.Sprintf("Google Android login (user ID: %d)", userID), nil)
|
||||||
|
|
||||||
|
return c.Status(fiber.StatusOK).JSON(domain.Response{
|
||||||
|
Message: "Login successful",
|
||||||
|
Data: loginUserRes{
|
||||||
|
AccessToken: accessToken,
|
||||||
|
RefreshToken: loginRes.RfToken,
|
||||||
|
Role: string(loginRes.Role),
|
||||||
|
UserID: loginRes.UserId,
|
||||||
|
},
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// AppleLogin godoc
|
// AppleLogin godoc
|
||||||
|
|
@ -153,10 +151,32 @@ func (h *Handler) AppleLogin(c *fiber.Ctx) error {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
h.notifyWelcomeIfNewAccount(loginRes)
|
h.notifyWelcomeIfNewAccount(loginRes)
|
||||||
if loginRes.Role.IsCustomerLearnerRole() {
|
|
||||||
return h.respondLearnerLogin(c, loginRes, "Login successful", fmt.Sprintf("Apple login (user ID: %d)", loginRes.UserId))
|
accessToken, err := jwtutil.CreateJwt(
|
||||||
|
loginRes.UserId,
|
||||||
|
loginRes.Role,
|
||||||
|
h.jwtConfig.JwtAccessKey,
|
||||||
|
h.jwtConfig.JwtAccessExpiry,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Token generation failed",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
return h.respondLegacyOAuthLogin(c, loginRes, fmt.Sprintf("Apple login (user ID: %d)", loginRes.UserId))
|
|
||||||
|
userID := loginRes.UserId
|
||||||
|
h.recordActivityAs(c, userID, loginRes.Role, domain.ActionAuthLogin, domain.ResourceAuth, &userID, fmt.Sprintf("Apple login (user ID: %d)", userID), nil)
|
||||||
|
|
||||||
|
return c.Status(fiber.StatusOK).JSON(domain.Response{
|
||||||
|
Message: "Login successful",
|
||||||
|
Data: loginUserRes{
|
||||||
|
AccessToken: accessToken,
|
||||||
|
RefreshToken: loginRes.RfToken,
|
||||||
|
Role: string(loginRes.Role),
|
||||||
|
UserID: loginRes.UserId,
|
||||||
|
},
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// GoogleLogin godoc
|
// GoogleLogin godoc
|
||||||
|
|
@ -217,10 +237,32 @@ func (h *Handler) GoogleCallback(c *fiber.Ctx) error {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
h.notifyWelcomeIfNewAccount(loginRes)
|
h.notifyWelcomeIfNewAccount(loginRes)
|
||||||
if loginRes.Role.IsCustomerLearnerRole() {
|
|
||||||
return h.respondLearnerLogin(c, loginRes, "Login successful", fmt.Sprintf("Google OAuth login (user ID: %d)", loginRes.UserId))
|
accessToken, err := jwtutil.CreateJwt(
|
||||||
|
loginRes.UserId,
|
||||||
|
loginRes.Role,
|
||||||
|
h.jwtConfig.JwtAccessKey,
|
||||||
|
h.jwtConfig.JwtAccessExpiry,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Token generation failed",
|
||||||
|
Error: err.Error(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
return h.respondLegacyOAuthLogin(c, loginRes, fmt.Sprintf("Google OAuth login (user ID: %d)", loginRes.UserId))
|
|
||||||
|
userID := loginRes.UserId
|
||||||
|
h.recordActivityAs(c, userID, loginRes.Role, domain.ActionAuthLogin, domain.ResourceAuth, &userID, fmt.Sprintf("Google OAuth login (user ID: %d)", userID), nil)
|
||||||
|
|
||||||
|
return c.Status(fiber.StatusOK).JSON(domain.Response{
|
||||||
|
Message: "Login successful",
|
||||||
|
Data: loginUserRes{
|
||||||
|
AccessToken: accessToken,
|
||||||
|
RefreshToken: loginRes.RfToken,
|
||||||
|
Role: string(loginRes.Role),
|
||||||
|
UserID: loginRes.UserId,
|
||||||
|
},
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// Loginuser godoc
|
// Loginuser godoc
|
||||||
|
|
@ -318,7 +360,46 @@ func (h *Handler) LoginUser(c *fiber.Ctx) error {
|
||||||
// })
|
// })
|
||||||
// }
|
// }
|
||||||
|
|
||||||
return h.respondLearnerLogin(c, successRes, "Login successful", fmt.Sprintf("User login (user ID: %d)", successRes.UserId))
|
accessToken, err := jwtutil.CreateJwt(
|
||||||
|
successRes.UserId,
|
||||||
|
successRes.Role,
|
||||||
|
h.jwtConfig.JwtAccessKey,
|
||||||
|
h.jwtConfig.JwtAccessExpiry,
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
h.mongoLoggerSvc.Error("Failed to create access token",
|
||||||
|
zap.Int("status_code", fiber.StatusInternalServerError),
|
||||||
|
zap.Int64("user_id", successRes.UserId),
|
||||||
|
zap.Error(err),
|
||||||
|
zap.Time("timestamp", time.Now()),
|
||||||
|
)
|
||||||
|
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{
|
||||||
|
Message: "Failed to login",
|
||||||
|
Error: "Failed to generate access token",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
res := loginUserRes{
|
||||||
|
AccessToken: accessToken,
|
||||||
|
RefreshToken: successRes.RfToken,
|
||||||
|
Role: string(successRes.Role),
|
||||||
|
UserID: successRes.UserId,
|
||||||
|
}
|
||||||
|
|
||||||
|
h.mongoLoggerSvc.Info("Login successful",
|
||||||
|
zap.Int("status_code", fiber.StatusOK),
|
||||||
|
zap.Int64("user_id", successRes.UserId),
|
||||||
|
zap.String("role", string(successRes.Role)),
|
||||||
|
zap.Time("timestamp", time.Now()),
|
||||||
|
)
|
||||||
|
|
||||||
|
userID := successRes.UserId
|
||||||
|
h.recordActivityAs(c, successRes.UserId, successRes.Role, domain.ActionAuthLogin, domain.ResourceAuth, &userID, fmt.Sprintf("User login (user ID: %d)", userID), nil)
|
||||||
|
|
||||||
|
return c.Status(fiber.StatusOK).JSON(domain.Response{
|
||||||
|
Message: "Login successful",
|
||||||
|
Data: res,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// loginAdminReq represents the request body for the LoginAdmin endpoint.
|
// loginAdminReq represents the request body for the LoginAdmin endpoint.
|
||||||
|
|
@ -590,17 +671,14 @@ func (h *Handler) RefreshToken(c *fiber.Ctx) error {
|
||||||
return fiber.NewError(fiber.StatusBadRequest, errMsg)
|
return fiber.NewError(fiber.StatusBadRequest, errMsg)
|
||||||
}
|
}
|
||||||
|
|
||||||
device, err := deviceInfoFromRequest(c)
|
refreshToken, err := h.authSvc.RefreshToken(c.Context(), req.RefreshToken)
|
||||||
if err != nil {
|
|
||||||
return fiber.NewError(fiber.StatusBadRequest, err.Error())
|
|
||||||
}
|
|
||||||
refreshToken, err := h.authSvc.RefreshTokenForDevice(c.Context(), req.RefreshToken, device)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, authentication.ErrExpiredToken):
|
case errors.Is(err, authentication.ErrExpiredToken):
|
||||||
h.mongoLoggerSvc.Info("Refresh token attempt failed: The refresh token has expired",
|
h.mongoLoggerSvc.Info("Refresh token attempt failed: The refresh token has expired",
|
||||||
zap.Int("status_code", fiber.StatusUnauthorized),
|
zap.Int("status_code", fiber.StatusUnauthorized),
|
||||||
|
zap.String("refresh_token", req.RefreshToken),
|
||||||
zap.Error(err),
|
zap.Error(err),
|
||||||
zap.Time("timestamp", time.Now()),
|
zap.Time("timestamp", time.Now()),
|
||||||
)
|
)
|
||||||
|
|
@ -608,14 +686,11 @@ func (h *Handler) RefreshToken(c *fiber.Ctx) error {
|
||||||
case errors.Is(err, authentication.ErrRefreshTokenNotFound):
|
case errors.Is(err, authentication.ErrRefreshTokenNotFound):
|
||||||
h.mongoLoggerSvc.Info("Refresh token attempt failed: Refresh token not found",
|
h.mongoLoggerSvc.Info("Refresh token attempt failed: Refresh token not found",
|
||||||
zap.Int("status_code", fiber.StatusUnauthorized),
|
zap.Int("status_code", fiber.StatusUnauthorized),
|
||||||
|
zap.String("refresh_token", req.RefreshToken),
|
||||||
zap.Error(err),
|
zap.Error(err),
|
||||||
zap.Time("timestamp", time.Now()),
|
zap.Time("timestamp", time.Now()),
|
||||||
)
|
)
|
||||||
return fiber.NewError(fiber.StatusUnauthorized, "Refresh token not found")
|
return fiber.NewError(fiber.StatusUnauthorized, "Refresh token not found")
|
||||||
case errors.Is(err, authentication.ErrSessionRevoked):
|
|
||||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Session revoked", "code": "SESSION_REVOKED"})
|
|
||||||
case errors.Is(err, authentication.ErrDeviceLimitReached):
|
|
||||||
return fiber.NewError(fiber.StatusUnauthorized, "Please sign in again")
|
|
||||||
default:
|
default:
|
||||||
h.mongoLoggerSvc.Error("Refresh token failed",
|
h.mongoLoggerSvc.Error("Refresh token failed",
|
||||||
zap.Int("status_code", fiber.StatusInternalServerError),
|
zap.Int("status_code", fiber.StatusInternalServerError),
|
||||||
|
|
@ -651,12 +726,7 @@ func (h *Handler) RefreshToken(c *fiber.Ctx) error {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var accessToken string
|
accessToken, err := jwtutil.CreateJwt(user.ID, user.Role, h.jwtConfig.JwtAccessKey, h.jwtConfig.JwtAccessExpiry)
|
||||||
if user.Role.IsCustomerLearnerRole() {
|
|
||||||
accessToken, err = jwtutil.CreateLearnerJwt(user.ID, user.Role, refreshToken.SessionID.UUID.String(), h.jwtConfig.JwtAccessKey, h.jwtConfig.JwtAccessExpiry)
|
|
||||||
} else {
|
|
||||||
accessToken, err = jwtutil.CreateJwt(user.ID, user.Role, h.jwtConfig.JwtAccessKey, h.jwtConfig.JwtAccessExpiry)
|
|
||||||
}
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.mongoLoggerSvc.Error("Failed to create new access token",
|
h.mongoLoggerSvc.Error("Failed to create new access token",
|
||||||
zap.Int("status_code", fiber.StatusInternalServerError),
|
zap.Int("status_code", fiber.StatusInternalServerError),
|
||||||
|
|
@ -669,7 +739,7 @@ func (h *Handler) RefreshToken(c *fiber.Ctx) error {
|
||||||
|
|
||||||
res := loginUserRes{
|
res := loginUserRes{
|
||||||
AccessToken: accessToken,
|
AccessToken: accessToken,
|
||||||
RefreshToken: refreshToken.Token,
|
RefreshToken: req.RefreshToken,
|
||||||
Role: string(user.Role),
|
Role: string(user.Role),
|
||||||
UserID: user.ID,
|
UserID: user.ID,
|
||||||
}
|
}
|
||||||
|
|
@ -744,6 +814,7 @@ func (h *Handler) LogOutuser(c *fiber.Ctx) error {
|
||||||
case errors.Is(err, authentication.ErrExpiredToken):
|
case errors.Is(err, authentication.ErrExpiredToken):
|
||||||
h.mongoLoggerSvc.Info("Logout attempt failed:The refresh token has expired",
|
h.mongoLoggerSvc.Info("Logout attempt failed:The refresh token has expired",
|
||||||
zap.Int("status_code", fiber.StatusUnauthorized),
|
zap.Int("status_code", fiber.StatusUnauthorized),
|
||||||
|
zap.String("refresh_token", req.RefreshToken),
|
||||||
zap.Error(err),
|
zap.Error(err),
|
||||||
zap.Time("timestamp", time.Now()),
|
zap.Time("timestamp", time.Now()),
|
||||||
)
|
)
|
||||||
|
|
@ -751,6 +822,7 @@ func (h *Handler) LogOutuser(c *fiber.Ctx) error {
|
||||||
case errors.Is(err, authentication.ErrRefreshTokenNotFound):
|
case errors.Is(err, authentication.ErrRefreshTokenNotFound):
|
||||||
h.mongoLoggerSvc.Info("Logout attempt failed: Refresh token not found",
|
h.mongoLoggerSvc.Info("Logout attempt failed: Refresh token not found",
|
||||||
zap.Int("status_code", fiber.StatusUnauthorized),
|
zap.Int("status_code", fiber.StatusUnauthorized),
|
||||||
|
zap.String("refresh_token", req.RefreshToken),
|
||||||
zap.Error(err),
|
zap.Error(err),
|
||||||
zap.Time("timestamp", time.Now()),
|
zap.Time("timestamp", time.Now()),
|
||||||
)
|
)
|
||||||
|
|
|
||||||
|
|
@ -1,161 +0,0 @@
|
||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"Rezina-Backend/internal/domain"
|
|
||||||
"Rezina-Backend/internal/ports"
|
|
||||||
activitylogservice "Rezina-Backend/internal/services/activity_log"
|
|
||||||
"Rezina-Backend/internal/services/authentication"
|
|
||||||
userservice "Rezina-Backend/internal/services/user"
|
|
||||||
jwtutil "Rezina-Backend/internal/web_server/jwt"
|
|
||||||
customvalidator "Rezina-Backend/internal/web_server/validator"
|
|
||||||
|
|
||||||
"github.com/go-playground/validator/v10"
|
|
||||||
"github.com/gofiber/fiber/v2"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
type refreshTokenStore struct {
|
|
||||||
ports.TokenStore
|
|
||||||
mu sync.Mutex
|
|
||||||
tokens map[string]domain.RefreshToken
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *refreshTokenStore) CreateRefreshToken(_ context.Context, token domain.RefreshToken) error {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
s.tokens[token.Token] = token
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *refreshTokenStore) GetRefreshToken(_ context.Context, value string) (domain.RefreshToken, error) {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
token, ok := s.tokens[value]
|
|
||||||
if !ok {
|
|
||||||
return domain.RefreshToken{}, authentication.ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
return token, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *refreshTokenStore) RevokeRefreshToken(_ context.Context, value string) error {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
token, ok := s.tokens[value]
|
|
||||||
if !ok {
|
|
||||||
return authentication.ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
token.Revoked = true
|
|
||||||
s.tokens[value] = token
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type refreshUserStore struct {
|
|
||||||
ports.UserStore
|
|
||||||
user domain.User
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s refreshUserStore) GetUserByID(_ context.Context, _ int64) (domain.User, error) {
|
|
||||||
return s.user, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type refreshActivityStore struct {
|
|
||||||
ports.ActivityLogStore
|
|
||||||
}
|
|
||||||
|
|
||||||
func (refreshActivityStore) CreateActivityLog(_ context.Context, log domain.ActivityLog) (domain.ActivityLog, error) {
|
|
||||||
return log, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRefreshTokenReturnsRotatedTokenAndPreservesSingleUse(t *testing.T) {
|
|
||||||
const submittedToken = "submitted-refresh-token"
|
|
||||||
const userID int64 = 42
|
|
||||||
|
|
||||||
tokenStore := &refreshTokenStore{tokens: map[string]domain.RefreshToken{
|
|
||||||
submittedToken: {
|
|
||||||
Token: submittedToken,
|
|
||||||
UserID: userID,
|
|
||||||
CreatedAt: time.Now(),
|
|
||||||
ExpiresAt: time.Now().Add(time.Hour),
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
userStore := refreshUserStore{user: domain.User{
|
|
||||||
ID: userID,
|
|
||||||
Role: domain.RoleStudent,
|
|
||||||
Status: domain.UserStatusActive,
|
|
||||||
}}
|
|
||||||
logger := zap.NewNop()
|
|
||||||
handler := &Handler{
|
|
||||||
authSvc: authentication.NewService(nil, userStore, nil, tokenStore, 3600),
|
|
||||||
userSvc: userservice.NewService(nil, userStore, nil, nil, nil, nil, nil),
|
|
||||||
activityLogSvc: activitylogservice.NewService(refreshActivityStore{}, logger),
|
|
||||||
jwtConfig: jwtutil.JwtConfig{
|
|
||||||
JwtAccessKey: "refresh-handler-test-key",
|
|
||||||
JwtAccessExpiry: 3600,
|
|
||||||
},
|
|
||||||
validator: customvalidator.NewCustomValidator(validator.New()),
|
|
||||||
mongoLoggerSvc: logger,
|
|
||||||
}
|
|
||||||
|
|
||||||
app := fiber.New()
|
|
||||||
app.Post("/api/v1/auth/refresh", handler.RefreshToken)
|
|
||||||
|
|
||||||
refresh := func(token string) (int, string) {
|
|
||||||
t.Helper()
|
|
||||||
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/refresh", strings.NewReader(`{"access_token":"expired-access-token","refresh_token":"`+token+`"}`))
|
|
||||||
req.Header.Set(fiber.HeaderContentType, fiber.MIMEApplicationJSON)
|
|
||||||
resp, err := app.Test(req)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
|
|
||||||
body, err := io.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if resp.StatusCode != fiber.StatusOK {
|
|
||||||
return resp.StatusCode, ""
|
|
||||||
}
|
|
||||||
|
|
||||||
var payload struct {
|
|
||||||
Data struct {
|
|
||||||
RefreshToken string `json:"refresh_token"`
|
|
||||||
} `json:"data"`
|
|
||||||
}
|
|
||||||
if err := json.Unmarshal(body, &payload); err != nil {
|
|
||||||
t.Fatalf("decode refresh response: %v; body=%s", err, body)
|
|
||||||
}
|
|
||||||
return resp.StatusCode, payload.Data.RefreshToken
|
|
||||||
}
|
|
||||||
|
|
||||||
status, rotatedToken := refresh(submittedToken)
|
|
||||||
if status != fiber.StatusOK {
|
|
||||||
t.Fatalf("first refresh status=%d, want %d", status, fiber.StatusOK)
|
|
||||||
}
|
|
||||||
if rotatedToken == "" || rotatedToken == submittedToken {
|
|
||||||
t.Fatalf("response refresh token=%q, want a non-empty token different from submitted token", rotatedToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
status, nextRotatedToken := refresh(rotatedToken)
|
|
||||||
if status != fiber.StatusOK {
|
|
||||||
t.Fatalf("refresh with rotated token status=%d, want %d", status, fiber.StatusOK)
|
|
||||||
}
|
|
||||||
if nextRotatedToken == "" || nextRotatedToken == rotatedToken {
|
|
||||||
t.Fatalf("second response refresh token=%q, want a newly rotated token", nextRotatedToken)
|
|
||||||
}
|
|
||||||
|
|
||||||
status, _ = refresh(submittedToken)
|
|
||||||
if status != fiber.StatusUnauthorized {
|
|
||||||
t.Fatalf("reused submitted token status=%d, want %d", status, fiber.StatusUnauthorized)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -807,27 +807,13 @@ func (h *Handler) VerifyOtp(c *fiber.Ctx) error {
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if loginSuccess.Role.IsCustomerLearnerRole() {
|
|
||||||
if loginSuccess.WelcomeEmailEligible {
|
|
||||||
if h.learnerNotifSvc != nil {
|
|
||||||
h.learnerNotifSvc.NotifyWelcome(loginSuccess.UserId)
|
|
||||||
}
|
|
||||||
if err := h.userSvc.SendWelcomeEmail(c.Context(), loginSuccess.UserId); err != nil {
|
|
||||||
h.mongoLoggerSvc.Warn("Failed to send welcome email",
|
|
||||||
zap.Int64("user_id", loginSuccess.UserId),
|
|
||||||
zap.Error(err),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return h.respondLearnerLogin(c, loginSuccess, "OTP verified successfully", "")
|
|
||||||
}
|
|
||||||
|
|
||||||
accessToken, err := jwtutil.CreateJwt(
|
accessToken, err := jwtutil.CreateJwt(
|
||||||
loginSuccess.UserId,
|
loginSuccess.UserId,
|
||||||
loginSuccess.Role,
|
loginSuccess.Role,
|
||||||
h.jwtConfig.JwtAccessKey,
|
h.jwtConfig.JwtAccessKey,
|
||||||
h.jwtConfig.JwtAccessExpiry,
|
h.jwtConfig.JwtAccessExpiry,
|
||||||
)
|
)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.mongoLoggerSvc.Error("Failed to create access token",
|
h.mongoLoggerSvc.Error("Failed to create access token",
|
||||||
zap.Int("status_code", fiber.StatusInternalServerError),
|
zap.Int("status_code", fiber.StatusInternalServerError),
|
||||||
|
|
@ -840,6 +826,7 @@ func (h *Handler) VerifyOtp(c *fiber.Ctx) error {
|
||||||
Error: "Failed to generate access token",
|
Error: "Failed to generate access token",
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
if loginSuccess.WelcomeEmailEligible {
|
if loginSuccess.WelcomeEmailEligible {
|
||||||
if h.learnerNotifSvc != nil {
|
if h.learnerNotifSvc != nil {
|
||||||
h.learnerNotifSvc.NotifyWelcome(loginSuccess.UserId)
|
h.learnerNotifSvc.NotifyWelcome(loginSuccess.UserId)
|
||||||
|
|
@ -855,8 +842,10 @@ func (h *Handler) VerifyOtp(c *fiber.Ctx) error {
|
||||||
return c.Status(fiber.StatusOK).JSON(domain.Response{
|
return c.Status(fiber.StatusOK).JSON(domain.Response{
|
||||||
Message: "OTP verified successfully",
|
Message: "OTP verified successfully",
|
||||||
Data: loginUserRes{
|
Data: loginUserRes{
|
||||||
AccessToken: accessToken, RefreshToken: loginSuccess.RfToken,
|
AccessToken: accessToken,
|
||||||
Role: string(loginSuccess.Role), UserID: loginSuccess.UserId,
|
RefreshToken: loginSuccess.RfToken,
|
||||||
|
Role: string(loginSuccess.Role),
|
||||||
|
UserID: loginSuccess.UserId,
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,240 +0,0 @@
|
||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"errors"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"Rezina-Backend/internal/domain"
|
|
||||||
"Rezina-Backend/internal/services/authentication"
|
|
||||||
jwtutil "Rezina-Backend/internal/web_server/jwt"
|
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
type deviceLimitData struct {
|
|
||||||
ChallengeToken string `json:"challenge_token"`
|
|
||||||
ExpiresAt string `json:"expires_at"`
|
|
||||||
Devices []deviceSummary `json:"devices"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type deviceSummary struct {
|
|
||||||
ID uuid.UUID `json:"id"`
|
|
||||||
Label string `json:"label"`
|
|
||||||
Platform string `json:"platform"`
|
|
||||||
LastSeenAt string `json:"last_seen_at"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type replaceSessionRequest struct {
|
|
||||||
ChallengeToken string `json:"challenge_token" validate:"required"`
|
|
||||||
SessionID string `json:"session_id" validate:"required"`
|
|
||||||
}
|
|
||||||
|
|
||||||
func deviceInfoFromRequest(c *fiber.Ctx) (domain.DeviceInfo, error) {
|
|
||||||
key := strings.TrimSpace(c.Get("X-Device-Id"))
|
|
||||||
if len(key) > 128 {
|
|
||||||
return domain.DeviceInfo{}, errors.New("X-Device-Id must be at most 128 characters")
|
|
||||||
}
|
|
||||||
platform := strings.ToLower(strings.TrimSpace(c.Get("X-Device-Platform")))
|
|
||||||
ua := strings.ToLower(c.Get("User-Agent"))
|
|
||||||
if platform == "" {
|
|
||||||
switch {
|
|
||||||
case strings.Contains(ua, "android"):
|
|
||||||
platform = "android"
|
|
||||||
case strings.Contains(ua, "iphone") || strings.Contains(ua, "ipad"):
|
|
||||||
platform = "ios"
|
|
||||||
default:
|
|
||||||
platform = "web"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if platform != "web" && platform != "android" && platform != "ios" {
|
|
||||||
return domain.DeviceInfo{}, errors.New("X-Device-Platform must be web, android, or ios")
|
|
||||||
}
|
|
||||||
browser := "Browser"
|
|
||||||
switch {
|
|
||||||
case strings.Contains(ua, "edg/"), strings.Contains(ua, "edgios/"), strings.Contains(ua, "edga/"):
|
|
||||||
browser = "Edge"
|
|
||||||
case strings.Contains(ua, "chrome/"), strings.Contains(ua, "crios/"):
|
|
||||||
browser = "Chrome"
|
|
||||||
case strings.Contains(ua, "firefox/"), strings.Contains(ua, "fxios/"):
|
|
||||||
browser = "Firefox"
|
|
||||||
case strings.Contains(ua, "safari/"):
|
|
||||||
browser = "Safari"
|
|
||||||
}
|
|
||||||
osName := ""
|
|
||||||
switch {
|
|
||||||
case strings.Contains(ua, "android"):
|
|
||||||
osName = "Android"
|
|
||||||
case strings.Contains(ua, "iphone"):
|
|
||||||
osName = "iPhone"
|
|
||||||
case strings.Contains(ua, "ipad"):
|
|
||||||
osName = "iPad"
|
|
||||||
case strings.Contains(ua, "windows"):
|
|
||||||
osName = "Windows"
|
|
||||||
case strings.Contains(ua, "macintosh"), strings.Contains(ua, "mac os x"):
|
|
||||||
osName = "macOS"
|
|
||||||
case strings.Contains(ua, "linux"):
|
|
||||||
osName = "Linux"
|
|
||||||
}
|
|
||||||
label := browser
|
|
||||||
if osName != "" {
|
|
||||||
label += " on " + osName
|
|
||||||
}
|
|
||||||
return domain.DeviceInfo{Key: key, Label: label, Platform: platform}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (h *Handler) respondLearnerLogin(c *fiber.Ctx, login domain.LoginSuccess, message, activityDescription string) error {
|
|
||||||
device, err := deviceInfoFromRequest(c)
|
|
||||||
if err != nil {
|
|
||||||
return c.Status(fiber.StatusBadRequest).JSON(domain.ErrorResponse{Message: "Invalid device information", Error: err.Error()})
|
|
||||||
}
|
|
||||||
issued, err := h.authSvc.IssueLearnerSession(c.Context(), login.UserId, login.Role, device)
|
|
||||||
if err != nil {
|
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to login", Error: err.Error()})
|
|
||||||
}
|
|
||||||
if issued.LimitReached {
|
|
||||||
devices := make([]deviceSummary, 0, len(issued.Devices))
|
|
||||||
for _, item := range issued.Devices {
|
|
||||||
devices = append(devices, deviceSummary{ID: item.ID, Label: item.Label, Platform: item.Platform, LastSeenAt: item.LastSeenAt.Format("2006-01-02T15:04:05.999999999Z07:00")})
|
|
||||||
}
|
|
||||||
return c.Status(fiber.StatusConflict).JSON(fiber.Map{"message": "Device limit reached", "code": "DEVICE_LIMIT_REACHED", "data": deviceLimitData{ChallengeToken: issued.ChallengeToken, ExpiresAt: issued.ChallengeExpires.Format("2006-01-02T15:04:05.999999999Z07:00"), Devices: devices}})
|
|
||||||
}
|
|
||||||
accessToken, err := jwtutil.CreateLearnerJwt(login.UserId, login.Role, issued.Session.ID.String(), h.jwtConfig.JwtAccessKey, h.jwtConfig.JwtAccessExpiry)
|
|
||||||
if err != nil {
|
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to login", Error: "Failed to generate access token"})
|
|
||||||
}
|
|
||||||
if activityDescription != "" {
|
|
||||||
userID := login.UserId
|
|
||||||
h.recordActivityAs(c, userID, login.Role, domain.ActionAuthLogin, domain.ResourceAuth, &userID, activityDescription, nil)
|
|
||||||
}
|
|
||||||
return c.Status(fiber.StatusOK).JSON(domain.Response{Message: message, Data: loginUserRes{AccessToken: accessToken, RefreshToken: issued.RefreshToken, Role: string(login.Role), UserID: login.UserId}})
|
|
||||||
}
|
|
||||||
|
|
||||||
// ReplaceSession godoc
|
|
||||||
// @Summary Replace an active learner device session
|
|
||||||
// @Tags auth
|
|
||||||
// @Accept json
|
|
||||||
// @Produce json
|
|
||||||
// @Param body body replaceSessionRequest true "Session replacement challenge and active session ID"
|
|
||||||
// @Success 200 {object} domain.Response{data=loginUserRes}
|
|
||||||
// @Failure 401 {object} domain.ErrorResponse
|
|
||||||
// @Router /api/v1/auth/sessions/replace [post]
|
|
||||||
func (h *Handler) ReplaceSession(c *fiber.Ctx) error {
|
|
||||||
var req replaceSessionRequest
|
|
||||||
if err := c.BodyParser(&req); err != nil {
|
|
||||||
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{Message: "Invalid session replacement"})
|
|
||||||
}
|
|
||||||
id, err := uuid.Parse(req.SessionID)
|
|
||||||
if err != nil || req.ChallengeToken == "" {
|
|
||||||
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{Message: "Invalid session replacement"})
|
|
||||||
}
|
|
||||||
login, err := h.authSvc.ReplaceLearnerSession(c.Context(), req.ChallengeToken, id)
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, authentication.ErrInvalidDeviceChallenge) || errors.Is(err, authentication.ErrSessionNotFound) {
|
|
||||||
return c.Status(fiber.StatusUnauthorized).JSON(domain.ErrorResponse{Message: "Invalid session replacement"})
|
|
||||||
}
|
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(domain.ErrorResponse{Message: "Failed to replace session"})
|
|
||||||
}
|
|
||||||
accessToken, err := jwtutil.CreateLearnerJwt(login.UserId, login.Role, login.SessionID.String(), h.jwtConfig.JwtAccessKey, h.jwtConfig.JwtAccessExpiry)
|
|
||||||
if err != nil {
|
|
||||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to generate access token")
|
|
||||||
}
|
|
||||||
return c.Status(fiber.StatusOK).JSON(domain.Response{Message: "Login successful", Data: loginUserRes{AccessToken: accessToken, RefreshToken: login.RfToken, Role: string(login.Role), UserID: login.UserId}})
|
|
||||||
}
|
|
||||||
|
|
||||||
// GetMySessions godoc
|
|
||||||
// @Summary List the current learner's active device sessions
|
|
||||||
// @Tags user
|
|
||||||
// @Produce json
|
|
||||||
// @Success 200 {object} domain.Response{data=[]domain.UserSession}
|
|
||||||
// @Security Bearer
|
|
||||||
// @Router /api/v1/user/me/sessions [get]
|
|
||||||
func (h *Handler) GetMySessions(c *fiber.Ctx) error {
|
|
||||||
userID := c.Locals("user_id").(int64)
|
|
||||||
sessions, err := h.authSvc.SessionStore().ListUserSessions(c.Context(), userID)
|
|
||||||
if err != nil {
|
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Failed to list sessions", "code": "SESSION_LIST_FAILED"})
|
|
||||||
}
|
|
||||||
current, _ := c.Locals("session_id").(uuid.UUID)
|
|
||||||
for i := range sessions {
|
|
||||||
sessions[i].IsCurrent = sessions[i].ID == current
|
|
||||||
}
|
|
||||||
return c.JSON(domain.Response{Message: "Active sessions", Data: sessions})
|
|
||||||
}
|
|
||||||
|
|
||||||
// DeleteMySession godoc
|
|
||||||
// @Summary Remove one of the current learner's device sessions
|
|
||||||
// @Tags user
|
|
||||||
// @Param id path string true "Session UUID"
|
|
||||||
// @Success 200 {object} domain.Response
|
|
||||||
// @Failure 404 {object} domain.ErrorResponse
|
|
||||||
// @Security Bearer
|
|
||||||
// @Router /api/v1/user/me/sessions/{id} [delete]
|
|
||||||
func (h *Handler) DeleteMySession(c *fiber.Ctx) error {
|
|
||||||
userID := c.Locals("user_id").(int64)
|
|
||||||
id, err := uuid.Parse(c.Params("id"))
|
|
||||||
if err != nil {
|
|
||||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"message": "Session not found", "code": "SESSION_NOT_FOUND"})
|
|
||||||
}
|
|
||||||
if err := h.authSvc.SessionStore().RevokeOwnUserSession(c.Context(), userID, id, "user_removed"); err != nil {
|
|
||||||
if errors.Is(err, authentication.ErrSessionNotFound) {
|
|
||||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"message": "Session not found", "code": "SESSION_NOT_FOUND"})
|
|
||||||
}
|
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Failed to remove session", "code": "SESSION_REMOVE_FAILED"})
|
|
||||||
}
|
|
||||||
return c.JSON(domain.Response{Message: "Session removed"})
|
|
||||||
}
|
|
||||||
|
|
||||||
// AdminGetUserSessions godoc
|
|
||||||
// @Summary List a user's active device sessions
|
|
||||||
// @Tags admin
|
|
||||||
// @Param user_id path int true "User ID"
|
|
||||||
// @Success 200 {object} domain.Response{data=[]domain.UserSession}
|
|
||||||
// @Security Bearer
|
|
||||||
// @Router /api/v1/admin/users/{user_id}/sessions [get]
|
|
||||||
func (h *Handler) AdminGetUserSessions(c *fiber.Ctx) error {
|
|
||||||
userID, err := c.ParamsInt("user_id")
|
|
||||||
if err != nil || userID <= 0 {
|
|
||||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "Invalid user ID", "code": "INVALID_USER_ID"})
|
|
||||||
}
|
|
||||||
sessions, err := h.authSvc.SessionStore().ListUserSessions(c.Context(), int64(userID))
|
|
||||||
if err != nil {
|
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Failed to list sessions", "code": "SESSION_LIST_FAILED"})
|
|
||||||
}
|
|
||||||
uid := int64(userID)
|
|
||||||
meta, _ := json.Marshal(map[string]any{"target_user_id": userID})
|
|
||||||
h.recordActivity(c, domain.ActionUserUpdated, domain.ResourceUser, &uid, "Viewed user sessions", meta)
|
|
||||||
return c.JSON(domain.Response{Message: "Active sessions", Data: sessions})
|
|
||||||
}
|
|
||||||
|
|
||||||
// AdminDeleteUserSession godoc
|
|
||||||
// @Summary Remove a user's active device session
|
|
||||||
// @Tags admin
|
|
||||||
// @Param user_id path int true "User ID"
|
|
||||||
// @Param id path string true "Session UUID"
|
|
||||||
// @Success 200 {object} domain.Response
|
|
||||||
// @Failure 404 {object} domain.ErrorResponse
|
|
||||||
// @Security Bearer
|
|
||||||
// @Router /api/v1/admin/users/{user_id}/sessions/{id} [delete]
|
|
||||||
func (h *Handler) AdminDeleteUserSession(c *fiber.Ctx) error {
|
|
||||||
targetID, err := c.ParamsInt("user_id")
|
|
||||||
if err != nil || targetID <= 0 {
|
|
||||||
return c.Status(fiber.StatusBadRequest).JSON(fiber.Map{"message": "Invalid user ID", "code": "INVALID_USER_ID"})
|
|
||||||
}
|
|
||||||
id, err := uuid.Parse(c.Params("id"))
|
|
||||||
if err != nil {
|
|
||||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"message": "Session not found", "code": "SESSION_NOT_FOUND"})
|
|
||||||
}
|
|
||||||
err = h.authSvc.SessionStore().RevokeUserSession(c.Context(), int64(targetID), id, "admin_removed")
|
|
||||||
if err != nil {
|
|
||||||
if errors.Is(err, authentication.ErrSessionNotFound) {
|
|
||||||
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{"message": "Session not found", "code": "SESSION_NOT_FOUND"})
|
|
||||||
}
|
|
||||||
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{"message": "Failed to remove session", "code": "SESSION_REMOVE_FAILED"})
|
|
||||||
}
|
|
||||||
meta, _ := json.Marshal(map[string]any{"session_id": id.String(), "target_user_id": targetID})
|
|
||||||
uid := int64(targetID)
|
|
||||||
h.recordActivity(c, domain.ActionUserUpdated, domain.ResourceUser, &uid, "Removed user session", meta)
|
|
||||||
return c.JSON(domain.Response{Message: "Session removed"})
|
|
||||||
}
|
|
||||||
|
|
@ -1,114 +0,0 @@
|
||||||
package handlers
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"Rezina-Backend/internal/domain"
|
|
||||||
"Rezina-Backend/internal/ports"
|
|
||||||
"Rezina-Backend/internal/services/authentication"
|
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
)
|
|
||||||
|
|
||||||
type handlerSessionStore struct {
|
|
||||||
ports.SessionStore
|
|
||||||
owner int64
|
|
||||||
sessionID uuid.UUID
|
|
||||||
active bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDeviceInfoFromRequestUsesBrowserAndUserAgentOS(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
userAgent string
|
|
||||||
platform string
|
|
||||||
label string
|
|
||||||
}{
|
|
||||||
{name: "Chrome Windows", platform: "web", userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36", label: "Chrome on Windows"},
|
|
||||||
{name: "Edge Windows", platform: "web", userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36 Edg/131.0", label: "Edge on Windows"},
|
|
||||||
{name: "Chrome iPhone", platform: "ios", userAgent: "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1 CriOS/131.0 Mobile/15E148 Safari/604.1", label: "Chrome on iPhone"},
|
|
||||||
{name: "Firefox iPad", platform: "ios", userAgent: "Mozilla/5.0 (iPad; CPU OS 18_0 like Mac OS X) AppleWebKit/605.1 FxiOS/132.0 Mobile/15E148 Safari/605.1", label: "Firefox on iPad"},
|
|
||||||
{name: "Safari macOS", platform: "web", userAgent: "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7) AppleWebKit/605.1 Version/18.0 Safari/605.1", label: "Safari on macOS"},
|
|
||||||
{name: "Chrome Android with web platform", platform: "web", userAgent: "Mozilla/5.0 (Linux; Android 15) AppleWebKit/537.36 Chrome/131.0 Mobile Safari/537.36", label: "Chrome on Android"},
|
|
||||||
{name: "Firefox Linux", platform: "web", userAgent: "Mozilla/5.0 (X11; Linux x86_64; rv:133.0) Gecko/20100101 Firefox/133.0", label: "Firefox on Linux"},
|
|
||||||
{name: "Unknown OS", platform: "web", userAgent: "CustomBrowser/1.0", label: "Browser"},
|
|
||||||
}
|
|
||||||
for _, test := range tests {
|
|
||||||
t.Run(test.name, func(t *testing.T) {
|
|
||||||
app := fiber.New()
|
|
||||||
app.Get("/", func(c *fiber.Ctx) error {
|
|
||||||
device, err := deviceInfoFromRequest(c)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
return c.JSON(device)
|
|
||||||
})
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
||||||
req.Header.Set("User-Agent", test.userAgent)
|
|
||||||
req.Header.Set("X-Device-Platform", test.platform)
|
|
||||||
res, err := app.Test(req)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer res.Body.Close()
|
|
||||||
var device domain.DeviceInfo
|
|
||||||
if err := json.NewDecoder(res.Body).Decode(&device); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if device.Label != test.label || device.Platform != test.platform {
|
|
||||||
t.Fatalf("device = %#v, want label %q platform %q", device, test.label, test.platform)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *handlerSessionStore) CreateRefreshToken(context.Context, domain.RefreshToken) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
func (s *handlerSessionStore) GetRefreshToken(context.Context, string) (domain.RefreshToken, error) {
|
|
||||||
return domain.RefreshToken{}, authentication.ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
func (s *handlerSessionStore) GetRefreshTokenByUserID(context.Context, int64) (domain.RefreshToken, error) {
|
|
||||||
return domain.RefreshToken{}, authentication.ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
func (s *handlerSessionStore) RevokeRefreshToken(context.Context, string) error { return nil }
|
|
||||||
func (s *handlerSessionStore) ListUserSessions(context.Context, int64) ([]domain.UserSession, error) {
|
|
||||||
return []domain.UserSession{{ID: s.sessionID, UserID: s.owner, Label: "Chrome on Web", Platform: "web"}}, nil
|
|
||||||
}
|
|
||||||
func (s *handlerSessionStore) RevokeOwnUserSession(_ context.Context, userID int64, id uuid.UUID, _ string) error {
|
|
||||||
if !s.active || userID != s.owner || id != s.sessionID {
|
|
||||||
return authentication.ErrSessionNotFound
|
|
||||||
}
|
|
||||||
s.active = false
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestDeleteMySessionOwnership(t *testing.T) {
|
|
||||||
id := uuid.New()
|
|
||||||
store := &handlerSessionStore{owner: 7, sessionID: id, active: true}
|
|
||||||
svc := authentication.NewService(nil, nil, nil, store, 3600)
|
|
||||||
h := &Handler{authSvc: svc}
|
|
||||||
app := fiber.New()
|
|
||||||
app.Delete("/sessions/:id", func(c *fiber.Ctx) error { c.Locals("user_id", int64(8)); return c.Next() }, h.DeleteMySession)
|
|
||||||
res, err := app.Test(httptest.NewRequest(http.MethodDelete, "/sessions/"+id.String(), nil))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if res.StatusCode != http.StatusNotFound {
|
|
||||||
t.Fatalf("other user's status=%d", res.StatusCode)
|
|
||||||
}
|
|
||||||
app = fiber.New()
|
|
||||||
app.Delete("/sessions/:id", func(c *fiber.Ctx) error { c.Locals("user_id", int64(7)); return c.Next() }, h.DeleteMySession)
|
|
||||||
res, err = app.Test(httptest.NewRequest(http.MethodDelete, "/sessions/"+id.String(), nil))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if res.StatusCode != http.StatusOK || store.active {
|
|
||||||
t.Fatalf("owner status=%d active=%v", res.StatusCode, store.active)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -21,7 +21,6 @@ type UserClaim struct {
|
||||||
UserId int64
|
UserId int64
|
||||||
Role domain.Role
|
Role domain.Role
|
||||||
CompanyID domain.NullJwtInt64
|
CompanyID domain.NullJwtInt64
|
||||||
Sid string `json:"sid,omitempty"`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type JwtConfig struct {
|
type JwtConfig struct {
|
||||||
|
|
@ -30,14 +29,6 @@ type JwtConfig struct {
|
||||||
}
|
}
|
||||||
|
|
||||||
func CreateJwt(userId int64, Role domain.Role, key string, expiry int) (string, error) {
|
func CreateJwt(userId int64, Role domain.Role, key string, expiry int) (string, error) {
|
||||||
return createJwt(userId, Role, "", key, expiry)
|
|
||||||
}
|
|
||||||
|
|
||||||
func CreateLearnerJwt(userId int64, role domain.Role, sessionID string, key string, expiry int) (string, error) {
|
|
||||||
return createJwt(userId, role, sessionID, key, expiry)
|
|
||||||
}
|
|
||||||
|
|
||||||
func createJwt(userId int64, Role domain.Role, sessionID string, key string, expiry int) (string, error) {
|
|
||||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, UserClaim{
|
token := jwt.NewWithClaims(jwt.SigningMethodHS256, UserClaim{
|
||||||
RegisteredClaims: jwt.RegisteredClaims{
|
RegisteredClaims: jwt.RegisteredClaims{
|
||||||
Issuer: "rezina.com",
|
Issuer: "rezina.com",
|
||||||
|
|
@ -48,7 +39,6 @@ func createJwt(userId int64, Role domain.Role, sessionID string, key string, exp
|
||||||
},
|
},
|
||||||
UserId: userId,
|
UserId: userId,
|
||||||
Role: Role,
|
Role: Role,
|
||||||
Sid: sessionID,
|
|
||||||
// CompanyID: domain.NullJwtInt64{
|
// CompanyID: domain.NullJwtInt64{
|
||||||
// Value: CompanyID.Value,
|
// Value: CompanyID.Value,
|
||||||
// Valid: CompanyID.Valid,
|
// Valid: CompanyID.Valid,
|
||||||
|
|
|
||||||
|
|
@ -2,7 +2,6 @@ package httpserver
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"Rezina-Backend/internal/domain"
|
"Rezina-Backend/internal/domain"
|
||||||
"Rezina-Backend/internal/services/authentication"
|
|
||||||
examprepsvc "Rezina-Backend/internal/services/examprep"
|
examprepsvc "Rezina-Backend/internal/services/examprep"
|
||||||
"Rezina-Backend/internal/web_server/fileurls"
|
"Rezina-Backend/internal/web_server/fileurls"
|
||||||
jwtutil "Rezina-Backend/internal/web_server/jwt"
|
jwtutil "Rezina-Backend/internal/web_server/jwt"
|
||||||
|
|
@ -15,7 +14,6 @@ import (
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
"github.com/gofiber/fiber/v2"
|
||||||
"github.com/google/uuid"
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -42,6 +40,7 @@ func (a *App) authMiddleware(c *fiber.Ctx) error {
|
||||||
|
|
||||||
if !strings.HasPrefix(authHeader, "Bearer ") {
|
if !strings.HasPrefix(authHeader, "Bearer ") {
|
||||||
a.mongoLoggerSvc.Info("Invalid authorization header format",
|
a.mongoLoggerSvc.Info("Invalid authorization header format",
|
||||||
|
zap.String("authHeader", authHeader),
|
||||||
zap.Int("status_code", fiber.StatusUnauthorized),
|
zap.Int("status_code", fiber.StatusUnauthorized),
|
||||||
zap.String("ip_address", ip),
|
zap.String("ip_address", ip),
|
||||||
zap.String("user_agent", userAgent),
|
zap.String("user_agent", userAgent),
|
||||||
|
|
@ -108,12 +107,6 @@ func (a *App) authMiddleware(c *fiber.Ctx) error {
|
||||||
|
|
||||||
userRole := claim.Role
|
userRole := claim.Role
|
||||||
if userRole.IsCustomerLearnerRole() {
|
if userRole.IsCustomerLearnerRole() {
|
||||||
if err := a.validateLearnerSession(c, claim); err != nil {
|
|
||||||
if errors.Is(err, authentication.ErrSessionRevoked) {
|
|
||||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Session revoked", "code": "SESSION_REVOKED"})
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
status, err := a.userSvc.GetAuthStatus(c.Context(), claim.UserId)
|
status, err := a.userSvc.GetAuthStatus(c.Context(), claim.UserId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if errors.Is(err, domain.ErrUserNotFound) {
|
if errors.Is(err, domain.ErrUserNotFound) {
|
||||||
|
|
@ -568,12 +561,6 @@ func (a *App) WebsocketAuthMiddleware(c *fiber.Ctx) error {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if claim.Role.IsCustomerLearnerRole() {
|
if claim.Role.IsCustomerLearnerRole() {
|
||||||
if err := a.validateLearnerSession(c, claim); err != nil {
|
|
||||||
if errors.Is(err, authentication.ErrSessionRevoked) {
|
|
||||||
return c.Status(fiber.StatusUnauthorized).JSON(fiber.Map{"message": "Session revoked", "code": "SESSION_REVOKED"})
|
|
||||||
}
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
status, err := a.userSvc.GetAuthStatus(c.Context(), claim.UserId)
|
status, err := a.userSvc.GetAuthStatus(c.Context(), claim.UserId)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fiber.NewError(fiber.StatusUnauthorized, "Unable to validate customer account")
|
return fiber.NewError(fiber.StatusUnauthorized, "Unable to validate customer account")
|
||||||
|
|
@ -601,26 +588,6 @@ func (a *App) WebsocketAuthMiddleware(c *fiber.Ctx) error {
|
||||||
return c.Next()
|
return c.Next()
|
||||||
}
|
}
|
||||||
|
|
||||||
func (a *App) validateLearnerSession(c *fiber.Ctx, claim *jwtutil.UserClaim) error {
|
|
||||||
if claim.Sid == "" {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
sessionID, err := uuid.Parse(claim.Sid)
|
|
||||||
if err != nil || a.authSvc == nil || a.authSvc.SessionStore() == nil {
|
|
||||||
return authentication.ErrSessionRevoked
|
|
||||||
}
|
|
||||||
active, err := a.authSvc.SessionStore().IsUserSessionActive(c.Context(), sessionID, claim.UserId)
|
|
||||||
if err != nil {
|
|
||||||
a.mongoLoggerSvc.Error("Failed to validate user session", zap.Int64("userID", claim.UserId), zap.Error(err))
|
|
||||||
return fiber.NewError(fiber.StatusInternalServerError, "Failed to validate session")
|
|
||||||
}
|
|
||||||
if !active {
|
|
||||||
return authentication.ErrSessionRevoked
|
|
||||||
}
|
|
||||||
c.Locals("session_id", sessionID)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (a *App) TenantMiddleware(c *fiber.Ctx) error {
|
func (a *App) TenantMiddleware(c *fiber.Ctx) error {
|
||||||
tenantSlug := c.Params("tenant_slug")
|
tenantSlug := c.Params("tenant_slug")
|
||||||
if tenantSlug == "" {
|
if tenantSlug == "" {
|
||||||
|
|
|
||||||
|
|
@ -145,8 +145,6 @@ func (a *App) initAdminRoutes(api fiber.Router, h *handlers.Handler) {
|
||||||
api.Get("/users/:user_id/recent-activity", a.adminAuthMiddleware, a.RequirePermission("progress.get_any_user"), h.AdminGetUserRecentActivity)
|
api.Get("/users/:user_id/recent-activity", a.adminAuthMiddleware, a.RequirePermission("progress.get_any_user"), h.AdminGetUserRecentActivity)
|
||||||
api.Get("/users/:user_id/learning-activity", a.adminAuthMiddleware, a.RequirePermission("progress.get_any_user"), h.AdminGetUserLearningActivityDetails)
|
api.Get("/users/:user_id/learning-activity", a.adminAuthMiddleware, a.RequirePermission("progress.get_any_user"), h.AdminGetUserLearningActivityDetails)
|
||||||
api.Get("/users/:user_id/subscriptions", a.adminAuthMiddleware, a.RequirePermission("subscriptions.get_by_user"), h.AdminGetUserSubscriptions)
|
api.Get("/users/:user_id/subscriptions", a.adminAuthMiddleware, a.RequirePermission("subscriptions.get_by_user"), h.AdminGetUserSubscriptions)
|
||||||
api.Get("/users/:user_id/sessions", a.adminAuthMiddleware, a.RequirePermission("users.get"), h.AdminGetUserSessions)
|
|
||||||
api.Delete("/users/:user_id/sessions/:id", a.adminAuthMiddleware, a.RequirePermission("users.update_status"), h.AdminDeleteUserSession)
|
|
||||||
api.Post("/users/:user_id/subscriptions/extend", a.adminAuthMiddleware, a.RequirePermission("subscriptions.admin_extend"), h.AdminExtendOrGrantUserSubscription)
|
api.Post("/users/:user_id/subscriptions/extend", a.adminAuthMiddleware, a.RequirePermission("subscriptions.admin_extend"), h.AdminExtendOrGrantUserSubscription)
|
||||||
api.Get("/users/summary", a.adminAuthMiddleware, a.RequirePermission("users.summary"), h.GetUserSummary)
|
api.Get("/users/summary", a.adminAuthMiddleware, a.RequirePermission("users.summary"), h.GetUserSummary)
|
||||||
api.Patch("/user/status", a.adminAuthMiddleware, a.RequirePermission("users.update_status"), h.UpdateUserStatus)
|
api.Patch("/user/status", a.adminAuthMiddleware, a.RequirePermission("users.update_status"), h.UpdateUserStatus)
|
||||||
|
|
|
||||||
|
|
@ -80,7 +80,6 @@ func (a *App) initClientRoutes(api fiber.Router, h *handlers.Handler) {
|
||||||
api.Get("/auth/google/login", apiAudience("client"), h.GoogleLogin)
|
api.Get("/auth/google/login", apiAudience("client"), h.GoogleLogin)
|
||||||
api.Post("/auth/apple", apiAudience("client"), h.AppleLogin)
|
api.Post("/auth/apple", apiAudience("client"), h.AppleLogin)
|
||||||
api.Post("/auth/customer-login", apiAudience("client"), h.LoginUser)
|
api.Post("/auth/customer-login", apiAudience("client"), h.LoginUser)
|
||||||
api.Post("/auth/sessions/replace", apiAudience("client"), h.ReplaceSession)
|
|
||||||
api.Post("/auth/refresh", apiAudience("client"), h.RefreshToken)
|
api.Post("/auth/refresh", apiAudience("client"), h.RefreshToken)
|
||||||
api.Post("/user/:id/profile-picture", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("users.upload_profile_picture"), h.UploadProfilePicture)
|
api.Post("/user/:id/profile-picture", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("users.upload_profile_picture"), h.UploadProfilePicture)
|
||||||
api.Post("/auth/logout", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("auth.logout"), h.LogOutuser)
|
api.Post("/auth/logout", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("auth.logout"), h.LogOutuser)
|
||||||
|
|
@ -96,8 +95,6 @@ func (a *App) initClientRoutes(api fiber.Router, h *handlers.Handler) {
|
||||||
api.Post("/user/sendRegisterCode", apiAudience("client"), h.SendRegisterCode)
|
api.Post("/user/sendRegisterCode", apiAudience("client"), h.SendRegisterCode)
|
||||||
api.Post("/user/checkPhoneEmailExist", apiAudience("client"), h.CheckPhoneEmailExist)
|
api.Post("/user/checkPhoneEmailExist", apiAudience("client"), h.CheckPhoneEmailExist)
|
||||||
api.Get("/user/user-profile", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("users.user_profile"), h.GetUserProfile)
|
api.Get("/user/user-profile", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("users.user_profile"), h.GetUserProfile)
|
||||||
api.Get("/user/me/sessions", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("users.user_profile"), h.GetMySessions)
|
|
||||||
api.Delete("/user/me/sessions/:id", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("users.update_self"), h.DeleteMySession)
|
|
||||||
api.Delete("/user/me", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("users.delete_self"), h.DeleteMyUserAccount)
|
api.Delete("/user/me", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("users.delete_self"), h.DeleteMyUserAccount)
|
||||||
api.Post("/user/me/deletion/cancel", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("users.cancel_delete_self"), h.CancelMyUserAccountDeletion)
|
api.Post("/user/me/deletion/cancel", apiAudience("client"), a.clientAuthMiddleware, a.RequirePermission("users.cancel_delete_self"), h.CancelMyUserAccountDeletion)
|
||||||
api.Get("/ws/connect", apiAudience("client"), a.clientWebsocketAuthMiddleware, h.ConnectSocket)
|
api.Get("/ws/connect", apiAudience("client"), a.clientWebsocketAuthMiddleware, h.ConnectSocket)
|
||||||
|
|
|
||||||
|
|
@ -1,89 +0,0 @@
|
||||||
package httpserver
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"encoding/json"
|
|
||||||
"io"
|
|
||||||
"log/slog"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"Rezina-Backend/internal/domain"
|
|
||||||
"Rezina-Backend/internal/ports"
|
|
||||||
"Rezina-Backend/internal/services/authentication"
|
|
||||||
userservice "Rezina-Backend/internal/services/user"
|
|
||||||
jwtutil "Rezina-Backend/internal/web_server/jwt"
|
|
||||||
|
|
||||||
"github.com/gofiber/fiber/v2"
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"go.uber.org/zap"
|
|
||||||
)
|
|
||||||
|
|
||||||
type middlewareUserStore struct{ ports.UserStore }
|
|
||||||
|
|
||||||
func (middlewareUserStore) GetUserByID(_ context.Context, id int64) (domain.User, error) {
|
|
||||||
return domain.User{ID: id, Role: domain.RoleStudent, Status: domain.UserStatusActive}, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
type middlewareSessionStore struct {
|
|
||||||
ports.SessionStore
|
|
||||||
active bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *middlewareSessionStore) CreateRefreshToken(context.Context, domain.RefreshToken) error {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
func (s *middlewareSessionStore) GetRefreshToken(context.Context, string) (domain.RefreshToken, error) {
|
|
||||||
return domain.RefreshToken{}, authentication.ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
func (s *middlewareSessionStore) GetRefreshTokenByUserID(context.Context, int64) (domain.RefreshToken, error) {
|
|
||||||
return domain.RefreshToken{}, authentication.ErrRefreshTokenNotFound
|
|
||||||
}
|
|
||||||
func (s *middlewareSessionStore) RevokeRefreshToken(context.Context, string) error { return nil }
|
|
||||||
func (s *middlewareSessionStore) IsUserSessionActive(context.Context, uuid.UUID, int64) (bool, error) {
|
|
||||||
return s.active, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func middlewareTestApp(active bool) *App {
|
|
||||||
users := middlewareUserStore{}
|
|
||||||
store := &middlewareSessionStore{active: active}
|
|
||||||
auth := authentication.NewService(nil, users, nil, store, 3600)
|
|
||||||
return &App{authSvc: auth, userSvc: userservice.NewService(nil, users, nil, nil, nil, nil, nil), JwtConfig: jwtutil.JwtConfig{JwtAccessKey: "session-test"}, mongoLoggerSvc: zap.NewNop(), logger: slog.Default()}
|
|
||||||
}
|
|
||||||
func performMiddlewareRequest(t *testing.T, app *App, token string) (int, map[string]any) {
|
|
||||||
t.Helper()
|
|
||||||
server := fiber.New()
|
|
||||||
server.Get("/", app.authMiddleware, func(c *fiber.Ctx) error { return c.JSON(fiber.Map{"ok": true}) })
|
|
||||||
req := httptest.NewRequest("GET", "/", nil)
|
|
||||||
req.Header.Set("Authorization", "Bearer "+token)
|
|
||||||
res, err := server.Test(req)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
body, _ := io.ReadAll(res.Body)
|
|
||||||
var decoded map[string]any
|
|
||||||
_ = json.Unmarshal(body, &decoded)
|
|
||||||
return res.StatusCode, decoded
|
|
||||||
}
|
|
||||||
func TestAuthMiddlewareRejectsRevokedSession(t *testing.T) {
|
|
||||||
app := middlewareTestApp(false)
|
|
||||||
token, err := jwtutil.CreateLearnerJwt(7, domain.RoleStudent, uuid.NewString(), app.JwtConfig.JwtAccessKey, 3600)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
status, body := performMiddlewareRequest(t, app, token)
|
|
||||||
if status != fiber.StatusUnauthorized || body["code"] != "SESSION_REVOKED" {
|
|
||||||
t.Fatalf("status=%d body=%v", status, body)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
func TestAuthMiddlewareAcceptsLegacyLearnerJWT(t *testing.T) {
|
|
||||||
app := middlewareTestApp(false)
|
|
||||||
token, err := jwtutil.CreateJwt(7, domain.RoleStudent, app.JwtConfig.JwtAccessKey, 3600)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
status, _ := performMiddlewareRequest(t, app, token)
|
|
||||||
if status != fiber.StatusOK {
|
|
||||||
t.Fatalf("status=%d", status)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Loading…
Reference in New Issue
Block a user