2017-02-14 15:51:39 +00:00
|
|
|
extern crate medallion;
|
2017-02-13 23:40:07 +00:00
|
|
|
|
|
|
|
use std::default::Default;
|
|
|
|
use std::fs::File;
|
|
|
|
use std::io::{Error, Read};
|
2017-02-14 15:51:39 +00:00
|
|
|
use medallion::{
|
2017-02-13 23:40:07 +00:00
|
|
|
Algorithm,
|
|
|
|
DefaultHeader,
|
|
|
|
Registered,
|
|
|
|
Token,
|
|
|
|
};
|
|
|
|
|
2017-02-17 17:54:50 +00:00
|
|
|
fn load_pem(keypath: &str) -> Result<String, Error> {
|
2017-02-17 17:39:28 +00:00
|
|
|
let mut key_file = File::open(keypath)?;
|
2017-02-13 23:40:07 +00:00
|
|
|
let mut key = String::new();
|
2017-02-17 17:39:28 +00:00
|
|
|
key_file.read_to_string(&mut key)?;
|
2017-02-13 23:40:07 +00:00
|
|
|
Ok(key)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn new_token(user_id: &str, password: &str) -> Option<String> {
|
|
|
|
// Dummy auth
|
|
|
|
if password != "password" {
|
|
|
|
return None
|
|
|
|
}
|
|
|
|
|
|
|
|
let header: DefaultHeader = DefaultHeader {
|
|
|
|
alg: Algorithm::RS256,
|
|
|
|
..Default::default()
|
|
|
|
};
|
|
|
|
let claims = Registered {
|
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()
|
|
|
|
};
|
|
|
|
let token = Token::new(header, claims);
|
|
|
|
|
2017-02-17 17:54:50 +00:00
|
|
|
token.signed(load_pem("./privateKey.pem").unwrap().as_bytes()).ok()
|
2017-02-13 23:40:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
fn login(token: &str) -> Option<String> {
|
|
|
|
let token = Token::<DefaultHeader, Registered>::parse(token).unwrap();
|
|
|
|
|
2017-02-17 17:54:50 +00:00
|
|
|
if token.verify(load_pem("./publicKey.pub").unwrap().as_bytes()).unwrap() {
|
2017-02-13 23:40:07 +00:00
|
|
|
token.claims.sub
|
|
|
|
} 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
|
|
|
}
|