fetch auth session data from token

This commit is contained in:
2025-07-18 12:11:29 +02:00
parent 026f84b870
commit 1a6c60ff03
19 changed files with 368 additions and 20 deletions

View File

@@ -35,6 +35,10 @@ impl AuthSession {
pub fn user_id(&self) -> &Uuid { pub fn user_id(&self) -> &Uuid {
&self.user_id &self.user_id
} }
pub fn expires_at(&self) -> &NaiveDateTime {
&self.expires_at
}
} }
/// A valid auth session id /// A valid auth session id

View File

@@ -2,6 +2,8 @@ use thiserror::Error;
use crate::domain::warren::models::user::User; use crate::domain::warren::models::user::User;
use super::{AuthSession, AuthSessionId};
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CreateAuthSessionRequest { pub struct CreateAuthSessionRequest {
user: User, user: User,
@@ -43,3 +45,48 @@ impl SessionExpirationTime {
self.0 self.0
} }
} }
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FetchAuthSessionRequest {
session_id: AuthSessionId,
}
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct FetchAuthSessionResponse {
session: AuthSession,
user: User,
}
impl FetchAuthSessionResponse {
pub fn new(session: AuthSession, user: User) -> Self {
Self { session, user }
}
pub fn session(&self) -> &AuthSession {
&self.session
}
pub fn user(&self) -> &User {
&self.user
}
}
impl FetchAuthSessionRequest {
pub fn new(session_id: AuthSessionId) -> Self {
Self { session_id }
}
pub fn session_id(&self) -> &AuthSessionId {
&self.session_id
}
}
#[derive(Debug, Error)]
pub enum FetchAuthSessionError {
#[error("There is no auth session with this id")]
NotFound,
#[error("The auth session has expired")]
Expired,
#[error(transparent)]
Unknown(#[from] anyhow::Error),
}

View File

@@ -58,4 +58,7 @@ pub trait AuthMetrics: Clone + Send + Sync + 'static {
fn record_auth_session_creation_success(&self) -> impl Future<Output = ()> + Send; fn record_auth_session_creation_success(&self) -> impl Future<Output = ()> + Send;
fn record_auth_session_creation_failure(&self) -> impl Future<Output = ()> + Send; fn record_auth_session_creation_failure(&self) -> impl Future<Output = ()> + Send;
fn record_auth_session_fetch_success(&self) -> impl Future<Output = ()> + Send;
fn record_auth_session_fetch_failure(&self) -> impl Future<Output = ()> + Send;
} }

View File

@@ -9,7 +9,10 @@ pub use repository::*;
use super::models::{ use super::models::{
auth_session::{ auth_session::{
AuthSession, AuthSession,
requests::{CreateAuthSessionError, CreateAuthSessionRequest}, requests::{
CreateAuthSessionError, CreateAuthSessionRequest, FetchAuthSessionError,
FetchAuthSessionRequest, FetchAuthSessionResponse,
},
}, },
file::{ file::{
CreateDirectoryError, CreateDirectoryRequest, CreateFileError, CreateFileRequest, CreateDirectoryError, CreateDirectoryRequest, CreateFileError, CreateFileRequest,
@@ -110,4 +113,8 @@ pub trait AuthService: Clone + Send + Sync + 'static {
&self, &self,
request: CreateAuthSessionRequest, request: CreateAuthSessionRequest,
) -> impl Future<Output = Result<AuthSession, CreateAuthSessionError>> + Send; ) -> impl Future<Output = Result<AuthSession, CreateAuthSessionError>> + Send;
fn fetch_auth_session(
&self,
request: FetchAuthSessionRequest,
) -> impl Future<Output = Result<FetchAuthSessionResponse, FetchAuthSessionError>> + Send;
} }

View File

@@ -1,6 +1,7 @@
use uuid::Uuid; use uuid::Uuid;
use crate::domain::warren::models::{ use crate::domain::warren::models::{
auth_session::requests::FetchAuthSessionResponse,
file::{AbsoluteFilePath, File, FilePath}, file::{AbsoluteFilePath, File, FilePath},
user::User, user::User,
warren::Warren, warren::Warren,
@@ -76,4 +77,8 @@ pub trait AuthNotifier: Clone + Send + Sync + 'static {
fn user_registered(&self, user: &User) -> impl Future<Output = ()> + Send; fn user_registered(&self, user: &User) -> impl Future<Output = ()> + Send;
fn user_logged_in(&self, user: &User) -> impl Future<Output = ()> + Send; fn user_logged_in(&self, user: &User) -> impl Future<Output = ()> + Send;
fn auth_session_created(&self, user_id: &Uuid) -> impl Future<Output = ()> + Send; fn auth_session_created(&self, user_id: &Uuid) -> impl Future<Output = ()> + Send;
fn auth_session_fetched(
&self,
response: &FetchAuthSessionResponse,
) -> impl Future<Output = ()> + Send;
} }

