diff --git a/src/rocket_api.rs b/src/rocket_api.rs index 32c4383..3a5a85c 100644 --- a/src/rocket_api.rs +++ b/src/rocket_api.rs @@ -1,4 +1,4 @@ -use rocket::http::{Cookies, Status}; +use rocket::http::{Cookie, Cookies, Status}; use rocket::request::{self, FromRequest, Request}; use rocket::{Outcome, State}; use rocket_contrib::json::Json; @@ -12,9 +12,10 @@ use user; const CURRENT_MAJOR_VERSION: i32 = 2; const CURRENT_MINOR_VERSION: i32 = 2; +const SESSION_FIELD_USERNAME: &str = "username"; pub fn get_routes() -> Vec { - routes![version, initial_setup, get_settings, put_settings, trigger_index] + routes![version, initial_setup, get_settings, put_settings, trigger_index, auth] } struct Auth { @@ -26,12 +27,14 @@ impl<'a, 'r> FromRequest<'a, 'r> for Auth { fn from_request(request: &'a Request<'r>) -> request::Outcome { let mut cookies = request.guard::().unwrap(); - match cookies.get_private("username") { + match cookies.get_private(SESSION_FIELD_USERNAME) { Some(u) => Outcome::Success(Auth { username: u.to_string(), }), _ => Outcome::Failure((Status::Forbidden, ())), } + + // TODO allow auth via authorization header } } @@ -102,3 +105,25 @@ fn trigger_index(command_sender: State>, _admin_rights command_sender.trigger_reindex()?; Ok(()) } + +#[derive(Deserialize)] +struct AuthCredentials { + username: String, + password: String, +} + +#[derive(Serialize)] +struct AuthOutput { + admin: bool, +} + +#[post("/auth", data = "")] +fn auth(db: State, credentials: Json, mut cookies: Cookies) -> Result<(Json), errors::Error> { + user::auth::(&db, &credentials.username, &credentials.password)?; + cookies.add_private(Cookie::new(SESSION_FIELD_USERNAME, credentials.username.clone())); + + let auth_output = AuthOutput { + admin: user::is_admin::(&db, &credentials.username)?, + }; + Ok(Json(auth_output)) +}