From 3cf401467e5724f2db06b911878fd82e54778965 Mon Sep 17 00:00:00 2001 From: alemi Date: Mon, 15 Apr 2024 22:29:55 +0200 Subject: [PATCH] feat: login tells you who you are --- src/routes/activitypub/auth.rs | 31 +++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/src/routes/activitypub/auth.rs b/src/routes/activitypub/auth.rs index c513068..9a07abd 100644 --- a/src/routes/activitypub/auth.rs +++ b/src/routes/activitypub/auth.rs @@ -2,7 +2,7 @@ use axum::{http::StatusCode, extract::State, Json}; use rand::Rng; use sea_orm::{ColumnTrait, Condition, EntityTrait, QueryFilter}; -use crate::{model, server::Context}; +use crate::{errors::UpubError, model, server::Context}; #[derive(Debug, Clone, serde::Deserialize)] @@ -11,7 +11,14 @@ pub struct LoginForm { password: String, } -pub async fn login(State(ctx): State, Json(login): Json) -> Result, StatusCode> { +#[derive(Debug, Clone, serde::Serialize)] +pub struct AuthSuccess { + token: String, + user: String, + expires: chrono::DateTime, +} + +pub async fn login(State(ctx): State, Json(login): Json) -> crate::Result> { // TODO salt the pwd match model::credential::Entity::find() .filter(Condition::all() @@ -19,30 +26,30 @@ pub async fn login(State(ctx): State, Json(login): Json) -> .add(model::credential::Column::Password.eq(sha256::digest(login.password))) ) .one(ctx.db()) - .await + .await? { - Ok(Some(x)) => { + Some(x) => { // TODO should probably use crypto-safe rng let token : String = rand::thread_rng() .sample_iter(&rand::distributions::Alphanumeric) .take(128) .map(char::from) .collect(); + let expires = chrono::Utc::now() + std::time::Duration::from_secs(3600 * 6); model::session::Entity::insert( model::session::ActiveModel { id: sea_orm::ActiveValue::Set(token.clone()), - actor: sea_orm::ActiveValue::Set(x.id), - expires: sea_orm::ActiveValue::Set(chrono::Utc::now() + std::time::Duration::from_secs(3600 * 6)), + actor: sea_orm::ActiveValue::Set(x.id.clone()), + expires: sea_orm::ActiveValue::Set(expires), } ) .exec(ctx.db()) .await.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; - Ok(Json(serde_json::Value::String(token))) + Ok(Json(AuthSuccess { + token, expires, + user: x.id + })) }, - Ok(None) => Err(StatusCode::UNAUTHORIZED), - Err(e) => { - tracing::error!("error querying db for user credentials: {e}"); - Err(StatusCode::INTERNAL_SERVER_ERROR) - } + None => Err(UpubError::unauthorized()), } }