View File

@@ -1,7 +1,10 @@
use crate::domain::warren::models::{ use crate::domain::warren::models::{
auth_session::{ auth_session::{
AuthSession, AuthSession,
requests::{CreateAuthSessionError, CreateAuthSessionRequest}, requests::{
CreateAuthSessionError, CreateAuthSessionRequest, FetchAuthSessionError,
FetchAuthSessionRequest, FetchAuthSessionResponse,
},
}, },
file::{ file::{
CreateDirectoryError, CreateDirectoryRequest, CreateFileError, CreateFileRequest, CreateDirectoryError, CreateDirectoryRequest, CreateFileError, CreateFileRequest,
@@ -70,4 +73,8 @@ pub trait AuthRepository: Clone + Send + Sync + 'static {
&self, &self,
request: CreateAuthSessionRequest, request: CreateAuthSessionRequest,
) -> impl Future<Output = Result<AuthSession, CreateAuthSessionError>> + Send; ) -> impl Future<Output = Result<AuthSession, CreateAuthSessionError>> + Send;
fn fetch_auth_session(
&self,
request: FetchAuthSessionRequest,
) -> impl Future<Output = Result<FetchAuthSessionResponse, FetchAuthSessionError>> + Send;
} }

View File

@@ -5,7 +5,8 @@ use crate::{
auth_session::{ auth_session::{
AuthSession, AuthSession,
requests::{ requests::{
CreateAuthSessionError, CreateAuthSessionRequest, SessionExpirationTime, CreateAuthSessionError, CreateAuthSessionRequest, FetchAuthSessionError,
FetchAuthSessionRequest, FetchAuthSessionResponse, SessionExpirationTime,
}, },
}, },
user::{ user::{
@@ -131,4 +132,20 @@ where
result result
} }
async fn fetch_auth_session(
&self,
request: FetchAuthSessionRequest,
) -> Result<FetchAuthSessionResponse, FetchAuthSessionError> {
let result = self.repository.fetch_auth_session(request).await;
if let Ok(response) = result.as_ref() {
self.metrics.record_auth_session_fetch_success().await;
self.notifier.auth_session_fetched(response).await;
} else {
self.metrics.record_auth_session_fetch_failure().await;
}
result
}
} }

View File

@@ -1,5 +1,6 @@
use crate::{ use crate::{
domain::warren::models::{ domain::warren::models::{
auth_session::requests::FetchAuthSessionError,
file::{CreateDirectoryError, DeleteDirectoryError, DeleteFileError, ListFilesError}, file::{CreateDirectoryError, DeleteDirectoryError, DeleteFileError, ListFilesError},
user::{LoginUserError, RegisterUserError, VerifyUserPasswordError}, user::{LoginUserError, RegisterUserError, VerifyUserPasswordError},
warren::{ warren::{
@@ -152,3 +153,17 @@ impl From<LoginUserError> for ApiError {
} }
} }
} }
impl From<FetchAuthSessionError> for ApiError {
fn from(value: FetchAuthSessionError) -> Self {
match value {
FetchAuthSessionError::NotFound => {
Self::BadRequest("This session does not exist".to_string())
}
FetchAuthSessionError::Expired => {
Self::BadRequest("This session has expired".to_string())
}
FetchAuthSessionError::Unknown(e) => Self::InternalServerError(e.to_string()),
}
}
}

View File

@@ -0,0 +1,82 @@
use axum::{
extract::State,
http::{HeaderMap, StatusCode},
};
use serde::Serialize;
use uuid::Uuid;
use crate::{
domain::warren::{
models::{
auth_session::{
AuthSessionId,
requests::{FetchAuthSessionRequest, FetchAuthSessionResponse},
},
user::User,
},
ports::{AuthService, WarrenService},
},
inbound::http::{
AppState,
responses::{ApiError, ApiSuccess},
},
};
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
struct SessionUser {
id: Uuid,
name: String,
email: String,
admin: bool,
}
impl From<User> for SessionUser {
fn from(value: User) -> Self {
Self {
id: *value.id(),
name: value.name().to_string(),
email: value.email().to_string(),
admin: value.admin(),
}
}
}
#[derive(Debug, Clone, Serialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct FetchSessionResponseBody {
user: SessionUser,
expires_at: i64,
}
impl From<FetchAuthSessionResponse> for FetchSessionResponseBody {
fn from(value: FetchAuthSessionResponse) -> Self {
Self {
user: value.user().clone().into(),
expires_at: value.session().expires_at().and_utc().timestamp_millis(),
}
}
}
pub async fn fetch_session<WS: WarrenService, AS: AuthService>(
State(state): State<AppState<WS, AS>>,
headers: HeaderMap,
) -> Result<ApiSuccess<FetchSessionResponseBody>, ApiError> {
let Some(Ok(Ok(session_id))) = headers.get("authorization").map(|h| {
h.to_str()
.map(|h| AuthSessionId::new(&h["WarrenAuth ".len()..]))
}) else {
return Err(ApiError::BadRequest(
"No authorization header set".to_string(),
));
};
let domain_request = FetchAuthSessionRequest::new(session_id);
state
.auth_service
.fetch_auth_session(domain_request)
.await
.map(|response| ApiSuccess::new(StatusCode::OK, response.into()))
.map_err(ApiError::from)
}

