aboutsummaryrefslogtreecommitdiff
path: root/src/auth.rs
blob: 2f7faf25948f77d9c90fa668d1a315dfb9e9cb1c (plain)
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
///
/// JWT Handling
///

use util::read_file;
use chrono::Duration;

use jwt;
use serde::ser::Serialize;

use CONFIG;

const JWT_ALGORITHM: jwt::Algorithm = jwt::Algorithm::RS256;

lazy_static! {
    pub static ref DEFAULT_VALIDITY: Duration = Duration::hours(2);
    pub static ref JWT_ISSUER: String = CONFIG.domain.clone();

    static ref JWT_HEADER: jwt::Header = jwt::Header::new(JWT_ALGORITHM);

    static ref PRIVATE_RSA_KEY: Vec<u8> = match read_file(&CONFIG.private_rsa_key) {
        Ok(key) => key,
        Err(e) => panic!("Error loading private RSA Key from {}\n Error: {}", CONFIG.private_rsa_key, e)
    };

    static ref PUBLIC_RSA_KEY: Vec<u8> = match read_file(&CONFIG.public_rsa_key) {
        Ok(key) => key,
        Err(e) => panic!("Error loading public RSA Key from {}\n Error: {}", CONFIG.public_rsa_key, e)
    };
}

pub fn encode_jwt<T: Serialize>(claims: &T) -> String {
    match jwt::encode(&JWT_HEADER, claims, &PRIVATE_RSA_KEY) {
        Ok(token) => token,
        Err(e) => panic!("Error encoding jwt {}", e)
    }
}

