Skip to content

Commit b6864fa

Browse files
committed
controllers::util: Move User::find() calls into the condition branches
This allows us to give more precise error messages and enables further simplification
1 parent 1114534 commit b6864fa

File tree

2 files changed

+10
-7
lines changed

2 files changed

+10
-7
lines changed

src/controllers/util.rs

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -62,8 +62,11 @@ fn authenticate_user(req: &dyn RequestExt) -> AppResult<AuthenticatedUser> {
6262
let session = req.session();
6363
let user_id_from_session = session.get("user_id").and_then(|s| s.parse::<i32>().ok());
6464

65-
let (user_id, token_id) = if let Some(id) = user_id_from_session {
66-
(id, None)
65+
let (user, token_id) = if let Some(id) = user_id_from_session {
66+
let user = User::find(&conn, id)
67+
.chain_error(|| internal("user_id from cookie not found in database"))?;
68+
69+
(user, None)
6770
} else {
6871
// Otherwise, look for an `Authorization` header on the request
6972
let maybe_authorization = req
@@ -80,16 +83,16 @@ fn authenticate_user(req: &dyn RequestExt) -> AppResult<AuthenticatedUser> {
8083
}
8184
})?;
8285

83-
(token.user_id, Some(token.id))
86+
let user = User::find(&conn, token.user_id)
87+
.chain_error(|| internal("user_id from token not found in database"))?;
88+
89+
(user, Some(token.id))
8490
} else {
8591
// Unable to authenticate the user
8692
return Err(internal("no cookie session or auth header found")).chain_error(forbidden);
8793
}
8894
};
8995

90-
let user = User::find(&conn, user_id)
91-
.chain_error(|| internal("user_id from cookie or token not found in database"))?;
92-
9396
Ok(AuthenticatedUser { user, token_id })
9497
}
9598

src/tests/authentication.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ static URL: &str = "/api/v1/me/updates";
88
static MUST_LOGIN: &[u8] =
99
b"{\"errors\":[{\"detail\":\"must be logged in to perform that action\"}]}";
1010
static INTERNAL_ERROR_NO_USER: &str =
11-
"user_id from cookie or token not found in database caused by NotFound";
11+
"user_id from cookie not found in database caused by NotFound";
1212

1313
fn call(app: &TestApp, mut request: MockRequest) -> HandlerResult {
1414
app.as_middleware().call(&mut request)

0 commit comments

Comments
 (0)