2017-02-14 15:51:39 +00:00
|
|
|
// need this for custom derivation
|
|
|
|
#[macro_use]
|
|
|
|
extern crate serde_derive;
|
|
|
|
extern crate medallion;
|
2017-02-13 23:40:07 +00:00
|
|
|
|
|
|
|
use std::default::Default;
|
2017-02-14 15:51:39 +00:00
|
|
|
use medallion::{
|
2017-02-13 23:40:07 +00:00
|
|
|
DefaultHeader,
|
|
|
|
Token,
|
|
|
|
};
|
|
|
|
|
2017-02-14 15:51:39 +00:00
|
|
|
#[derive(Default, Serialize, Deserialize)]
|
2017-02-13 23:40:07 +00:00
|
|
|
struct Custom {
|
|
|
|
sub: String,
|
|
|
|
rhino: bool,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn new_token(user_id: &str, password: &str) -> Option<String> {
|
|
|
|
// Dummy auth
|
|
|
|
if password != "password" {
|
|
|
|
return None
|
|
|
|
}
|
|
|
|
|
|
|
|
let header: DefaultHeader = Default::default();
|
|
|
|
let claims = Custom {
|
|
|
|
sub: user_id.into(),
|
|
|
|
rhino: true,
|
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
let token = Token::new(header, claims);
|
|
|
|
|
|
|
|
token.signed(b"secret_key").ok()
|
|
|
|
}
|
|
|
|
|
|
|
|
fn login(token: &str) -> Option<String> {
|
|
|
|
let token = Token::<DefaultHeader, Custom>::parse(token).unwrap();
|
|
|
|
|
2017-02-17 16:53:12 +00:00
|
|
|
if token.verify(b"secret_key").unwrap() {
|
2017-02-13 23:40:07 +00:00
|
|
|
Some(token.claims.sub)
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2017-02-14 18:45:24 +00:00
|
|
|
let token = new_token("Random User", "password").unwrap();
|
2017-02-13 23:40:07 +00:00
|
|
|
|
|
|
|
let logged_in_user = login(&*token).unwrap();
|
|
|
|
|
2017-02-14 18:45:24 +00:00
|
|
|
assert_eq!(logged_in_user, "Random User");
|
2017-02-13 23:40:07 +00:00
|
|
|
}
|