Skip to content

Commit 482d461

Browse files
Merge #904
904: Use diesel from inside the users middleware r=carols10cents I'm a bit worried about the fact that there were not tests which needed to be updated. It seems like we never actually test the authentication directly, we always just stub the user into the request.
2 parents ffa8751 + 0fc8b95 commit 482d461

File tree

1 file changed

+10
-4
lines changed

1 file changed

+10
-4
lines changed

src/user/middleware.rs

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@ use std::error::Error;
33
use conduit_middleware;
44
use conduit::Request;
55
use conduit_cookie::RequestSession;
6+
use diesel::prelude::*;
67

7-
use Model;
88
use db::RequestTransaction;
9+
use schema::users;
910
use super::User;
1011
use util::errors::{CargoResult, Unauthorized, ChainError, std_error};
1112

@@ -22,12 +23,17 @@ impl conduit_middleware::Middleware for Middleware {
2223
fn before(&self, req: &mut Request) -> Result<(), Box<Error + Send>> {
2324
// Check if the request has a session cookie with a `user_id` property inside
2425
let id = {
25-
req.session().get("user_id").and_then(|s| s.parse().ok())
26+
req.session().get("user_id").and_then(
27+
|s| s.parse::<i32>().ok(),
28+
)
2629
};
2730

31+
let conn = req.db_conn().map_err(std_error)?;
32+
2833
if let Some(id) = id {
2934
// If it did, look for a user in the database with the given `user_id`
30-
if let Ok(user) = User::find(req.tx().map_err(std_error)?, id) {
35+
let maybe_user = users::table.find(id).first::<User>(&*conn);
36+
if let Ok(user) = maybe_user {
3137
// Attach the `User` model from the database to the request
3238
req.mut_extensions().insert(user);
3339
req.mut_extensions().insert(
@@ -38,7 +44,7 @@ impl conduit_middleware::Middleware for Middleware {
3844
// Otherwise, look for an `Authorization` header on the request
3945
// and try to find a user in the database with a matching API token
4046
let user = if let Some(headers) = req.headers().find("Authorization") {
41-
User::find_by_api_token(&*req.db_conn().map_err(std_error)?, headers[0]).ok()
47+
User::find_by_api_token(&conn, headers[0]).ok()
4248
} else {
4349
None
4450
};

0 commit comments

Comments
 (0)