Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use postgres #96

Merged
merged 8 commits into from
Nov 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .env.template
Original file line number Diff line number Diff line change
@@ -1 +1 @@
DATABASE_URL="mysql://iam:secret@localhost:3306/iam"
DATABASE_URL="postgres://iam:secret@localhost:3306/iam"
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ iam-macros = { path = "./iam-macros" }
jsonwebtoken = "9.3.0"
mime = "0.3.17"
rand = { version = "0.8.5", default-features = false, features = ["std", "std_rng"] }
sea-orm = { version = "1.0.0", default-features = false, features = ["macros", "runtime-actix-rustls", "sqlx-mysql", "with-chrono"] }
sea-orm = { version = "1.0.0", default-features = false, features = ["macros", "runtime-actix-rustls", "sqlx-postgres", "with-chrono"] }
serde = { version = "1.0.204", features = ["derive"] }
serde_json = "1.0.120"
tokio = { version = "1.38.0", features = ["macros", "rt-multi-thread", "signal"] }
Expand Down
14 changes: 6 additions & 8 deletions compose.yaml
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
services:
database:
image: docker.io/mysql:8.0
db:
image: docker.io/postgres:16
environment:
MYSQL_DATABASE: iam
MYSQL_USER: iam
MYSQL_PASSWORD: secret
MYSQL_ROOT_PASSWORD: secret
TZ: Europe/Budapest
POSTGRES_USER: iam
POSTGRES_PASSWORD: secret
POSTGRES_DB: iam
ports:
- "3306:3306"
- 5432:5432
69 changes: 1 addition & 68 deletions iam-cli/commands/setup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,10 @@ use rand::{
};
use sea_orm::Database;
use std::collections::BTreeMap;
use url::Url;

pub fn command() -> Command {
Command::new("setup")
.about("Creates mysql password and admin user")
.about("Creates admin user")
.arg(
Arg::new("database")
.long("database")
Expand All @@ -40,52 +39,11 @@ pub fn command() -> Command {
pub async fn run(matches: &ArgMatches) -> anyhow::Result<()> {
let client = Client::try_default().await?;

generate_mysql_password(client.clone()).await?;
create_admin_user(matches, client).await?;

Ok(())
}

const MYSQL_SECRET_NAME: &str = "mysql";
const MYSQL_SECRET_KEY: &str = "MYSQL_ROOT_PASSWORD";

async fn generate_mysql_password(client: Client) -> anyhow::Result<()> {
let secrets: Api<Secret> = Api::default_namespaced(client);

if secrets
.get_opt(MYSQL_SECRET_NAME)
.await
.context("Failed to query secret")?
.is_some()
{
println!("Mysql password already exists.");
return Ok(());
}

let mysql_password = Alphanumeric.sample_string(&mut OsRng, 64);

secrets
.create(
&PostParams::default(),
&Secret {
metadata: ObjectMeta {
name: Some(MYSQL_SECRET_NAME.to_owned()),
..Default::default()
},
string_data: Some({
let mut map = BTreeMap::new();
map.insert(MYSQL_SECRET_KEY.to_owned(), mysql_password);
map
}),
..Default::default()
},
)
.await
.context("Failed to create secret")?;

Ok(())
}

async fn create_admin_user(matches: &ArgMatches, client: Client) -> anyhow::Result<()> {
const SECRET_NAME: &str = "iam";
const ADMIN_EMAIL: &str = "[email protected]";
Expand All @@ -105,31 +63,6 @@ async fn create_admin_user(matches: &ArgMatches, client: Client) -> anyhow::Resu
let iam_url = matches.get_one::<String>("iam").unwrap();
let database_url = matches.get_one::<String>("database").unwrap();

let database_password = {
let secret = secrets
.get_opt(MYSQL_SECRET_NAME)
.await
.context("Failed to query secret")?
.context("No mysql secret")?
.data
.unwrap();

String::from_utf8(
secret
.get(MYSQL_SECRET_KEY)
.context("No mysql password")?
.0
.clone(),
)
.context("Not utf8 from kube rs")?
};

let database_url = {
let mut url = Url::parse(database_url).context("invalid url")?;
url.set_password(Some(&database_password)).unwrap();
url
};

let iam = Iam::new(iam_url);
let db = Database::connect(database_url.as_str()).await?;

Expand Down
1 change: 1 addition & 0 deletions iam-entity/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ license-file.workspace = true
path = "./lib.rs"

[dependencies]
chrono.workspace = true
sea-orm.workspace = true
15 changes: 13 additions & 2 deletions iam-entity/actions.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use async_trait::async_trait;
use chrono::Utc;
use sea_orm::entity::prelude::*;
use sea_orm::{JoinType, QuerySelect};
use sea_orm::{JoinType, QuerySelect, Set};

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "actions")]
Expand Down Expand Up @@ -43,7 +45,16 @@ impl Related<super::groups::Entity> for Entity {
}
}

impl ActiveModelBehavior for ActiveModel {}
#[async_trait]
impl ActiveModelBehavior for ActiveModel {
async fn before_save<C>(mut self, _db: &C, _insert: bool) -> Result<Self, DbErr>
where
C: ConnectionTrait,
{
self.updated_at = Set(Utc::now().naive_utc());
Ok(self)
}
}

impl Entity {
pub fn get_actions_for_user_id_through_groups(id: &str) -> Select<super::actions::Entity> {
Expand Down
17 changes: 14 additions & 3 deletions iam-entity/apps.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use sea_orm::entity::prelude::*;
use async_trait::async_trait;
use chrono::Utc;
use sea_orm::{entity::prelude::*, Set};

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "apps")]
Expand All @@ -15,8 +17,6 @@ pub struct Model {
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}

impl ActiveModelBehavior for ActiveModel {}

impl Related<super::actions::Entity> for Entity {
fn to() -> RelationDef {
super::pivot_apps_actions::Relation::Action.def()
Expand All @@ -36,3 +36,14 @@ impl Related<super::groups::Entity> for Entity {
Some(super::pivot_apps_groups::Relation::App.def())
}
}

#[async_trait]
impl ActiveModelBehavior for ActiveModel {
async fn before_save<C>(mut self, _db: &C, _insert: bool) -> Result<Self, DbErr>
where
C: ConnectionTrait,
{
self.updated_at = Set(Utc::now().naive_utc());
Ok(self)
}
}
15 changes: 13 additions & 2 deletions iam-entity/groups.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use sea_orm::entity::prelude::*;
use async_trait::async_trait;
use chrono::Utc;
use sea_orm::{entity::prelude::*, Set};

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "groups")]
Expand Down Expand Up @@ -41,4 +43,13 @@ impl Related<super::users::Entity> for Entity {
}
}

