From a92fb07d23fb2268a6f4e650c5cbd00ad993e760 Mon Sep 17 00:00:00 2001 From: Santo Cariotti Date: Wed, 21 Aug 2024 13:25:55 +0200 Subject: Add login Fields sent are ``` { "query": "mutation Login($input: LoginCredentials!) { login(input: $input) { accessToken tokenType } }", "variables": { "input": { "email": "....", "password": "..." } } } ``` --- src/graphql/mutation.rs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 src/graphql/mutation.rs (limited to 'src/graphql/mutation.rs') diff --git a/src/graphql/mutation.rs b/src/graphql/mutation.rs new file mode 100644 index 0000000..9321653 --- /dev/null +++ b/src/graphql/mutation.rs @@ -0,0 +1,35 @@ +use crate::graphql::types::jwt; +use crate::state::AppState; +use async_graphql::{Context, Error, FieldResult, Object}; + +pub struct Mutation; + +#[Object] +impl Mutation { + async fn login<'ctx>( + &self, + ctx: &Context<'ctx>, + input: jwt::LoginCredentials, + ) -> FieldResult { + let state = ctx.data::().expect("Can't connect to db"); + let client = &*state.client; + + let password = sha256::digest(input.password); + let rows = client + .query( + "SELECT id FROM users WHERE email = $1 AND password = $2", + &[&input.email, &password], + ) + .await + .unwrap(); + + let id: Vec = rows.iter().map(|row| row.get(0)).collect(); + if id.len() == 1 { + let claims = jwt::Claims::new(id[0]); + let token = claims.get_token().unwrap(); + Ok(jwt::AuthBody::new(token)) + } else { + Err(Error::new("Invalid email or password")) + } + } +} -- cgit v1.2.3-18-g5258