2025-02-26 13:10:47 -08:00
|
|
|
use chrono::{DateTime, Utc};
|
2025-02-26 13:10:48 -08:00
|
|
|
use deadpool_diesel::postgres::Connection;
|
2025-02-26 13:10:47 -08:00
|
|
|
use diesel::{
|
|
|
|
dsl::{auto_type, AsSelect},
|
|
|
|
pg::Pg,
|
|
|
|
prelude::*,
|
|
|
|
};
|
2025-02-26 13:10:50 -08:00
|
|
|
use uuid::Uuid;
|
|
|
|
|
2025-02-26 13:10:47 -08:00
|
|
|
use crate::{app_error::AppError, schema::api_keys, teams::Team};
|
2025-02-26 13:10:50 -08:00
|
|
|
|
2025-02-26 13:10:48 -08:00
|
|
|
#[derive(Associations, Clone, Debug, Identifiable, Insertable, Queryable, Selectable)]
|
2025-02-26 13:10:47 -08:00
|
|
|
#[diesel(table_name = api_keys)]
|
2025-02-26 13:10:50 -08:00
|
|
|
#[diesel(belongs_to(Team))]
|
|
|
|
pub struct ApiKey {
|
|
|
|
pub id: Uuid,
|
|
|
|
pub team_id: Uuid,
|
2025-02-26 13:10:47 -08:00
|
|
|
pub last_used_at: Option<DateTime<Utc>>,
|
2025-02-26 13:10:50 -08:00
|
|
|
}
|
|
|
|
|
|
|
|
impl ApiKey {
|
2025-02-26 13:10:47 -08:00
|
|
|
pub async fn generate_for_team(db_conn: &Connection, team_id: Uuid) -> Result<Self, AppError> {
|
2025-02-26 13:10:48 -08:00
|
|
|
let api_key = Self {
|
2025-02-26 13:10:47 -08:00
|
|
|
team_id,
|
2025-02-26 13:10:48 -08:00
|
|
|
id: Uuid::new_v4(),
|
2025-02-26 13:10:47 -08:00
|
|
|
last_used_at: None,
|
2025-02-26 13:10:48 -08:00
|
|
|
};
|
|
|
|
let api_key_copy = api_key.clone();
|
|
|
|
db_conn
|
2025-02-26 13:10:50 -08:00
|
|
|
.interact(move |conn| {
|
2025-02-26 13:10:47 -08:00
|
|
|
diesel::insert_into(api_keys::table)
|
2025-02-26 13:10:48 -08:00
|
|
|
.values(api_key_copy)
|
|
|
|
.execute(conn)
|
2025-02-26 13:10:50 -08:00
|
|
|
})
|
|
|
|
.await
|
|
|
|
.unwrap()?;
|
|
|
|
Ok(api_key)
|
|
|
|
}
|
2025-02-26 13:10:47 -08:00
|
|
|
|
|
|
|
#[auto_type(no_type_alias)]
|
|
|
|
pub fn all() -> _ {
|
|
|
|
let select: AsSelect<ApiKey, Pg> = ApiKey::as_select();
|
|
|
|
api_keys::table.select(select)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[auto_type(no_type_alias)]
|
|
|
|
pub fn with_id(id: Uuid) -> _ {
|
|
|
|
api_keys::id.eq(id)
|
|
|
|
}
|
|
|
|
|
|
|
|
#[auto_type(no_type_alias)]
|
|
|
|
pub fn with_team(team_id: Uuid) -> _ {
|
|
|
|
api_keys::team_id.eq(team_id)
|
|
|
|
}
|
2025-02-26 13:10:50 -08:00
|
|
|
}
|