Skip to content

Commit

Permalink
Merge pull request #49 from traP-jp/feat/#19-post-reset-password-request
Browse files Browse the repository at this point in the history
POST /reset-password/request を実装
  • Loading branch information
kenken714 authored Oct 29, 2024
2 parents 2a2c730 + 32c06f0 commit 11b435d
Show file tree
Hide file tree
Showing 3 changed files with 59 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ pub fn make_router(app_state: Repository) -> Router {
.route("/signup/request", post(authentication::sign_up_request))
.route("/signup", post(authentication::sign_up))
.route("/login", post(authentication::login))
.route("/logout", post(authentication::logout));
.route("/logout", post(authentication::logout))
.route(
"/reset-password/request",
post(authentication::reset_password_request),
);

let users_router = Router::new()
.route("/me", get(users::get_me).put(users::put_me))
Expand Down
37 changes: 37 additions & 0 deletions src/handler/authentication.rs
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,40 @@ pub async fn logout(

Ok((StatusCode::NO_CONTENT, headers))
}

#[derive(Deserialize)]
pub struct ResetPasswordRequest {
email: String,
}

pub async fn reset_password_request(
State(state): State<Repository>,
Json(body): Json<ResetPasswordRequest>,
) -> Result<StatusCode, StatusCode> {
let user_address = body
.email
.parse::<Address>()
.map_err(|_| StatusCode::BAD_REQUEST)?;

// 登録されていないメールアドレスのとき、正常時と同じステータスコードを返すが実際にメールを送信しない
if let Ok(false) = state.is_exist_email(&body.email).await {
return Ok(StatusCode::CREATED);
}

let jwt = state
.encode_email_reset_password_jwt(&body.email)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

let message = format!(
"これはテストメールです。
以下のリンクをクリックしてください。
https://link/{jwt}"
);

crate::utils::mail::send_email(user_address, "traOJudgeパスワードリセット", &message)
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;

Ok(StatusCode::CREATED)
}
17 changes: 17 additions & 0 deletions src/repository/jwt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,23 @@ impl Repository {
claims.to_jwt()
}

pub async fn encode_email_reset_password_jwt(&self, email: &str) -> anyhow::Result<String> {
let exp = (Utc::now() + Duration::minutes(60)).timestamp();
let iat = Utc::now().timestamp();
let nbf = Utc::now().timestamp();

let claims = EmailToken {
exp,
iat,
nbf,
user_id: None,
email: email.to_string(),
action: Action::reset_password,
};

claims.to_jwt()
}

pub async fn verify_email_jwt(&self, jwt: &str) -> anyhow::Result<()> {
EmailToken::verify(jwt)
}
Expand Down

0 comments on commit 11b435d

Please sign in to comment.