diff --git a/src/main.rs b/src/main.rs index ff2274d..4fe8b04 100644 --- a/src/main.rs +++ b/src/main.rs @@ -269,6 +269,7 @@ fn run() -> Result<()> { }; rocket::ignite() + .manage(db::DB::new(&db_path)?) .mount(&static_url, StaticFiles::from(web_dir_path)) .mount(&api_url, rocket_api::get_routes()) .launch(); diff --git a/src/rocket_api.rs b/src/rocket_api.rs index 6febf90..ba156a5 100644 --- a/src/rocket_api.rs +++ b/src/rocket_api.rs @@ -1,10 +1,60 @@ +use rocket::{Outcome, State}; +use rocket::http::{Cookies, Status}; +use rocket::request::{self, Request, FromRequest}; use rocket_contrib::json::Json; +use config::{self, Config}; +use db::DB; +use errors; +use user; + const CURRENT_MAJOR_VERSION: i32 = 2; const CURRENT_MINOR_VERSION: i32 = 2; pub fn get_routes() -> Vec { - routes![version] + routes![ + version, + initial_setup, + get_settings, + ] +} + +struct Auth { + username: String, +} + +impl<'a, 'r> FromRequest<'a, 'r> for Auth { + type Error = (); + + fn from_request(request: &'a Request<'r>) -> request::Outcome { + let mut cookies = request.guard::().unwrap(); + match cookies.get_private("username") { + Some(u) => Outcome::Success(Auth { username: u.to_string() }), + _ => Outcome::Failure((Status::Forbidden, ())) + } + } +} + +struct AdminRights {} +impl<'a, 'r> FromRequest<'a, 'r> for AdminRights { + type Error = (); + + fn from_request(request: &'a Request<'r>) -> request::Outcome { + let db = request.guard::>()?; + + match user::count::(&db) { + Err(_) => return Outcome::Failure((Status::InternalServerError, ())), + Ok(0) => return Outcome::Success(AdminRights {}), + _ => () + }; + + let auth = request.guard::()?; + match user::is_admin::(&db, &auth.username) { + Err(_) => Outcome::Failure((Status::InternalServerError, ())), + Ok(true) => Outcome::Success(AdminRights {}), + Ok(false) => Outcome::Failure((Status::Forbidden, ())), + } + } } #[derive(Serialize)] @@ -21,3 +71,22 @@ fn version() -> Json { }; Json(current_version) } + +#[derive(Serialize)] +struct InitialSetup { + has_any_users: bool, +} + +#[get("/initial_setup")] +fn initial_setup(db: State) -> Result, errors::Error> { + let initial_setup = InitialSetup { + has_any_users: user::count::(&db)? > 0, + }; + Ok(Json(initial_setup)) +} + +#[get("/settings")] +fn get_settings(db: State, _admin_rights: AdminRights) -> Result, errors::Error> { + let config = config::read::(&db)?; + Ok(Json(config)) +}