permissions: homepage, sql + crate, add/remove/view for user

This commit is contained in:
Philippe Loctaux 2023-05-08 17:15:21 +02:00
parent 8dbeffddc9
commit 440f42ed2e
26 changed files with 880 additions and 1 deletions

View file

@ -0,0 +1,11 @@
[package]
name = "permissions"
version = "0.0.0"
edition = "2021"
[dependencies]
database = { path = "../database" }
id = { path = "../id" }
thiserror = { workspace = true }
chrono = { workspace = true }
serde = { workspace = true }

View file

@ -0,0 +1,61 @@
use crate::error::Error;
use crate::Permission;
use database::sqlx::SqliteExecutor;
use database::Error as DatabaseError;
use database::Permissions as DatabasePermissions;
use id::{RoleID, UserID};
impl From<DatabasePermissions> for Permission {
fn from(db: DatabasePermissions) -> Self {
Self {
user: UserID(db.user),
role: RoleID(db.role),
created_at: db.created_at,
}
}
}
impl Permission {
pub async fn get_all(
conn: impl SqliteExecutor<'_>,
user: Option<&UserID>,
role: Option<&RoleID>,
) -> Result<Vec<Self>, Error> {
Ok(DatabasePermissions::get_all(
conn,
user.map(|UserID(user)| user.as_str()),
role.map(|RoleID(role)| role.as_str()),
)
.await?
.into_iter()
.map(Self::from)
.collect::<Vec<_>>())
}
pub async fn add(
conn: impl SqliteExecutor<'_>,
user: &UserID,
role: &RoleID,
) -> Result<(), Error> {
DatabasePermissions::add(conn, user.as_ref(), role.as_ref())
.await
.map_err(|e| match e {
DatabaseError::UniqueConstraintPrimaryKey => {
Error::Duplicate(user.to_string(), role.to_string())
}
_ => e.into(),
})?;
Ok(())
}
pub async fn delete(
conn: impl SqliteExecutor<'_>,
user: &UserID,
role: &RoleID,
) -> Result<(), Error> {
DatabasePermissions::delete(conn, user.as_ref(), role.as_ref()).await?;
Ok(())
}
}

View file

@ -0,0 +1,11 @@
// error
#[derive(thiserror::Error)]
// the rest
#[derive(Debug)]
pub enum Error {
#[error("Database: {0}")]
Database(#[from] database::Error),
#[error("The permission user:\"{0}\" and role:\"{1}\" already exists.")]
Duplicate(String, String),
}

View file

@ -0,0 +1,28 @@
mod database;
mod error;
use chrono::{DateTime, Utc};
use id::{RoleID, UserID};
use serde::Serialize;
// Exports
pub use crate::error::Error;
#[derive(Serialize, Debug, Clone)]
pub struct Permission {
user: UserID,
role: RoleID,
created_at: DateTime<Utc>,
}
impl Permission {
pub fn user(&self) -> &UserID {
&self.user
}
pub fn role(&self) -> &RoleID {
&self.role
}
pub fn created_at(&self) -> DateTime<Utc> {
self.created_at
}
}