Skip to content

Commit 3fa1eba

Browse files
committed
auth: Extract authenticate_via_cookie/token() fns
1 parent 0754b83 commit 3fa1eba

File tree

1 file changed

+34
-8
lines changed

1 file changed

+34
-8
lines changed

src/auth.rs

Lines changed: 34 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ use crate::util::errors::{
99
account_locked, forbidden, internal, AppError, AppResult, InsecurelyGeneratedTokenRevoked,
1010
};
1111
use chrono::Utc;
12+
use diesel::PgConnection;
1213
use http::header;
1314

1415
#[derive(Debug, Clone)]
@@ -152,11 +153,10 @@ impl Authentication {
152153
}
153154
}
154155

155-
fn authenticate_user<T: RequestPartsExt>(req: &T) -> AppResult<Authentication> {
156-
controllers::util::verify_origin(req)?;
157-
158-
let conn = req.app().db_write()?;
159-
156+
fn authenticate_via_cookie<T: RequestPartsExt>(
157+
req: &T,
158+
conn: &PgConnection,
159+
) -> AppResult<Option<CookieAuthentication>> {
160160
let user_id_from_session = req
161161
.session_get("user_id")
162162
.and_then(|s| s.parse::<i32>().ok());
@@ -169,10 +169,16 @@ fn authenticate_user<T: RequestPartsExt>(req: &T) -> AppResult<Authentication> {
169169

170170
req.add_custom_metadata("uid", id);
171171

172-
return Ok(Authentication::Cookie(CookieAuthentication { user }));
172+
return Ok(Some(CookieAuthentication { user }));
173173
}
174174

175-
// Otherwise, look for an `Authorization` header on the request
175+
return Ok(None);
176+
}
177+
178+
fn authenticate_via_token<T: RequestPartsExt>(
179+
req: &T,
180+
conn: &PgConnection,
181+
) -> AppResult<Option<TokenAuthentication>> {
176182
let maybe_authorization = req
177183
.headers()
178184
.get(header::AUTHORIZATION)
@@ -195,7 +201,27 @@ fn authenticate_user<T: RequestPartsExt>(req: &T) -> AppResult<Authentication> {
195201
req.add_custom_metadata("uid", token.user_id);
196202
req.add_custom_metadata("tokenid", token.id);
197203

198-
return Ok(Authentication::Token(TokenAuthentication { user, token }));
204+
return Ok(Some(TokenAuthentication { user, token }));
205+
}
206+
207+
return Ok(None);
208+
}
209+
210+
fn authenticate_user<T: RequestPartsExt>(req: &T) -> AppResult<Authentication> {
211+
controllers::util::verify_origin(req)?;
212+
213+
let conn = req.app().db_write()?;
214+
215+
match authenticate_via_cookie(req, &conn) {
216+
Ok(None) => {}
217+
Ok(Some(auth)) => return Ok(Authentication::Cookie(auth)),
218+
Err(err) => return Err(err),
219+
}
220+
221+
match authenticate_via_token(req, &conn) {
222+
Ok(None) => {}
223+
Ok(Some(auth)) => return Ok(Authentication::Token(auth)),
224+
Err(err) => return Err(err),
199225
}
200226

201227
// Unable to authenticate the user

0 commit comments

Comments
 (0)