rusty-bever/src/main.rs

63 lines
1.7 KiB
Rust
Raw Normal View History

2021-08-19 22:46:50 +02:00
// This needs to be explicitely included before diesel is imported to make sure
2021-08-21 20:22:19 +02:00
// compilation succeeds in the release Docker image.
2021-08-19 22:46:50 +02:00
extern crate openssl;
2021-08-20 23:09:22 +02:00
#[macro_use]
extern crate rocket;
#[macro_use]
extern crate diesel_migrations;
2021-08-19 22:46:50 +02:00
use rocket::{fairing::AdHoc, Build, Rocket};
use rocket_sync_db_pools::{database, diesel};
2021-08-21 21:42:36 +02:00
pub(crate) mod guards;
2021-08-22 16:24:59 +02:00
mod routes;
2021-08-20 16:52:58 +02:00
2021-08-19 22:46:50 +02:00
embed_migrations!();
#[database("postgres_rb")]
pub struct RbDbConn(diesel::PgConnection);
2021-08-22 16:45:01 +02:00
async fn run_db_migrations(rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>>
{
2021-08-19 22:46:50 +02:00
let conn = RbDbConn::get_one(&rocket)
.await
.expect("database connection");
conn.run(|c| match embedded_migrations::run(c) {
Ok(()) => Ok(rocket),
Err(_) => Err(rocket),
})
.await
}
2021-08-22 16:45:01 +02:00
async fn create_admin_user(rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>>
{
2021-08-21 20:22:19 +02:00
let admin_user = std::env::var("ADMIN_USER").unwrap_or(String::from("admin"));
let admin_password = std::env::var("ADMIN_PASSWORD").unwrap_or(String::from("password"));
2021-08-21 18:05:16 +02:00
let conn = RbDbConn::get_one(&rocket)
.await
.expect("database connection");
2021-08-21 21:42:36 +02:00
conn.run(move |c| {
rb::auth::create_admin_user(c, &admin_user, &admin_password)
.expect("failed to create admin user")
})
.await;
2021-08-21 18:05:16 +02:00
Ok(rocket)
}
2021-08-19 22:46:50 +02:00
#[launch]
2021-08-22 16:45:01 +02:00
fn rocket() -> _
{
2021-08-19 22:46:50 +02:00
rocket::build()
.attach(RbDbConn::fairing())
.attach(AdHoc::try_on_ignite(
"Run database migrations",
run_db_migrations,
))
2021-08-21 21:42:36 +02:00
.attach(AdHoc::try_on_ignite("Create admin user", create_admin_user))
2021-08-22 16:24:59 +02:00
.mount("/api/auth", routes::auth::routes())
.mount("/api/admin", routes::admin::routes())
}