Skip to content

Commit 7f62ebf

Browse files
committed
Use diesel from inside the users middleware
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.
1 parent fcca5cc commit 7f62ebf

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

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

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

0 commit comments

Comments
 (0)