View File

@@ -66,6 +66,7 @@ impl LoginUserHttpRequestBody {
} }
} }
// TODO: Include `user` and `expires_at` fields
#[derive(Debug, Clone, PartialEq, Serialize)] #[derive(Debug, Clone, PartialEq, Serialize)]
pub struct LoginResponseBody { pub struct LoginResponseBody {
token: String, token: String,

View File

@@ -1,9 +1,14 @@
mod fetch_session;
mod login; mod login;
mod register; mod register;
use fetch_session::fetch_session;
use login::login; use login::login;
use register::register; use register::register;
use axum::{Router, routing::post}; use axum::{
Router,
routing::{get, post},
};
use crate::{ use crate::{
domain::warren::ports::{AuthService, WarrenService}, domain::warren::ports::{AuthService, WarrenService},
@@ -14,4 +19,5 @@ pub fn routes<WS: WarrenService, AS: AuthService>() -> Router<AppState<WS, AS>>
Router::new() Router::new()
.route("/register", post(register)) .route("/register", post(register))
.route("/login", post(login)) .route("/login", post(login))
.route("/session", get(fetch_session))
} }

View File

@@ -144,4 +144,11 @@ impl AuthMetrics for MetricsDebugLogger {
async fn record_auth_session_creation_failure(&self) { async fn record_auth_session_creation_failure(&self) {
tracing::debug!("[Metrics] Auth session creation failed"); tracing::debug!("[Metrics] Auth session creation failed");
} }
async fn record_auth_session_fetch_success(&self) {
tracing::debug!("[Metrics] Auth session fetch succeeded");
}
async fn record_auth_session_fetch_failure(&self) {
tracing::debug!("[Metrics] Auth session fetch failed");
}
} }

View File

@@ -2,6 +2,7 @@ use uuid::Uuid;
use crate::domain::warren::{ use crate::domain::warren::{
models::{ models::{
auth_session::requests::FetchAuthSessionResponse,
file::{File, FilePath}, file::{File, FilePath},
user::User, user::User,
warren::Warren, warren::Warren,
@@ -128,4 +129,11 @@ impl AuthNotifier for NotifierDebugLogger {
async fn auth_session_created(&self, user_id: &Uuid) { async fn auth_session_created(&self, user_id: &Uuid) {
tracing::debug!("[Notifier] Created auth session for user {}", user_id); tracing::debug!("[Notifier] Created auth session for user {}", user_id);
} }
async fn auth_session_fetched(&self, response: &FetchAuthSessionResponse) {
tracing::debug!(
"[Notifier] Fetched auth session for user {}",
response.user().id()
);
}
} }

View File

@@ -18,8 +18,11 @@ use uuid::Uuid;
use crate::domain::warren::{ use crate::domain::warren::{
models::{ models::{
auth_session::{ auth_session::{
AuthSession, AuthSession, AuthSessionId,
requests::{CreateAuthSessionError, CreateAuthSessionRequest, SessionExpirationTime}, requests::{
CreateAuthSessionError, CreateAuthSessionRequest, FetchAuthSessionError,
FetchAuthSessionRequest, FetchAuthSessionResponse, SessionExpirationTime,
},
}, },
user::{ user::{
RegisterUserError, RegisterUserRequest, User, UserEmail, UserName, UserPassword, RegisterUserError, RegisterUserRequest, User, UserEmail, UserName, UserPassword,
@@ -163,6 +166,28 @@ impl Postgres {
Ok(user) Ok(user)
} }
async fn get_user_from_id(
&self,
connection: &mut PgConnection,
id: &Uuid,
) -> Result<User, sqlx::Error> {
let user: User = sqlx::query_as(
"
SELECT
*
FROM
users
WHERE
id = $1
",
)
.bind(id)
.fetch_one(connection)
.await?;
Ok(user)
}
async fn get_user_from_email( async fn get_user_from_email(
&self, &self,
connection: &mut PgConnection, connection: &mut PgConnection,
@@ -245,6 +270,28 @@ impl Postgres {
Ok(session) Ok(session)
} }
async fn get_auth_session(
&self,
connection: &mut PgConnection,
session_id: &AuthSessionId,
) -> anyhow::Result<AuthSession> {
let session: AuthSession = sqlx::query_as(
"
SELECT
*
FROM
auth_sessions
WHERE
session_id = $1
",
)
.bind(session_id)
.fetch_one(connection)
.await?;
Ok(session)
}
} }
impl WarrenRepository for Postgres { impl WarrenRepository for Postgres {
@@ -355,6 +402,28 @@ impl AuthRepository for Postgres {
Ok(session) Ok(session)
} }
async fn fetch_auth_session(
&self,
request: FetchAuthSessionRequest,
) -> Result<FetchAuthSessionResponse, FetchAuthSessionError> {
let mut connection = self
.pool
.acquire()
.await
.context("Failed to get a PostgreSQL connection")?;
let session = self
.get_auth_session(&mut connection, request.session_id())
.await
.context("Failed to get auth session")?;
let user = self
.get_user_from_id(&mut connection, session.user_id())
.await
.context("Failed to get user")?;
Ok(FetchAuthSessionResponse::new(session, user))
}
} }
fn is_not_found_error(err: &sqlx::Error) -> bool { fn is_not_found_error(err: &sqlx::Error) -> bool {

View File

@@ -15,6 +15,7 @@ import {
const route = useRoute(); const route = useRoute();
const store = useWarrenStore(); const store = useWarrenStore();
const session = useAuthSession();
async function selectWarren(id: string) { async function selectWarren(id: string) {
await store.setCurrentWarren(id, '/'); await store.setCurrentWarren(id, '/');
@@ -77,7 +78,7 @@ async function selectWarren(id: string) {
</SidebarGroup> </SidebarGroup>
</SidebarContent> </SidebarContent>
<SidebarFooter> <SidebarFooter>
<SidebarUser /> <SidebarUser v-if="session != null" :user="session.user" />
</SidebarFooter> </SidebarFooter>
</Sidebar> </Sidebar>
</template> </template>

View File

@@ -13,14 +13,15 @@ import {
} from '@/components/ui/dropdown-menu'; } from '@/components/ui/dropdown-menu';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'; import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { logout } from '~/lib/api/auth/logout'; import { logout } from '~/lib/api/auth/logout';
import type { AuthUser } from '~/types/auth';
const { isMobile } = useSidebar(); const { isMobile } = useSidebar();
const { user } = defineProps<{
user: AuthUser;
}>();
const user = { const AVATAR =
name: '409', 'https://cdn.discordapp.com/avatars/285424924049276939/0368b00056c416cae689ab1434c0aac0.webp';
email: 'user@example.com',
avatar: 'https://cdn.discordapp.com/avatars/285424924049276939/0368b00056c416cae689ab1434c0aac0.webp',
};
</script> </script>
<template> <template>
@@ -34,7 +35,7 @@ const user = {
tooltip="Settings" tooltip="Settings"
> >
<Avatar class="h-8 w-8 rounded-lg"> <Avatar class="h-8 w-8 rounded-lg">
<AvatarImage :src="user.avatar" /> <AvatarImage :src="AVATAR" />
<AvatarFallback class="rounded-lg" <AvatarFallback class="rounded-lg"
>A</AvatarFallback >A</AvatarFallback
> >
@@ -66,10 +67,7 @@ const user = {
class="flex items-center gap-2 px-1 py-1.5 text-left text-sm" class="flex items-center gap-2 px-1 py-1.5 text-left text-sm"
> >
<Avatar class="h-8 w-8 rounded-lg"> <Avatar class="h-8 w-8 rounded-lg">
<AvatarImage <AvatarImage :src="AVATAR" :alt="user.name" />
:src="user.avatar"
:alt="user.name"
/>
<AvatarFallback class="rounded-lg"> <AvatarFallback class="rounded-lg">
CN CN
</AvatarFallback> </AvatarFallback>
@@ -86,7 +84,7 @@ const user = {
</div> </div>
</div> </div>
</DropdownMenuLabel> </DropdownMenuLabel>
<DropdownMenuSeparator /> <!-- <DropdownMenuSeparator />
<DropdownMenuGroup> <DropdownMenuGroup>
<DropdownMenuItem> <DropdownMenuItem>
<Icon name="lucide:user" /> <Icon name="lucide:user" />
@@ -99,7 +97,7 @@ const user = {
<Icon name="lucide:settings" /> <Icon name="lucide:settings" />
Settings Settings
</DropdownMenuItem> </DropdownMenuItem>
</DropdownMenuGroup> </DropdownMenuGroup> -->
<DropdownMenuSeparator /> <DropdownMenuSeparator />
<DropdownMenuItem @click="logout"> <DropdownMenuItem @click="logout">
<Icon name="lucide:door-open" /> <Icon name="lucide:door-open" />

View File

@@ -0,0 +1,42 @@
import type { AuthSessionType, AuthUser } from '~/types/auth';
import type { ApiResponse } from '~/types/api';
export async function getAuthSessionData(params: {
sessionType: AuthSessionType;
sessionId: string;
}): Promise<
{ success: true; user: AuthUser; expiresAt: number } | { success: false }
> {
const { data, status } = await useFetch<
ApiResponse<{
user: AuthUser;
expiresAt: number;
}>
>(getApiUrl('auth/session'), {
method: 'GET',
key: new Date().getTime().toString(),
headers: {
authorization: `${params.sessionType} ${params.sessionId}`,
},
});
if (status.value !== 'success' || data.value == null) {
return {
success: false,
};
}
const { id, name, email, admin } = data.value.data.user;
const expiresAt = data.value.data.expiresAt;
return {
success: true,
user: {
id,
name,
email,
admin,
},
expiresAt,
};
}

View File

@@ -1,10 +1,12 @@
import { toast } from 'vue-sonner'; import { toast } from 'vue-sonner';
import type { ApiResponse } from '~/types/api'; import type { ApiResponse } from '~/types/api';
import { getAuthSessionData } from './getSession';
export async function loginUser( export async function loginUser(
email: string, email: string,
password: string password: string
): Promise<{ success: boolean }> { ): Promise<{ success: boolean }> {
console.log('logging in...', email, password);
const { data, error } = await useFetch<ApiResponse<{ token: string }>>( const { data, error } = await useFetch<ApiResponse<{ token: string }>>(
getApiUrl('auth/login'), getApiUrl('auth/login'),
{ {
@@ -30,7 +32,24 @@ export async function loginUser(
}; };
} }
useAuthSession().value = { type: 'WarrenAuth', id: data.value.data.token }; // TODO: Get this data directly from the login request
const sessionData = await getAuthSessionData({
sessionType: 'WarrenAuth',
sessionId: data.value.data.token,
});
if (!sessionData.success) {
return {
success: false,
};
}
useAuthSession().value = {
type: 'WarrenAuth',
id: data.value.data.token,
user: sessionData.user,
expiresAt: sessionData.expiresAt,
};
toast.success('Login', { toast.success('Login', {
description: `Successfully logged in`, description: `Successfully logged in`,

View File

@@ -2,4 +2,14 @@ export type AuthSessionType = 'WarrenAuth';
export interface AuthSession { export interface AuthSession {
type: AuthSessionType; type: AuthSessionType;
id: string; id: string;
user: AuthUser;
expiresAt: number;
}
export interface AuthUser {
id: string;
name: string;
email: string;
admin: boolean;
} }