2017-02-14 15:51:39 +00:00
|
|
|
extern crate medallion;
|
2017-02-13 23:40:07 +00:00
|
|
|
|
|
|
|
use std::default::Default;
|
2017-03-07 19:03:24 +00:00
|
|
|
use medallion::{Header, DefaultPayload, DefaultToken};
|
2017-02-13 23:40:07 +00:00
|
|
|
|
|
|
|
fn new_token(user_id: &str, password: &str) -> Option<String> {
|
|
|
|
// Dummy auth
|
|
|
|
if password != "password" {
|
2017-03-07 19:03:24 +00:00
|
|
|
return None;
|
2017-02-13 23:40:07 +00:00
|
|
|
}
|
|
|
|
|
2017-03-07 19:03:24 +00:00
|
|
|
// can satisfy Header's generic parameter with an empty type
|
|
|
|
let header: Header<()> = Default::default();
|
|
|
|
let payload = DefaultPayload {
|
2017-02-14 15:51:39 +00:00
|
|
|
iss: Some("example.com".into()),
|
2017-02-13 23:40:07 +00:00
|
|
|
sub: Some(user_id.into()),
|
|
|
|
..Default::default()
|
|
|
|
};
|
2017-03-07 19:03:24 +00:00
|
|
|
let token = DefaultToken::new(header, payload);
|
2017-02-13 23:40:07 +00:00
|
|
|
|
2017-03-07 19:03:24 +00:00
|
|
|
token.sign(b"secret_key").ok()
|
2017-02-13 23:40:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn login(token: &str) -> Option<String> {
|
2017-03-07 19:03:24 +00:00
|
|
|
let token: DefaultToken<()> = DefaultToken::parse(token).unwrap();
|
2017-02-13 23:40:07 +00:00
|
|
|
|
2017-02-17 16:53:12 +00:00
|
|
|
if token.verify(b"secret_key").unwrap() {
|
2017-03-07 19:03:24 +00:00
|
|
|
token.payload.sub
|
2017-02-13 23:40:07 +00:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn main() {
|
2017-02-14 15:51:39 +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 15:51:39 +00:00
|
|
|
assert_eq!(logged_in_user, "Random User");
|
2017-02-13 23:40:07 +00:00
|
|
|
}
|