Skip to content

Commit

Permalink
fix: feat: remove duplicate operation of storing jwt in the database
Browse files Browse the repository at this point in the history
  • Loading branch information
Eraxyso authored Sep 19, 2024
1 parent 9543934 commit 17dc701
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/handler/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,15 +33,24 @@ pub async fn get_me(

pub async fn put_me_email(
State(state): State<Repository>,
TypedHeader(cookie): TypedHeader<Cookie>,
Json(body): Json<EmailUpdate>,
) -> anyhow::Result<StatusCode, StatusCode> {
let session_id = cookie.get("session_id").ok_or(StatusCode::UNAUTHORIZED)?;

let user_id = state
.get_user_id_by_session_id(session_id)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?
.ok_or(StatusCode::UNAUTHORIZED)?;

let email = body
.email
.parse::<Address>()
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

let jwt = state
.save_email_varifications(&body.email)
.encode_email_update_jwt(user_id, &body.email)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
let message = format!(
Expand Down
1 change: 1 addition & 0 deletions src/repository.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use sqlx::{

mod signup_jwt;
mod users;
mod users_jwt;
mod users_session;

#[derive(Clone)]
Expand Down
36 changes: 36 additions & 0 deletions src/repository/users_jwt.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
use async_session::chrono::{Duration, Utc};
use serde::{Deserialize, Serialize};

use super::Repository;

#[derive(Serialize, Deserialize)]
struct SignupClaims {
user_id: i64,
email: String,
exp: i64,
}

impl Repository {
pub async fn encode_email_update_jwt(
&self,
user_id: i64,
email: &str,
) -> anyhow::Result<String> {
let exp = (Utc::now() + Duration::minutes(60)).timestamp();
let claims = SignupClaims {
user_id: user_id,
email: email.to_owned(),
exp,
};

let encode_key: String = std::env::var("JWT_SECRET")?;

let jwt = jsonwebtoken::encode(
&jsonwebtoken::Header::default(),
&claims,
&jsonwebtoken::EncodingKey::from_secret(encode_key.as_ref()),
)?;

Ok(jwt)
}
}

0 comments on commit 17dc701

Please sign in to comment.