routes.rs 1.89 KB
Newer Older
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
1
use serde::{Serialize, Deserialize};
2

Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
3
use rocket_contrib::json::Json;
4
5
6
7
8
9
10
11
use rocket::Response;
use rocket::http::Status;
use uuid::Uuid;
use jsonwebtoken::{encode, Header, EncodingKey};
use chrono::prelude::{DateTime, Utc};
use chrono::Duration;
use chrono::serde::ts_seconds;

Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
12
use crate::DbConn;
13
14
use crate::models::errors::ErrorResponse;
use crate::models::users::{LocalUser, CreateUserRequest};
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
15
16
17
18
19

#[derive(Debug, Serialize, Deserialize)]
struct AuthClaims {
    jti: String,
    sub: String,
20
21
22
23
    #[serde(with = "ts_seconds")]
    exp: DateTime<Utc>,
    #[serde(with = "ts_seconds")]
    iat: DateTime<Utc>,
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
24
25
26
27
28
29
30
31
32
}

#[derive(Debug, Serialize)]
pub struct AuthTokenResponse {
    token: String
}

#[derive(Debug, Deserialize)]
pub struct AuthTokenRequest {
33
    username: String,
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
34
35
36
37
    password: String,
}

#[post("/users/me/token", data = "<auth_request>")]
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
pub fn create_auth_token(conn: DbConn, auth_request: Json<AuthTokenRequest>) -> Result<Json<AuthTokenResponse>, ErrorResponse<()>> {
    let user_info = LocalUser::get_user_by_creds(&conn, &auth_request.username, &auth_request.password)?;
    let jti = Uuid::new_v4().to_simple().to_string();
    let iat = Utc::now();
    let exp = iat + Duration::minutes(1);

    let claims = AuthClaims {
        jti: jti,
        sub: user_info.id,
        exp: exp,
        iat: iat,
    };

    // TODO: catch error
    let token = encode(&Header::default(), &claims, &EncodingKey::from_secret("changeme".as_ref())).unwrap();
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
53

54
    Ok(Json(AuthTokenResponse { token }))
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
55
56
}

57
58
59
60
61
62
63
#[post("/users", data = "<user_request>")]
pub fn create_user<'r>(conn: DbConn, user_request: Json<CreateUserRequest>) -> Result<Response<'r>, ErrorResponse<()>>{
    // TODO: Check current user if any to check if user has permission to create users (with or without role)
    let _user_info = LocalUser::create_user(&conn, user_request.into_inner())?;
    Response::build()
        .status(Status::Created)
        .ok()
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
64
}