Skip to content

Commit 8d92aba

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 8d92aba

File tree

1 file changed

+8
-4
lines changed

1 file changed

+8
-4
lines changed

src/user/middleware.rs

Lines changed: 8 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,15 @@ 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(|s| s.parse::<i32>().ok())
2526
};
2627

28+
let conn = req.db_conn().map_err(std_error)?;
29+
2730
if let Some(id) = id {
2831
// 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) {
32+
let maybe_user = users::table.find(id).first::<User>(&*conn);
33+
if let Ok(user) = maybe_user {
3034
// Attach the `User` model from the database to the request
3135
req.mut_extensions().insert(user);
3236
req.mut_extensions().insert(
@@ -37,7 +41,7 @@ impl conduit_middleware::Middleware for Middleware {
3741
// Otherwise, look for an `Authorization` header on the request
3842
// and try to find a user in the database with a matching API token
3943
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()
44+
User::find_by_api_token(&conn, headers[0]).ok()
4145
} else {
4246
None
4347
};

0 commit comments

Comments
 (0)