diff --git a/server/.env.example b/server/.env.example index 071bc76..e84140d 100644 --- a/server/.env.example +++ b/server/.env.example @@ -1,5 +1,6 @@ GITHUB_CLIENT_ID= GITHUB_CLIENT_SECRET= +SINGLE_USER_NO_AUTH_MODE=true DATABASE_URL=postgres://fog_machine:fog_machine@localhost:5432/fog_machine JWT_SECRET=aabbcc CORS_ALLOWED_ORIGINS=* diff --git a/server/src/main.rs b/server/src/main.rs index 1d8cfb2..43f2d5c 100644 --- a/server/src/main.rs +++ b/server/src/main.rs @@ -44,6 +44,9 @@ pub struct Config { #[envconfig(from = "GITHUB_CLIENT_SECRET")] pub github_client_secret: String, + #[envconfig(from = "SINGLE_USER_NO_AUTH_MODE")] + pub single_user_no_auth_mode: Option, + #[envconfig(from = "JWT_SECRET")] pub jwt_secret: String, @@ -137,6 +140,10 @@ fn rocket() -> _ { }, )); + if config.single_user_no_auth_mode.unwrap_or(false) { + println!("Single user no auth mode is enabled!"); + } + let allowed_origins = if config.cors_allowed_origins == "*" { AllowedOrigins::All } else { diff --git a/server/src/user_handler.rs b/server/src/user_handler.rs index abbcc59..0e3ce13 100644 --- a/server/src/user_handler.rs +++ b/server/src/user_handler.rs @@ -66,12 +66,20 @@ impl<'r> FromRequest<'r> for User { use jwt::VerifyWithKey; // https://jwt.io/introduction/ + let server_state = req.rocket().state::().unwrap(); + if server_state + .config + .single_user_no_auth_mode + .unwrap_or(false) + { + return Outcome::Success(User { uid: -1 }); + } + let user = match req.headers().get_one("Authorization") { None => None, Some(authorization) => match authorization.strip_prefix("Bearer ") { None => None, Some(jwt_token) => { - let server_state = req.rocket().state::().unwrap(); let jwt_data: Result = jwt_token.verify_with_key(&server_state.user_jwt_key); match jwt_data { @@ -261,8 +269,40 @@ async fn sso( } #[get("/")] -async fn user(conn: Connection<'_, Db>, user: User) -> APIResponse { +async fn user( + conn: Connection<'_, Db>, + server_state: &rocket::State, + user: User, +) -> APIResponse { let db = conn.into_inner(); + + if server_state + .config + .single_user_no_auth_mode + .unwrap_or(false) + && user.uid == -1 + { + // we are in single user no auth mode, may need to initialize the user + if entity::user::Entity::find() + .filter(entity::user::Column::Id.eq(user.uid)) + .count(db) + .await? + == 0 + { + let new_user = entity::user::ActiveModel { + id: Set(-1), + email: Set(None), + password: Set(None), + contact_email: Set("user@example.com".to_owned()), + github_uid: Set(None), + language: Set(entity::user::Language::EnUs), + created_at: Set(chrono::offset::Utc::now()), + updated_at: Set(chrono::offset::Utc::now()), + }; + let _new_user = new_user.insert(db).await?; + } + } + let user = entity::user::Entity::find() .filter(entity::user::Column::Id.eq(user.uid)) .one(db)