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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
|
use argon2::{
Argon2, PasswordHash, PasswordHasher, PasswordVerifier,
password_hash::{SaltString, rand_core::OsRng},
};
use axum::{
extract::{FromRequestParts, Request, State},
http::{StatusCode, request::Parts},
middleware::Next,
response::{IntoResponse, Redirect, Response},
};
use rusqlite::params;
use serde::Deserialize;
use uuid::Uuid;
use crate::models::Account;
use crate::routes::AppState;
#[derive(Debug, Deserialize)]
pub struct LoginForm {
pub username: String,
pub password: String,
}
const SESSION_COOKIE: &str = "mcui_session";
pub fn hash_password(password: &str) -> Result<String, argon2::password_hash::Error> {
let salt = SaltString::generate(&mut OsRng);
let hash = Argon2::default().hash_password(password.as_bytes(), &salt)?;
Ok(hash.to_string())
}
pub fn verify_password(password: &str, hash: &str) -> Result<bool, argon2::password_hash::Error> {
let parsed = PasswordHash::new(hash)?;
Ok(Argon2::default()
.verify_password(password.as_bytes(), &parsed)
.is_ok())
}
pub async fn authenticate(
State(state): State<AppState>,
axum::Form(form): axum::Form<LoginForm>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
let conn = state.db.conn();
let account = conn
.query_row(
"SELECT id, username, is_superuser, password_change_required FROM accounts WHERE username = ?1",
params![form.username],
|row| {
Ok(Account {
id: row.get(0)?,
username: row.get(1)?,
is_superuser: row.get::<_, i32>(2)? != 0,
password_change_required: row.get::<_, i32>(3)? != 0,
})
},
)
.map_err(|_| (StatusCode::UNAUTHORIZED, "Invalid username or password".into()))?;
let hash: String = conn
.query_row(
"SELECT password FROM accounts WHERE id = ?1",
params![account.id],
|row| row.get(0),
)
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Database error".into()))?;
if !verify_password(&form.password, &hash).unwrap_or(false) {
return Err((
StatusCode::UNAUTHORIZED,
"Invalid username or password".into(),
));
}
let session_id = Uuid::new_v4().to_string();
conn.execute(
"INSERT INTO sessions (id, account_id) VALUES (?1, ?2)",
params![session_id, account.id],
)
.map_err(|_| (StatusCode::INTERNAL_SERVER_ERROR, "Session error".into()))?;
drop(conn);
let cookie_value =
format!("{SESSION_COOKIE}={session_id}; Path=/; HttpOnly; Max-Age=86400; SameSite=Lax");
let redirect = if account.password_change_required {
Redirect::to("/change-password")
} else {
Redirect::to("/")
};
Ok(([(axum::http::header::SET_COOKIE, cookie_value)], redirect))
}
pub async fn require_auth(
State(state): State<AppState>,
mut request: Request,
next: Next,
) -> Result<Response, Response> {
let cookies = request
.headers()
.get(axum::http::header::COOKIE)
.and_then(|v| v.to_str().ok())
.unwrap_or("");
let session_id = cookies.split(';').map(|s| s.trim()).find_map(|cookie| {
if let Some((name, value)) = cookie.split_once('=') {
if name.trim() == SESSION_COOKIE {
Some(value.trim().to_string())
} else {
None
}
} else {
None
}
});
match session_id {
Some(id) => {
let account = state
.db
.conn()
.query_row(
"SELECT a.id, a.username, a.is_superuser, a.password_change_required
FROM sessions s JOIN accounts a ON s.account_id = a.id
WHERE s.id = ?1",
params![id],
|row| {
Ok(Account {
id: row.get(0)?,
username: row.get(1)?,
is_superuser: row.get::<_, i32>(2)? != 0,
password_change_required: row.get::<_, i32>(3)? != 0,
})
},
)
.ok();
if let Some(account) = account {
request.extensions_mut().insert(account);
Ok(next.run(request).await)
} else {
Err(Redirect::to("/login").into_response())
}
}
None => Err(Redirect::to("/login").into_response()),
}
}
#[derive(Clone)]
pub struct CurrentUser(pub Account);
impl<S> FromRequestParts<S> for CurrentUser
where
S: Send + Sync,
{
type Rejection = (StatusCode, &'static str);
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
parts
.extensions
.get::<Account>()
.cloned()
.map(CurrentUser)
.ok_or((StatusCode::UNAUTHORIZED, "Not authenticated"))
}
}
pub async fn logout(
State(state): State<AppState>,
headers: axum::http::HeaderMap,
) -> impl IntoResponse {
if let Some(cookie_header) = headers.get(axum::http::header::COOKIE) {
if let Ok(cookie_str) = cookie_header.to_str() {
for part in cookie_str.split(';') {
let part = part.trim();
if let Some((name, value)) = part.split_once('=') {
if name.trim() == SESSION_COOKIE {
let _ = state
.db
.conn()
.execute("DELETE FROM sessions WHERE id = ?1", params![value.trim()]);
}
}
}
}
}
let clear_cookie = format!("{SESSION_COOKIE}=; Path=/; HttpOnly; Max-Age=0");
(
[(axum::http::header::SET_COOKIE, clear_cookie)],
Redirect::to("/login"),
)
}
|