-
-
Notifications
You must be signed in to change notification settings - Fork 62
/
auth.rs
92 lines (78 loc) 路 2.42 KB
/
auth.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
use askama::Template;
use axum::{
extract::Query,
http::StatusCode,
response::{IntoResponse, Redirect},
routing::{get, post},
Form, Router,
};
use axum_messages::{Message, Messages};
use serde::Deserialize;
use crate::users::{AuthSession, Credentials};
#[derive(Template)]
#[template(path = "login.html")]
pub struct LoginTemplate {
messages: Vec<Message>,
next: Option<String>,
}
// This allows us to extract the "next" field from the query string. We use this
// to redirect after log in.
#[derive(Debug, Deserialize)]
pub struct NextUrl {
next: Option<String>,
}
pub fn router() -> Router<()> {
Router::new()
.route("/login", post(self::post::login))
.route("/login", get(self::get::login))
.route("/logout", get(self::get::logout))
}
mod post {
use super::*;
pub async fn login(
mut auth_session: AuthSession,
messages: Messages,
Form(creds): Form<Credentials>,
) -> impl IntoResponse {
let user = match auth_session.authenticate(creds.clone()).await {
Ok(Some(user)) => user,
Ok(None) => {
messages.error("Invalid credentials");
let mut login_url = "/login".to_string();
if let Some(next) = creds.next {
login_url = format!("{}?next={}", login_url, next);
};
return Redirect::to(&login_url).into_response();
}
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
};
if auth_session.login(&user).await.is_err() {
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
}
messages.success(format!("Successfully logged in as {}", user.username));
if let Some(ref next) = creds.next {
Redirect::to(next)
} else {
Redirect::to("/")
}
.into_response()
}
}
mod get {
use super::*;
pub async fn login(
messages: Messages,
Query(NextUrl { next }): Query<NextUrl>,
) -> LoginTemplate {
LoginTemplate {
messages: messages.into_iter().collect(),
next,
}
}
pub async fn logout(mut auth_session: AuthSession) -> impl IntoResponse {
match auth_session.logout().await {
Ok(_) => Redirect::to("/login").into_response(),
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
}
}
}