// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓ // ┃ Copyright: (c) 2023, Mike 'PhiSyX' S. (https://github.com/PhiSyX) ┃ // ┃ SPDX-License-Identifier: MPL-2.0 ┃ // ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃ // ┃ ┃ // ┃ This Source Code Form is subject to the terms of the Mozilla Public ┃ // ┃ License, v. 2.0. If a copy of the MPL was not distributed with this ┃ // ┃ file, You can obtain one at https://mozilla.org/MPL/2.0/. ┃ // ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛ use lexa_framework::types::uuid; use sqlb::bindable_to_string; // ---- // // Type // // ---- // pub type User = UserEntity; // --------- // // Structure // // --------- // #[derive(Debug)] #[derive(serde::Deserialize, serde::Serialize)] #[derive(sqlx::FromRow)] #[derive(sqlb::Fields)] pub struct UserEntity { pub id: uuid::Uuid, pub name: String, pub password: String, pub role: UserRole, } bitflags::bitflags! { #[derive(Debug)] #[derive(Copy, Clone)] #[derive(PartialEq, Eq)] #[derive(serde::Deserialize, serde::Serialize)] #[serde(transparent)] pub struct UserRole: u32 { const USER = 1; const ADMIN = 10; } } // -------------- // // Implémentation // -> Interface // -------------- // bindable_to_string!(UserRole); impl<'r, DB> sqlx::Decode<'r, DB> for UserRole where DB: sqlx::Database + Send + Sync, &'r str: sqlx::Decode<'r, DB>, { fn decode( value: >::ValueRef, ) -> Result { let value = <&str as sqlx::Decode>::decode(value)?; if value.is_empty() { return Err("Un rôle (UserRole) ne DOIT pas être vide.".into()); } let role = match value.to_uppercase().as_str() { | "ADMIN" => Self::ADMIN, | "USER" => Self::USER, | _ => { return Err( "Un rôle (UserRole) `ADMIN` ou `USER` est attendu.".into() ) } }; Ok(role) } } impl sqlx::Type for UserRole { fn type_info() -> ::TypeInfo { sqlx::postgres::PgTypeInfo::with_name("users_role") } } impl std::fmt::Display for UserRole { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let role = match *self { | Self::ADMIN => "ADMIN", | Self::USER => "USER", | _ => "", }; write!(f, "{}", role) } }