oauth2
This commit is contained in:
@@ -1,12 +1,16 @@
|
||||
use axum::{
|
||||
extract::State,
|
||||
http::StatusCode,
|
||||
Json,
|
||||
};
|
||||
use axum_login::AuthSession;
|
||||
use sea_orm::{DatabaseConnection, EntityTrait, ColumnTrait, QueryFilter, ActiveModelTrait, Set};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::auth::{AuthBackend, Credentials};
|
||||
use crate::models::{user, User, family, Family};
|
||||
use crate::services::FamilyService;
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
pub struct LoginRequest {
|
||||
@@ -20,6 +24,15 @@ pub struct LoginResponse {
|
||||
pub is_admin: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct MeResponse {
|
||||
pub id: i32,
|
||||
pub username: Option<String>,
|
||||
pub email: Option<String>,
|
||||
pub is_admin: bool,
|
||||
pub family_id: Option<i32>,
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/login",
|
||||
@@ -72,3 +85,105 @@ pub async fn logout(
|
||||
|
||||
Ok(StatusCode::OK)
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/me",
|
||||
tag = "auth",
|
||||
responses(
|
||||
(status = 200, description = "Current user info", body = MeResponse),
|
||||
(status = 401, description = "Not authenticated")
|
||||
)
|
||||
)]
|
||||
pub async fn me(
|
||||
auth_session: AuthSession<AuthBackend>,
|
||||
) -> Result<Json<MeResponse>, StatusCode> {
|
||||
let user = auth_session.user.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
Ok(Json(MeResponse {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
is_admin: user.is_admin,
|
||||
family_id: user.family_id,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
pub struct FamilyLoginRequest {
|
||||
pub family_name: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct FamilyLoginResponse {
|
||||
pub success: bool,
|
||||
pub family_id: i32,
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/auth/family-login",
|
||||
tag = "auth",
|
||||
request_body = FamilyLoginRequest,
|
||||
responses(
|
||||
(status = 200, description = "Login successful", body = FamilyLoginResponse),
|
||||
(status = 401, description = "Invalid credentials"),
|
||||
(status = 404, description = "Family not found")
|
||||
)
|
||||
)]
|
||||
pub async fn family_login(
|
||||
mut auth_session: AuthSession<AuthBackend>,
|
||||
State(db): State<DatabaseConnection>,
|
||||
Json(payload): Json<FamilyLoginRequest>,
|
||||
) -> Result<Json<FamilyLoginResponse>, StatusCode> {
|
||||
let family = Family::find()
|
||||
.filter(family::Column::Name.eq(&payload.family_name))
|
||||
.one(&db)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
let valid = FamilyService::verify_password(&db, family.id, payload.password.clone())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
if !valid {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
let existing_member = User::find()
|
||||
.filter(user::Column::FamilyId.eq(family.id))
|
||||
.filter(user::Column::GoogleId.is_null())
|
||||
.filter(user::Column::Username.eq(&payload.family_name))
|
||||
.one(&db)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let member_user = if let Some(user) = existing_member {
|
||||
user
|
||||
} else {
|
||||
let new_member = user::ActiveModel {
|
||||
username: Set(Some(payload.family_name)),
|
||||
email: Set(None),
|
||||
google_id: Set(None),
|
||||
password_hash: Set(None),
|
||||
is_admin: Set(false),
|
||||
family_id: Set(Some(family.id)),
|
||||
..Default::default()
|
||||
};
|
||||
new_member.insert(&db)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
};
|
||||
|
||||
auth_session
|
||||
.login(&member_user)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
Ok(Json(FamilyLoginResponse {
|
||||
success: true,
|
||||
family_id: family.id,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -3,12 +3,15 @@ use axum::{
|
||||
http::StatusCode,
|
||||
Json,
|
||||
};
|
||||
use sea_orm::DatabaseConnection;
|
||||
use axum_login::AuthSession;
|
||||
use sea_orm::{DatabaseConnection, EntityTrait, ActiveModelTrait, Set};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
use tower_sessions::Session;
|
||||
|
||||
use crate::auth::AuthBackend;
|
||||
use crate::models::family::Model as FamilyModel;
|
||||
use crate::models::{user, User};
|
||||
use crate::services::FamilyService;
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
@@ -18,6 +21,14 @@ pub struct CreateFamilyRequest {
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
#[schema(example = json!({"name": "Smith Family", "password": "secret123"}))]
|
||||
pub struct CreateMyFamilyRequest {
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub password: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
#[schema(example = json!({"password": "secret123"}))]
|
||||
pub struct VerifyFamilyPasswordRequest {
|
||||
@@ -188,3 +199,57 @@ pub async fn verify_family_password(
|
||||
Err(StatusCode::UNAUTHORIZED)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct CreateMyFamilyResponse {
|
||||
pub family: FamilyModel,
|
||||
pub user_id: i32,
|
||||
pub family_id: i32,
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/my-family",
|
||||
tag = "families",
|
||||
request_body = CreateMyFamilyRequest,
|
||||
responses(
|
||||
(status = 200, description = "Family created and linked to user", body = CreateMyFamilyResponse),
|
||||
(status = 401, description = "Not authenticated"),
|
||||
(status = 409, description = "User already has a family"),
|
||||
(status = 500, description = "Internal server error")
|
||||
)
|
||||
)]
|
||||
pub async fn create_my_family(
|
||||
auth_session: AuthSession<AuthBackend>,
|
||||
State(db): State<DatabaseConnection>,
|
||||
Json(payload): Json<CreateMyFamilyRequest>,
|
||||
) -> Result<Json<CreateMyFamilyResponse>, StatusCode> {
|
||||
let current_user = auth_session.user.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
if current_user.family_id.is_some() {
|
||||
return Err(StatusCode::CONFLICT);
|
||||
}
|
||||
|
||||
let password = payload.password.unwrap_or_default();
|
||||
let family = FamilyService::create(&db, payload.name, password)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let mut active_user: user::ActiveModel = User::find_by_id(current_user.id)
|
||||
.one(&db)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?
|
||||
.into();
|
||||
|
||||
active_user.family_id = Set(Some(family.id));
|
||||
active_user.update(&db)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
Ok(Json(CreateMyFamilyResponse {
|
||||
family_id: family.id,
|
||||
user_id: current_user.id,
|
||||
family,
|
||||
}))
|
||||
}
|
||||
|
||||
264
backend/src/routes/invite_link.rs
Normal file
264
backend/src/routes/invite_link.rs
Normal file
@@ -0,0 +1,264 @@
|
||||
use axum::{
|
||||
extract::{Path, State},
|
||||
http::StatusCode,
|
||||
Json,
|
||||
};
|
||||
use axum_login::AuthSession;
|
||||
use sea_orm::DatabaseConnection;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::auth::AuthBackend;
|
||||
use crate::models::invite_link::Model as InviteLinkModel;
|
||||
use crate::services::InviteLinkService;
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
#[schema(example = json!({"expires_in_hours": 24, "max_uses": 5}))]
|
||||
pub struct CreateInviteLinkRequest {
|
||||
pub expires_in_hours: Option<i64>,
|
||||
pub max_uses: Option<i32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct InviteLinkResponse {
|
||||
pub id: i32,
|
||||
pub family_id: i32,
|
||||
pub token: String,
|
||||
pub invite_url: String,
|
||||
pub expires_at: Option<String>,
|
||||
pub max_uses: Option<i32>,
|
||||
pub uses_count: i32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct ValidateInviteResponse {
|
||||
pub valid: bool,
|
||||
pub family_id: Option<i32>,
|
||||
pub family_name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct JoinFamilyResponse {
|
||||
pub success: bool,
|
||||
pub family_id: i32,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
fn model_to_response(model: InviteLinkModel, base_url: &str) -> InviteLinkResponse {
|
||||
InviteLinkResponse {
|
||||
id: model.id,
|
||||
family_id: model.family_id,
|
||||
token: model.token.clone(),
|
||||
invite_url: format!("{}/invite/{}", base_url, model.token),
|
||||
expires_at: model.expires_at.map(|dt| dt.to_string()),
|
||||
max_uses: model.max_uses,
|
||||
uses_count: model.uses_count,
|
||||
}
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/my-family/invite-links",
|
||||
tag = "invite-links",
|
||||
request_body = CreateInviteLinkRequest,
|
||||
responses(
|
||||
(status = 200, description = "Invite link created", body = InviteLinkResponse),
|
||||
(status = 401, description = "Not authenticated"),
|
||||
(status = 403, description = "User has no family"),
|
||||
(status = 500, description = "Internal server error")
|
||||
)
|
||||
)]
|
||||
pub async fn create_invite_link(
|
||||
auth_session: AuthSession<AuthBackend>,
|
||||
State(db): State<DatabaseConnection>,
|
||||
Json(payload): Json<CreateInviteLinkRequest>,
|
||||
) -> Result<Json<InviteLinkResponse>, StatusCode> {
|
||||
let user = auth_session.user.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let family_id = user.family_id.ok_or(StatusCode::FORBIDDEN)?;
|
||||
|
||||
let expires_at = payload.expires_in_hours.map(|hours| {
|
||||
chrono::Utc::now().naive_utc() + chrono::Duration::hours(hours)
|
||||
});
|
||||
|
||||
let invite = InviteLinkService::create(&db, family_id, user.id, expires_at, payload.max_uses)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let base_url = std::env::var("FRONTEND_URL").unwrap_or_else(|_| "http://localhost:5173".to_string());
|
||||
Ok(Json(model_to_response(invite, &base_url)))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/my-family/invite-links",
|
||||
tag = "invite-links",
|
||||
responses(
|
||||
(status = 200, description = "List of invite links", body = Vec<InviteLinkResponse>),
|
||||
(status = 401, description = "Not authenticated"),
|
||||
(status = 403, description = "User has no family"),
|
||||
(status = 500, description = "Internal server error")
|
||||
)
|
||||
)]
|
||||
pub async fn get_my_invite_links(
|
||||
auth_session: AuthSession<AuthBackend>,
|
||||
State(db): State<DatabaseConnection>,
|
||||
) -> Result<Json<Vec<InviteLinkResponse>>, StatusCode> {
|
||||
let user = auth_session.user.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let family_id = user.family_id.ok_or(StatusCode::FORBIDDEN)?;
|
||||
|
||||
let invites = InviteLinkService::find_by_family(&db, family_id)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let base_url = std::env::var("FRONTEND_URL").unwrap_or_else(|_| "http://localhost:5173".to_string());
|
||||
let responses: Vec<InviteLinkResponse> = invites
|
||||
.into_iter()
|
||||
.map(|i| model_to_response(i, &base_url))
|
||||
.collect();
|
||||
|
||||
Ok(Json(responses))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
delete,
|
||||
path = "/my-family/invite-links/{token}",
|
||||
tag = "invite-links",
|
||||
params(
|
||||
("token" = String, Path, description = "Invite token")
|
||||
),
|
||||
responses(
|
||||
(status = 204, description = "Invite link deleted"),
|
||||
(status = 401, description = "Not authenticated"),
|
||||
(status = 403, description = "User has no family or not authorized"),
|
||||
(status = 404, description = "Invite link not found"),
|
||||
(status = 500, description = "Internal server error")
|
||||
)
|
||||
)]
|
||||
pub async fn delete_invite_link(
|
||||
auth_session: AuthSession<AuthBackend>,
|
||||
State(db): State<DatabaseConnection>,
|
||||
Path(token): Path<String>,
|
||||
) -> Result<StatusCode, StatusCode> {
|
||||
let user = auth_session.user.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
let family_id = user.family_id.ok_or(StatusCode::FORBIDDEN)?;
|
||||
|
||||
let invite = InviteLinkService::find_by_token(&db, &token)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
if invite.family_id != family_id {
|
||||
return Err(StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
InviteLinkService::delete_by_token(&db, &token)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/invite/{token}",
|
||||
tag = "invite-links",
|
||||
params(
|
||||
("token" = String, Path, description = "Invite token")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Invite link is valid", body = ValidateInviteResponse),
|
||||
(status = 404, description = "Invite link not found or invalid"),
|
||||
(status = 500, description = "Internal server error")
|
||||
)
|
||||
)]
|
||||
pub async fn validate_invite_link(
|
||||
State(db): State<DatabaseConnection>,
|
||||
Path(token): Path<String>,
|
||||
) -> Result<Json<ValidateInviteResponse>, StatusCode> {
|
||||
use crate::models::Family;
|
||||
use sea_orm::EntityTrait;
|
||||
|
||||
let invite = InviteLinkService::find_by_token(&db, &token)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
|
||||
.ok_or(StatusCode::NOT_FOUND)?;
|
||||
|
||||
if let Some(expires_at) = invite.expires_at {
|
||||
let now = chrono::Utc::now().naive_utc();
|
||||
if now > expires_at {
|
||||
return Ok(Json(ValidateInviteResponse {
|
||||
valid: false,
|
||||
family_id: None,
|
||||
family_name: None,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(max_uses) = invite.max_uses {
|
||||
if invite.uses_count >= max_uses {
|
||||
return Ok(Json(ValidateInviteResponse {
|
||||
valid: false,
|
||||
family_id: None,
|
||||
family_name: None,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
let family = Family::find_by_id(invite.family_id)
|
||||
.one(&db)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
Ok(Json(ValidateInviteResponse {
|
||||
valid: true,
|
||||
family_id: Some(invite.family_id),
|
||||
family_name: family.map(|f| f.name),
|
||||
}))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = "/invite/{token}/join",
|
||||
tag = "invite-links",
|
||||
params(
|
||||
("token" = String, Path, description = "Invite token")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Successfully joined family", body = JoinFamilyResponse),
|
||||
(status = 401, description = "Not authenticated"),
|
||||
(status = 400, description = "User already in a family or invite invalid"),
|
||||
(status = 404, description = "Invite link not found"),
|
||||
(status = 500, description = "Internal server error")
|
||||
)
|
||||
)]
|
||||
pub async fn join_family_via_invite(
|
||||
auth_session: AuthSession<AuthBackend>,
|
||||
State(db): State<DatabaseConnection>,
|
||||
Path(token): Path<String>,
|
||||
) -> Result<Json<JoinFamilyResponse>, StatusCode> {
|
||||
let user = auth_session.user.ok_or(StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
if user.family_id.is_some() {
|
||||
return Ok(Json(JoinFamilyResponse {
|
||||
success: false,
|
||||
family_id: 0,
|
||||
message: "You already belong to a family".to_string(),
|
||||
}));
|
||||
}
|
||||
|
||||
let invite = InviteLinkService::validate_and_use(&db, &token, user.id)
|
||||
.await
|
||||
.map_err(|e| match e {
|
||||
sea_orm::DbErr::RecordNotFound(_) => StatusCode::NOT_FOUND,
|
||||
sea_orm::DbErr::Custom(msg) if msg.contains("expired") => StatusCode::BAD_REQUEST,
|
||||
sea_orm::DbErr::Custom(msg) if msg.contains("max uses") => StatusCode::BAD_REQUEST,
|
||||
sea_orm::DbErr::Custom(msg) if msg.contains("already belongs") => StatusCode::BAD_REQUEST,
|
||||
_ => StatusCode::INTERNAL_SERVER_ERROR,
|
||||
})?;
|
||||
|
||||
Ok(Json(JoinFamilyResponse {
|
||||
success: true,
|
||||
family_id: invite.family_id,
|
||||
message: "Successfully joined family".to_string(),
|
||||
}))
|
||||
}
|
||||
@@ -3,3 +3,5 @@ pub mod category;
|
||||
pub mod expense;
|
||||
pub mod auth;
|
||||
pub mod shopping_item;
|
||||
pub mod oauth;
|
||||
pub mod invite_link;
|
||||
|
||||
125
backend/src/routes/oauth.rs
Normal file
125
backend/src/routes/oauth.rs
Normal file
@@ -0,0 +1,125 @@
|
||||
use axum::{
|
||||
extract::{Query, State},
|
||||
http::StatusCode,
|
||||
response::Redirect,
|
||||
Json,
|
||||
};
|
||||
use axum_login::AuthSession;
|
||||
use sea_orm::DatabaseConnection;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tower_sessions::Session;
|
||||
use utoipa::ToSchema;
|
||||
|
||||
use crate::auth::AuthBackend;
|
||||
use crate::services::OAuthService;
|
||||
|
||||
const CSRF_TOKEN_KEY: &str = "oauth_csrf_token";
|
||||
const FRONTEND_URL_KEY: &str = "oauth_frontend_url";
|
||||
|
||||
#[derive(Debug, Deserialize, ToSchema)]
|
||||
pub struct GoogleAuthQuery {
|
||||
pub redirect_url: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct GoogleCallbackQuery {
|
||||
pub code: String,
|
||||
pub state: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, ToSchema)]
|
||||
pub struct OAuthUrlResponse {
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/auth/google",
|
||||
tag = "auth",
|
||||
params(
|
||||
("redirect_url" = Option<String>, Query, description = "Frontend URL to redirect after auth")
|
||||
),
|
||||
responses(
|
||||
(status = 200, description = "Returns Google OAuth URL", body = OAuthUrlResponse)
|
||||
)
|
||||
)]
|
||||
pub async fn google_auth(
|
||||
session: Session,
|
||||
Query(query): Query<GoogleAuthQuery>,
|
||||
) -> Result<Json<OAuthUrlResponse>, StatusCode> {
|
||||
let oauth_service = OAuthService::new();
|
||||
let (auth_url, csrf_token) = oauth_service.get_auth_url();
|
||||
|
||||
session
|
||||
.insert(CSRF_TOKEN_KEY, csrf_token.secret().clone())
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
if let Some(redirect_url) = query.redirect_url {
|
||||
session
|
||||
.insert(FRONTEND_URL_KEY, redirect_url)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
}
|
||||
|
||||
Ok(Json(OAuthUrlResponse { url: auth_url }))
|
||||
}
|
||||
|
||||
#[utoipa::path(
|
||||
get,
|
||||
path = "/auth/google/callback",
|
||||
tag = "auth",
|
||||
responses(
|
||||
(status = 302, description = "Redirects to frontend after successful auth"),
|
||||
(status = 401, description = "Authentication failed")
|
||||
)
|
||||
)]
|
||||
pub async fn google_callback(
|
||||
mut auth_session: AuthSession<AuthBackend>,
|
||||
session: Session,
|
||||
State(db): State<DatabaseConnection>,
|
||||
Query(query): Query<GoogleCallbackQuery>,
|
||||
) -> Result<Redirect, StatusCode> {
|
||||
let stored_csrf: Option<String> = session
|
||||
.get(CSRF_TOKEN_KEY)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let frontend_url: Option<String> = session
|
||||
.get(FRONTEND_URL_KEY)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
session.remove::<String>(CSRF_TOKEN_KEY).await.ok();
|
||||
session.remove::<String>(FRONTEND_URL_KEY).await.ok();
|
||||
|
||||
if stored_csrf.as_deref() != Some(&query.state) {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
let oauth_service = OAuthService::new();
|
||||
|
||||
let access_token = oauth_service
|
||||
.exchange_code(query.code)
|
||||
.await
|
||||
.map_err(|_| StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let google_user = oauth_service
|
||||
.get_user_info(&access_token)
|
||||
.await
|
||||
.map_err(|_| StatusCode::UNAUTHORIZED)?;
|
||||
|
||||
let user = oauth_service
|
||||
.find_or_create_user(&db, google_user)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
auth_session
|
||||
.login(&user)
|
||||
.await
|
||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
||||
|
||||
let redirect_url = frontend_url.unwrap_or_else(|| "http://localhost:3000".to_string());
|
||||
|
||||
Ok(Redirect::temporary(&redirect_url))
|
||||
}
|
||||
Reference in New Issue
Block a user