use super::AppError;
use crate::{
AppState,
models::{post, user},
};
use axum::{
extract::{Path, Query, State},
http::HeaderMap,
response::Response,
};
use ryuk::{
auth::{self, Auth, OptionalAuth},
inertia::{self, Inertia},
mail::{Mail, MailError},
proxy::ClientIp,
throttle::Throttle,
tokens::{RESET_PASSWORD, VERIFY_EMAIL},
validation::Form,
};
use sea_orm::{ActiveModelTrait, ActiveValue::{Set, Unchanged}, ColumnTrait, EntityTrait, QueryFilter};
use serde::Deserialize;
use serde_json::json;
use std::{collections::BTreeMap, net::IpAddr, time::Duration};
use ryuk::session::Session;
use utoipa::ToSchema;
use validator::Validate;
#[derive(Deserialize, Validate, ToSchema)]
pub struct RegisterForm {
#[validate(length(min = 1, message = "Name is required"))]
name: String,
#[validate(email(message = "Enter a valid email"))]
email: String,
#[validate(length(min = 8, message = "Password must be at least 8 characters"))]
password: String,
}
#[derive(Deserialize, Validate, ToSchema)]
pub struct LoginForm {
#[validate(email(message = "Enter a valid email"))]
email: String,
#[validate(length(min = 1, message = "Password is required"))]
password: String,
}
#[derive(Deserialize, Validate, ToSchema)]
pub struct ForgotForm {
#[validate(email(message = "Enter a valid email"))]
email: String,
}
#[derive(Deserialize, Validate, ToSchema)]
pub struct ResendForm {
#[validate(email(message = "Enter a valid email"))]
email: String,
}
#[derive(Deserialize, Validate, ToSchema)]
pub struct ResetForm {
token: String,
#[validate(length(min = 8, message = "Password must be at least 8 characters"))]
#[validate(must_match(other = "password_confirmation", message = "Passwords do not match"))]
password: String,
password_confirmation: String,
}
fn field_error(field: &str, msg: &str) -> BTreeMap<String, String> {
BTreeMap::from([(field.to_string(), msg.to_string())])
}
fn unverified_error() -> BTreeMap<String, String> {
BTreeMap::from([
("email".to_string(), "Verify your email first.".to_string()),
("unverified".to_string(), "true".to_string()),
])
}
const VERIFY_TTL: Duration = Duration::from_secs(24 * 3600);
const RESET_TTL: Duration = Duration::from_secs(3600);
fn app_url() -> String {
std::env::var("APP_URL").unwrap_or_else(|_| "http://127.0.0.1:3000".into()).trim_end_matches('/').to_string()
}
pub(crate) async fn ip_gate(s: &AppState, flow: &str, ip: Option<IpAddr>) -> Result<(), ryuk::throttle::Locked> {
match ip {
Some(ip) => s.ip_throttle.attempt(&Throttle::key(&format!("{flow}-ip"), Some(ip))).await,
None => Ok(()),
}
}
async fn mail_gate(s: &AppState, flow: &str, email: &str) -> bool {
s.mail_throttle.attempt(&Throttle::key(&format!("{flow}:{email}"), None)).await.is_ok()
}
async fn mail_link(s: &AppState, u: &user::Model, purpose: &str, ttl: Duration, path: &str, build: fn(&str, &str, &str, Duration) -> Result<Mail, MailError>) -> Result<(), AppError> {
let token = s.tokens.issue(u.id, purpose, ttl).await?;
let link = format!("{}/{path}/{token}", app_url());
let mail = build(&u.name, &u.email, &link, ttl)?;
if std::env::var("APP_ENV").as_deref() != Ok("production") {
tracing::info!("{}: {link}", mail.subject);
}
if let Err(e) = s.mailer.send(mail).await {
tracing::error!("mail to user {}: {e}", u.id);
}
Ok(())
}
async fn send_verification(s: &AppState, u: &user::Model) -> Result<(), AppError> {
mail_link(s, u, VERIFY_EMAIL, VERIFY_TTL, "verify-email", crate::mails::auth::verify_email).await
}
#[utoipa::path(get, path = "/", responses((status = 200, description = "Welcome page")))]
pub async fn welcome(inertia: Inertia, OptionalAuth(uid): OptionalAuth) -> Response {
inertia.render("Welcome", json!({ "authenticated": uid.is_some() }))
}
#[utoipa::path(get, path = "/login", responses((status = 200, description = "Login page")))]
pub async fn show_login(inertia: Inertia, Query(q): Query<LoginQuery>, session: Session) -> Response {
if let Some(n) = q.next.as_deref().and_then(safe_next) {
let _ = session.insert("login_next", n).await;
}
inertia.render("Auth/Login", json!({ "social": super::social::enabled(&super::social::social()) }))
}
#[derive(Deserialize)]
pub struct LoginQuery {
next: Option<String>,
}
fn safe_next(next: &str) -> Option<String> {
let ok = next.starts_with('/')
&& !next.starts_with("//")
&& !next.contains('\\')
&& !next.chars().any(char::is_control)
&& next.len() <= 2048;
ok.then(|| next.to_string())
}
#[utoipa::path(post, path = "/login", request_body = LoginForm,
responses((status = 303, description = "Redirect to dashboard or back to login")))]
pub async fn login(
State(s): State<AppState>,
ClientIp(ip): ClientIp,
session: Session,
Form(f): Form<LoginForm>,
) -> Result<Response, AppError> {
let key = Throttle::key(&f.email, ip);
let gate = match ip_gate(&s, "login", ip).await {
Ok(()) => s.throttle.attempt(&key).await,
locked => locked,
};
if let Err(locked) = gate {
let msg = format!("Too many attempts. Try again in {} seconds.", locked.retry_after.as_secs());
inertia::flash_errors(&session, field_error("email", &msg)).await;
return Ok(inertia::redirect("/login"));
}
let found = user::Entity::find()
.filter(user::Column::Email.eq(f.email.as_str()))
.one(&s.db)
.await?;
let ok = match &found {
Some(u) => auth::verify_password_async(f.password.clone(), u.password.clone()).await,
None => {
auth::verify_password_async(f.password.clone(), crate::account::dummy_hash().await).await;
false
}
};
match found {
Some(u) if ok && u.email_verified_at.is_none() => {
s.throttle.clear(&key).await?;
inertia::flash_errors(&session, unverified_error()).await;
Ok(inertia::redirect("/login"))
}
Some(u) if ok => {
s.throttle.clear(&key).await?;
auth::login(&session, u.id).await?;
inertia::flash(&session, "success", "Welcome back!").await;
let next = session.remove::<String>("login_next").await.ok().flatten();
Ok(inertia::redirect(&next.as_deref().and_then(safe_next).unwrap_or_else(|| "/dashboard".into())))
}
_ => {
let msg = "These credentials do not match our records.";
inertia::flash_errors(&session, field_error("email", msg)).await;
Ok(inertia::redirect("/login"))
}
}
}
#[utoipa::path(get, path = "/register", responses((status = 200, description = "Register page")))]
pub async fn show_register(inertia: Inertia) -> Response {
inertia.render("Auth/Register", json!({ "social": super::social::enabled(&super::social::social()) }))
}
#[utoipa::path(post, path = "/register", request_body = RegisterForm,
responses((status = 303, description = "Always the same redirect to /login, whether or not the email exists")))]
pub async fn register(
State(s): State<AppState>,
ClientIp(ip): ClientIp,
session: Session,
Form(f): Form<RegisterForm>,
) -> Result<Response, AppError> {
let key = Throttle::key(&format!("register:{}", f.email), ip);
if ip_gate(&s, "register", ip).await.is_err() || s.throttle.attempt(&key).await.is_err() {
inertia::flash(&session, "success", "Check your email to finish creating your account.").await;
return Ok(inertia::redirect("/login"));
}
let hash = auth::hash_password_async(f.password.clone()).await?;
let taken = user::Entity::find().filter(user::Column::Email.eq(f.email.as_str())).one(&s.db).await?;
let existing = match taken {
Some(u) => Some(u),
None => {
let email = f.email.clone();
match (user::ActiveModel { name: Set(f.name), email: Set(f.email), password: Set(hash), has_usable_password: Set(true), ..Default::default() })
.insert(&s.db)
.await
{
Ok(u) => {
if mail_gate(&s, "register", &u.email).await {
send_verification(&s, &u).await?;
}
s.throttle.clear(&key).await?;
None
}
Err(e) => {
tracing::warn!("register insert failed: {e}");
user::Entity::find().filter(user::Column::Email.eq(email.as_str())).one(&s.db).await?
}
}
}
};
if let Some(u) = existing
&& mail_gate(&s, "register-notice", &u.email).await
{
let mail = crate::mails::auth::account_exists(&u.name, &u.email, &format!("{}/forgot-password", app_url()))?;
if let Err(e) = s.mailer.send(mail).await {
tracing::error!("mail to user {}: {e}", u.id);
}
}
inertia::flash(&session, "success", "Check your email to finish creating your account.").await;
Ok(inertia::redirect("/login"))
}
#[utoipa::path(post, path = "/logout", responses((status = 303, description = "Redirect home")))]
pub async fn logout(session: Session) -> Response {
auth::logout(&session).await;
inertia::redirect("/")
}
#[utoipa::path(get, path = "/dashboard",
responses((status = 200, description = "Dashboard page"), (status = 303, description = "Not logged in")))]
pub async fn dashboard(
State(s): State<AppState>,
Auth(uid): Auth,
inertia: Inertia,
) -> Result<Response, AppError> {
let u = user::Entity::find_by_id(uid).one(&s.db).await?;
let posts = post::Entity::find()
.filter(post::Column::UserId.eq(uid))
.all(&s.db)
.await?;
let verified = u.as_ref().is_some_and(|u| u.email_verified_at.is_some());
Ok(inertia.render("Dashboard", json!({ "user": u, "posts": posts, "verified": verified })))
}
#[utoipa::path(get, path = "/verify-email/{token}", params(("token" = String, Path, description = "Verification token")),
responses((status = 200, description = "Confirm page; the token is consumed only by POST /verify-email")))]
pub async fn show_verify_email(inertia: Inertia, Path(token): Path<String>) -> Response {
inertia.render("Auth/VerifyEmail", json!({ "token": token }))
}
#[derive(Deserialize, Validate, ToSchema)]
pub struct VerifyForm {
#[validate(length(min = 1, message = "Missing token"))]
token: String,
}
#[utoipa::path(post, path = "/verify-email", request_body = VerifyForm,
responses((status = 303, description = "Redirect to login")))]
pub async fn verify_email(State(s): State<AppState>, session: Session, Form(f): Form<VerifyForm>) -> Result<Response, AppError> {
match s.tokens.consume(&f.token, VERIFY_EMAIL).await? {
Some(uid) => {
user::ActiveModel { id: Unchanged(uid), email_verified_at: Set(Some(chrono::Utc::now())), ..Default::default() }
.update(&s.db)
.await?;
inertia::flash(&session, "success", "Email verified. Log in to continue.").await;
}
None => inertia::flash(&session, "error", "This verification link is invalid or has expired.").await,
}
Ok(inertia::redirect("/login"))
}
#[utoipa::path(post, path = "/email/resend", request_body = ResendForm,
responses((status = 303, description = "Always the same response; mails only for an existing unverified account")))]
pub async fn resend_verification(
State(s): State<AppState>,
ClientIp(ip): ClientIp,
session: Session,
headers: HeaderMap,
Form(f): Form<ResendForm>,
) -> Result<Response, AppError> {
let key = Throttle::key(&format!("resend:{}", f.email), ip);
if s.throttle.attempt(&key).await.is_ok() && mail_gate(&s, "resend", &f.email).await {
let found = user::Entity::find().filter(user::Column::Email.eq(f.email.as_str())).one(&s.db).await?;
if let Some(u) = found.filter(|u| u.email_verified_at.is_none()) {
send_verification(&s, &u).await?;
}
}
inertia::flash(&session, "success", "If that account needs verification, a new link is on its way.").await;
Ok(inertia::redirect_back(&headers))
}
#[utoipa::path(get, path = "/forgot-password", responses((status = 200, description = "Forgot password page")))]
pub async fn show_forgot(inertia: Inertia) -> Response {
inertia.render("Auth/ForgotPassword", json!({}))
}
#[utoipa::path(post, path = "/forgot-password", request_body = ForgotForm,
responses((status = 303, description = "Always the same response, whether or not the email exists")))]
pub async fn forgot(
State(s): State<AppState>,
ClientIp(ip): ClientIp,
session: Session,
Form(f): Form<ForgotForm>,
) -> Result<Response, AppError> {
let key = Throttle::key(&format!("forgot:{}", f.email), ip);
if ip_gate(&s, "forgot", ip).await.is_ok() && s.throttle.attempt(&key).await.is_ok() && mail_gate(&s, "forgot", &f.email).await {
let found = user::Entity::find().filter(user::Column::Email.eq(f.email.as_str())).one(&s.db).await?;
if let Some(u) = found {
mail_link(&s, &u, RESET_PASSWORD, RESET_TTL, "reset-password", crate::mails::auth::reset_password).await?;
}
}
inertia::flash(&session, "success", "If that email is registered, a reset link is on its way.").await;
Ok(inertia::redirect("/forgot-password"))
}
#[utoipa::path(get, path = "/reset-password/{token}", params(("token" = String, Path, description = "Reset token")),
responses((status = 200, description = "Reset password page")))]
pub async fn show_reset_form(inertia: Inertia, Path(token): Path<String>) -> Response {
inertia.render("Auth/ResetPassword", json!({ "token": token }))
}
#[utoipa::path(post, path = "/reset-password", request_body = ResetForm,
responses((status = 303, description = "Redirect to login, or back with an error")))]
pub async fn reset(
State(s): State<AppState>,
session: Session,
headers: HeaderMap,
Form(f): Form<ResetForm>,
) -> Result<Response, AppError> {
let Some(uid) = s.tokens.consume(&f.token, RESET_PASSWORD).await? else {
inertia::flash_errors(&session, field_error("password", "This reset link is invalid or has expired.")).await;
return Ok(inertia::redirect_back(&headers));
};
user::ActiveModel {
id: Unchanged(uid),
password: Set(auth::hash_password_async(f.password.clone()).await?),
has_usable_password: Set(true), ..Default::default()
}
.update(&s.db)
.await?;
crate::account::sign_out_everywhere(&s, uid).await?;
s.api_keys.revoke_all(uid).await?;
inertia::flash(&session, "success", "Password updated. Log in with your new password.").await;
Ok(inertia::redirect("/login"))
}
#[cfg(test)]
mod tests {
use super::safe_next;
#[test]
fn next_is_a_local_path_or_nothing() {
assert_eq!(safe_next("/oauth/authorize?client_id=x").as_deref(), Some("/oauth/authorize?client_id=x"));
for bad in ["https://evil.example", "//evil.example", "/\\evil.example", "evil", "", "/a\r\nb"] {
assert_eq!(safe_next(bad), None, "{bad:?}");
}
assert_eq!(safe_next(&format!("/{}", "a".repeat(3000))), None);
}
}