users.rs 1.31 KB
Newer Older
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
1
use rocket_contrib::json::Json;
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
2
use rocket::{Response, State};
3
4
use rocket::http::Status;

Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
5
use crate::config::Config;
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
6
use crate::DbConn;
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
7
8
use crate::models::errors::{ErrorResponse, make_500};
use crate::models::users::{LocalUser, CreateUserRequest, AuthClaims, AuthTokenRequest, AuthTokenResponse};
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
9
10
11


#[post("/users/me/token", data = "<auth_request>")]
12
pub async fn create_auth_token(
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
13
    conn: DbConn,
14
    config: State<'_, Config>,
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
15
16
    auth_request: Json<AuthTokenRequest>
) -> Result<Json<AuthTokenResponse>, ErrorResponse<()>> {
17

18
19
20
21
    let user_info = conn.run(move |c| {
        LocalUser::get_user_by_creds(c, &auth_request.username, &auth_request.password)
    }).await?;

Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
22
23
24
    let token = AuthClaims::new(&user_info, config.web_app.token_duration)
        .encode(&config.web_app.secret)
        .map_err(|e| make_500(e))?;
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
25

26
    Ok(Json(AuthTokenResponse { token }))
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
27
28
}

29
#[post("/users", data = "<user_request>")]
30
pub async fn create_user<'r>(conn: DbConn, user_request: Json<CreateUserRequest>) -> Result<Response<'r>, ErrorResponse<()>>{
31
    // TODO: Check current user if any to check if user has permission to create users (with or without role)
32
33
34
35
    let _user_info = conn.run(|c| {
        LocalUser::create_user(&c, user_request.into_inner())
    }).await?;

36
37
38
    Response::build()
        .status(Status::Created)
        .ok()
Gaël Berthaud-Müller's avatar
Gaël Berthaud-Müller committed
39
}