-
Notifications
You must be signed in to change notification settings - Fork 0
/
firebase_jwt.rs
78 lines (61 loc) · 1.94 KB
/
firebase_jwt.rs
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/// @TODO: tests
use jwt;
use jwt::id_token::{IDToken, IDTokenDecoder};
use base64;
use json;
use auth::firebase_keyring::Keyring;
use auth::{Result, ErrorKind};
use std::ops::Deref;
pub struct Token {
idtoken: IDToken
}
static FIREBASE_AUDIENCE: &str = "dhcircles-fa776";
static FIREBASE_ISSUER: &str = "https://securetoken.google.com/dhcircles-fa776";
impl Token {
pub fn decode(token: &str, keyring: &Keyring) -> Result<Token> {
// Decode and deserialize token keader to retrieve "kid"
let header = token.split(".").nth(0).ok_or(jwt::Error::JWTInvalid)?;
let header = base64::decode(header)?;
let header: TokenHeader = json::from_slice(&header[..])?;
// Get a Public Key with received "kid" from Google Keyring
let public_key = keyring.get(&header.kid).ok_or(ErrorKind::UnknownKeyID)?;
// Construct a decoder that will decode token,
// verify signature and ISSUES + AUDIENCE
let decoder = IDTokenDecoder::from_pem(
public_key,
FIREBASE_ISSUER,
FIREBASE_AUDIENCE
)?;
// Construct Self object wrapping a decoded idtoken
let token = Token {
idtoken: decoder.decode(token)?
};
// And then we can verify token's other data correctness
token.verify_data()?;
Ok(token)
}
pub fn user_id(&self) -> &str {
self.idtoken.subject_identifier()
}
fn verify_data(&self) -> Result<()> {
let token = &self.idtoken;
// Check that user_id is not empty
if token.subject_identifier().is_empty()
|| token.subject_identifier().chars().all(|c| c.is_whitespace())
{
bail!(ErrorKind::EmptyUserID)
}
Ok(())
}
}
impl Deref for Token {
type Target = IDToken;
fn deref(&self) -> &Self::Target {
&self.idtoken
}
}
#[derive(Debug, Deserialize)]
struct TokenHeader {
alg: String,
kid: String
}