Skip to content

Commit

Permalink
refactor(auth): Make permission handling more straight forward.
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonTeixidor committed Jul 16, 2015
1 parent c723786 commit 66d74da
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 15 deletions.
24 changes: 14 additions & 10 deletions examples/example.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,22 +20,26 @@ struct User {
struct SessionType(Option<String>);

#[derive(Eq, PartialEq)]
enum UserClass {User, Admin, None}
enum UserClass {User, Admin}

impl AuthorizeSession for SessionType {
type Permissions = UserClass;

fn permissions(&self) -> UserClass {
let SessionType(ref user) = *self;
if let Some(u) = user.as_ref() {
if u == "foo" {
return UserClass::User;
}
else if u == "admin" {
return UserClass::Admin;
fn has_permission(&self, permission: &UserClass) -> bool {
match *permission {
UserClass::User => {
match *self {
SessionType(Some(ref u)) => &*u == "foo" || &*u == "admin",
SessionType(None) => false
}
},
UserClass::Admin => {
match *self {
SessionType(Some(ref u)) => &*u == "admin",
SessionType(None) => false
}
}
}
UserClass::None
}
}

Expand Down
9 changes: 4 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use nickel::status::StatusCode::Forbidden;
pub trait AuthorizeSession {
type Permissions;

fn permissions(&self) -> Self::Permissions;
fn has_permission(&self, permission: &Self::Permissions) -> bool;
}

pub struct Authorize<P, M> {
Expand Down Expand Up @@ -61,11 +61,10 @@ where for<'a, 'k> Response<'a, 'k, D>: Cookies,
P: PartialEq +'static + Send + Sync {
fn invoke<'a, 'b>(&'a self, mut res: Response<'a, 'b, D>) -> MiddlewareResult<'a, 'b, D> {
let allowed = {
let current_permission = &res.session().permissions();
match self.permissions {
Permit::Only(ref p) => p == current_permission,
Permit::Any(ref ps) => ps.iter().any(|p| p == current_permission),
Permit::All(ref ps) => ps.iter().all(|p| p == current_permission),
Permit::Only(ref p) => res.session().has_permission(p),
Permit::Any(ref ps) => ps.iter().any(|p| res.session().has_permission(p)),
Permit::All(ref ps) => ps.iter().all(|p| res.session().has_permission(p)),
}
};

Expand Down

0 comments on commit 66d74da

Please sign in to comment.