impl ActiveModelBehavior for ActiveModel {}
#[async_trait]
impl ActiveModelBehavior for ActiveModel {
async fn before_save<C>(mut self, _db: &C, _insert: bool) -> Result<Self, DbErr>
where
C: ConnectionTrait,
{
self.updated_at = Set(Utc::now().naive_utc());
Ok(self)
}
}
15 changes: 13 additions & 2 deletions iam-entity/users.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use sea_orm::entity::prelude::*;
use async_trait::async_trait;
use chrono::Utc;
use sea_orm::{entity::prelude::*, Set};

#[derive(Clone, Debug, PartialEq, Eq, DeriveEntityModel)]
#[sea_orm(table_name = "users")]
Expand Down Expand Up @@ -43,4 +45,13 @@ impl Related<super::groups::Entity> for Entity {
}
}

impl ActiveModelBehavior for ActiveModel {}
#[async_trait]
impl ActiveModelBehavior for ActiveModel {
async fn before_save<C>(mut self, _db: &C, _insert: bool) -> Result<Self, DbErr>
where
C: ConnectionTrait,
{
self.updated_at = Set(Utc::now().naive_utc());
Ok(self)
}
}
5 changes: 2 additions & 3 deletions iam-migration/m20220311_151913_create_users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,13 @@ impl MigrationTrait for Migration {
ColumnDef::new(Column::CreatedAt)
.date_time()
.not_null()
.extra("DEFAULT CURRENT_TIMESTAMP"),
.default(Expr::current_timestamp()),
)
.col(
ColumnDef::new(Column::UpdatedAt)
.date_time()
.not_null()
.extra("DEFAULT CURRENT_TIMESTAMP")
.extra("ON UPDATE CURRENT_TIMESTAMP"),
.default(Expr::current_timestamp()),
)
.col(
ColumnDef::new(Column::DeletedAt)
Expand Down
5 changes: 2 additions & 3 deletions iam-migration/m20220311_152016_create_actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,13 @@ impl MigrationTrait for Migration {
ColumnDef::new(Column::CreatedAt)
.date_time()
.not_null()
.extra("DEFAULT CURRENT_TIMESTAMP"),
.default(Expr::current_timestamp()),
)
.col(
ColumnDef::new(Column::UpdatedAt)
.date_time()
.not_null()
.extra("DEFAULT CURRENT_TIMESTAMP")
.extra("ON UPDATE CURRENT_TIMESTAMP"),
.default(Expr::current_timestamp()),
)
.col(
ColumnDef::new(Column::DeletedAt)
Expand Down
5 changes: 2 additions & 3 deletions iam-migration/m20220416_053618_create_groups.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,13 @@ impl MigrationTrait for Migration {
ColumnDef::new(Column::CreatedAt)
.date_time()
.not_null()
.extra("DEFAULT CURRENT_TIMESTAMP"),
.default(Expr::current_timestamp()),
)
.col(
ColumnDef::new(Column::UpdatedAt)
.date_time()
.not_null()
.extra("DEFAULT CURRENT_TIMESTAMP")
.extra("ON UPDATE CURRENT_TIMESTAMP"),
.default(Expr::current_timestamp()),
)
.col(
ColumnDef::new(Column::DeletedAt)
Expand Down
Loading
Loading