pub fn decode_jwt(token: &str) -> Result<JWTClaims, String> {
    let validation = jwt::Validation {
        leeway: 30, // 30 seconds
        validate_exp: true,
        validate_iat: true,
        validate_nbf: true,
        aud: None,
        iss: Some(JWT_ISSUER.clone()),
        sub: None,
        algorithms: vec![JWT_ALGORITHM],
    };

    match jwt::decode(token, &PUBLIC_RSA_KEY, &validation) {
        Ok(decoded) => Ok(decoded.claims),
        Err(msg) => {
            println!("Error validating jwt - {:#?}", msg);
            Err(msg.to_string())
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub struct JWTClaims {
    // Not before
    pub nbf: i64,
    // Expiration time
    pub exp: i64,
    // Issuer
    pub iss: String,
    // Subject
    pub sub: String,

    pub premium: bool,
    pub name: String,
    pub email: String,
    pub email_verified: bool,

    pub orgowner: Vec<String>,
    pub orgadmin: Vec<String>,
    pub orguser: Vec<String>,

    // user security_stamp
    pub sstamp: String,
    // device uuid
    pub device: String,
    // [ "api", "offline_access" ]
    pub scope: Vec<String>,
    // [ "Application" ]
    pub amr: Vec<String>,
}

///
/// Bearer token authentication
///

use rocket::Outcome;
use rocket::request::{self, Request, FromRequest};

use db::DbConn;
use db::models::{User, UserOrganization, UserOrgType, UserOrgStatus, Device};

pub struct Headers {
    pub host: String,
    pub device: Device,
    pub user: User,
}

impl<'a, 'r> FromRequest<'a, 'r> for Headers {
    type Error = &'static str;

    fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
        let headers = request.headers();

        // Get host
        let host = if CONFIG.domain_set {
            CONFIG.domain.clone()
        } else if let Some(referer) = headers.get_one("Referer") {
            referer.to_string()
        } else {   
            // Try to guess from the headers
            use std::env;

            let protocol = if let Some(proto) = headers.get_one("X-Forwarded-Proto") {
                proto
            } else if env::var("ROCKET_TLS").is_ok() {
                "https"
            } else {
                "http"
            };

            let host = if let Some(host) = headers.get_one("X-Forwarded-Host") {
                host
            } else if let Some(host) = headers.get_one("Host") {
                host
            } else {
                ""
            };

            format!("{}://{}", protocol, host)
        };

        // Get access_token
        let access_token: &str = match request.headers().get_one("Authorization") {
            Some(a) => {
                match a.rsplit("Bearer ").next() {
                    Some(split) => split,
                    None => err_handler!("No access token provided")
                }
            }
            None => err_handler!("No access token provided")
        };

        // Check JWT token is valid and get device and user from it
        let claims: JWTClaims = match decode_jwt(access_token) {
            Ok(claims) => claims,
            Err(_) => err_handler!("Invalid claim")
        };

        let device_uuid = claims.device;
        let user_uuid = claims.sub;

        let conn = match request.guard::<DbConn>() {
            Outcome::Success(conn) => conn,
            _ => err_handler!("Error getting DB")
        };

        let device = match Device::find_by_uuid(&device_uuid, &conn) {
            Some(device) => device,
            None => err_handler!("Invalid device id")
        };

        let user = match User::find_by_uuid(&user_uuid, &conn) {
            Some(user) => user,
            None => err_handler!("Device has no user associated")
        };

        if user.security_stamp != claims.sstamp {
            err_handler!("Invalid security stamp")
        }

        Outcome::Success(Headers { host, device, user })
    }
}

pub struct OrgHeaders {
    pub host: String,
    pub device: Device,
    pub user: User,
    pub org_user_type: i32,
}

impl<'a, 'r> FromRequest<'a, 'r> for OrgHeaders {
    type Error = &'static str;

    fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
        match request.guard::<Headers>() {
            Outcome::Forward(f) => Outcome::Forward(f),
            Outcome::Failure(f) => Outcome::Failure(f),
            Outcome::Success(headers) => {
                // org_id is expected to be the first dynamic param
                match request.get_param::<String>(0) {
                    Err(_) => err_handler!("Error getting the organization id"),
                    Ok(org_id) => {
                        let conn = match request.guard::<DbConn>() {
                            Outcome::Success(conn) => conn,
                            _ => err_handler!("Error getting DB")
                        };

                        let org_user = match UserOrganization::find_by_user_and_org(&headers.user.uuid, &org_id, &conn) {
                            Some(user) => {
                                if user.status == UserOrgStatus::Confirmed as i32 {
                                    user
                                } else {
                                    err_handler!("The current user isn't confirmed member of the organization")
                                }
                            }
                            None => err_handler!("The current user isn't member of the organization")
                        };

                        Outcome::Success(Self{
                            host: headers.host,
                            device: headers.device,
                            user: headers.user,
                            org_user_type: org_user.type_,
                        })
                    }
                }
            }
        }
    }
}

pub struct AdminHeaders {
    pub host: String,
    pub device: Device,
    pub user: User,
    pub org_user_type: i32,
}

impl<'a, 'r> FromRequest<'a, 'r> for AdminHeaders {
    type Error = &'static str;

    fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
        match request.guard::<OrgHeaders>() {
            Outcome::Forward(f) => Outcome::Forward(f),
            Outcome::Failure(f) => Outcome::Failure(f),
            Outcome::Success(headers) => {
                if headers.org_user_type > UserOrgType::Admin as i32 {
                    err_handler!("You need to be Admin or Owner to call this endpoint")
                } else {
                    Outcome::Success(Self{
                        host: headers.host,
                        device: headers.device,
                        user: headers.user,
                        org_user_type: headers.org_user_type,
                    })
                }
            }
        }
    }
}

pub struct OwnerHeaders {
    pub host: String,
    pub device: Device,
    pub user: User,
}

impl<'a, 'r> FromRequest<'a, 'r> for OwnerHeaders {
    type Error = &'static str;

    fn from_request(request: &'a Request<'r>) -> request::Outcome<Self, Self::Error> {
        match request.guard::<OrgHeaders>() {
            Outcome::Forward(f) => Outcome::Forward(f),
            Outcome::Failure(f) => Outcome::Failure(f),
            Outcome::Success(headers) => {
                if headers.org_user_type > UserOrgType::Owner as i32 {
                    err_handler!("You need to be Owner to call this endpoint")
                } else {
                    Outcome::Success(Self{
                        host: headers.host,
                        device: headers.device,
                        user: headers.user,
                    })
                }
            }
        }
    }
}