barreleye_common/models/
api_key.rs

1use eyre::Result;
2use sea_orm::entity::{prelude::*, *};
3use serde::{Deserialize, Serialize};
4
5use crate::{
6	models::{BasicModel, PrimaryId},
7	utils, Db, IdPrefix,
8};
9
10#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, DeriveEntityModel)]
11#[sea_orm(table_name = "api_keys")]
12#[serde(rename_all = "camelCase")]
13pub struct Model {
14	#[sea_orm(primary_key)]
15	#[serde(skip_serializing, skip_deserializing)]
16	pub api_key_id: PrimaryId,
17	pub id: String,
18	#[serde(skip_serializing)]
19	pub uuid: Uuid,
20	pub is_active: bool,
21	#[sea_orm(nullable)]
22	#[serde(skip_serializing)]
23	pub updated_at: Option<DateTime>,
24	pub created_at: DateTime,
25
26	#[sea_orm(ignore)]
27	pub key: String, // abbreviated `uuid` used in responses
28}
29
30pub use ActiveModel as ApiKeyActiveModel;
31pub use Model as ApiKey;
32
33#[derive(Copy, Clone, Debug, EnumIter)]
34pub enum Relation {}
35
36impl RelationTrait for Relation {
37	fn def(&self) -> RelationDef {
38		panic!("No RelationDef")
39	}
40}
41
42impl ActiveModelBehavior for ActiveModel {}
43
44impl BasicModel for Model {
45	type ActiveModel = ActiveModel;
46}
47
48impl Model {
49	pub fn new_model() -> ActiveModel {
50		ActiveModel {
51			id: Set(utils::new_unique_id(IdPrefix::ApiKey)),
52			uuid: Set(utils::new_uuid()),
53			is_active: Set(true),
54			..Default::default()
55		}
56	}
57
58	pub async fn get_by_uuid(db: &Db, uuid: &Uuid) -> Result<Option<Self>> {
59		Ok(Entity::find().filter(Column::Uuid.eq(*uuid)).one(db.get()).await?)
60	}
61
62	pub fn format(&self) -> Self {
63		Self { key: self.uuid.to_string()[..4].to_string(), ..self.clone() }
64	}
65}