|
| 1 | +use async_graphql::{Context, Object, Result, SimpleObject}; |
| 2 | +use ecow::EcoString; |
| 3 | + |
| 4 | +use super::error::Error; |
| 5 | +use crate::{db, gql::error::ErrorCode}; |
| 6 | + |
| 7 | +use super::auth::ContextAuthExt; |
| 8 | + |
| 9 | +#[derive(Default)] |
| 10 | +pub struct UserQuery; |
| 11 | + |
| 12 | +#[Object] |
| 13 | +impl UserQuery { |
| 14 | + async fn user<'ctx>(&self, ctx: &Context<'ctx>) -> Result<User> { |
| 15 | + tracing::debug!("Running GraphQL query 'user'"); |
| 16 | + |
| 17 | + let Some(sub) = ctx.sub() else { |
| 18 | + return Err(Error { |
| 19 | + code: ErrorCode::Unauthorized, |
| 20 | + title: EcoString::inline("Unauthorized"), |
| 21 | + details: "You must login to access this API.".into(), |
| 22 | + error: None, |
| 23 | + } |
| 24 | + .to_gql_error()); |
| 25 | + }; |
| 26 | + let pool = ctx.data::<db::Pool>()?; |
| 27 | + |
| 28 | + let user = db::get_or_initialize_user(pool, sub).await?; |
| 29 | + Ok(user.into()) |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +#[derive(Debug, Clone, SimpleObject)] |
| 34 | +pub struct User { |
| 35 | + pub user_id: String, |
| 36 | + pub group_id: Option<i64>, |
| 37 | + pub created_at: chrono::DateTime<chrono::Utc>, |
| 38 | + pub updated_at: chrono::DateTime<chrono::Utc>, |
| 39 | +} |
| 40 | + |
| 41 | +impl From<db::User> for User { |
| 42 | + fn from(user: db::User) -> Self { |
| 43 | + Self { |
| 44 | + user_id: user.user_id, |
| 45 | + group_id: user.group_id, |
| 46 | + created_at: user.created_at, |
| 47 | + updated_at: user.updated_at, |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments