Skip to content

Use diesel from inside the users middleware #904

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 13, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions src/user/middleware.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ use std::error::Error;
use conduit_middleware;
use conduit::Request;
use conduit_cookie::RequestSession;
use diesel::prelude::*;

use Model;
use db::RequestTransaction;
use schema::users;
use super::User;
use util::errors::{CargoResult, Unauthorized, ChainError, std_error};

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

let conn = req.db_conn().map_err(std_error)?;

if let Some(id) = id {
// If it did, look for a user in the database with the given `user_id`
if let Ok(user) = User::find(req.tx().map_err(std_error)?, id) {
let maybe_user = users::table.find(id).first::<User>(&*conn);
if let Ok(user) = maybe_user {
// Attach the `User` model from the database to the request
req.mut_extensions().insert(user);
req.mut_extensions().insert(
Expand All @@ -38,7 +44,7 @@ impl conduit_middleware::Middleware for Middleware {
// Otherwise, look for an `Authorization` header on the request
// and try to find a user in the database with a matching API token
let user = if let Some(headers) = req.headers().find("Authorization") {
User::find_by_api_token(&*req.db_conn().map_err(std_error)?, headers[0]).ok()
User::find_by_api_token(&conn, headers[0]).ok()
} else {
None
};
Expand Down