DEVELOPMENT ENVIRONMENT

~liljamo/ulairi

ref: e78be1f39347874c13c8ff1c08025ec375b5e928 ulairi/ulairi-api/src/users/auth.rs -rw-r--r-- 1.2 KiB
e78be1f3Jonni Liljamo I lost the old commit history... 1 year, 11 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
use rocket::request::{self, FromRequest, Request};
use rocket::Outcome;

pub extern crate crypto;
pub extern crate jwt;
pub extern crate rustc_serialize;

use self::jwt::{Header, Registered, Token};
use crypto::sha2::Sha256;

pub struct ApiKey(pub String);

pub fn read_token(key: &str) -> Result<String, String> {
    let token =
        Token::<Header, Registered>::parse(key).map_err(|_| "Unable to parse key".to_string())?;

    // Check if the key is valid
    if token.verify(dotenv!("JWT_KEY").as_bytes(), Sha256::new()) {
        token.claims.sub.ok_or("Claims not valid".to_string())
    } else {
        Err("Token not valid".to_string())
    }
}

impl<'a, 'r> FromRequest<'a, 'r> for ApiKey {
    type Error = ();

    fn from_request(request: &'a Request<'r>) -> request::Outcome<ApiKey, ()> {
        // Get the key(s) from the authorization header
        let keys: Vec<_> = request.headers().get("Authentication").collect();
        if keys.len() != 1 {
            return Outcome::Forward(());
        }
        // Check if the key is valid
        match read_token(keys[0]) {
            Ok(claim) => Outcome::Success(ApiKey(claim)),
            Err(_) => Outcome::Forward(()),
        }
    }
}