flabk/src/svc/profiles.rs

100 lines
2.2 KiB
Rust

use serde::Serialize;
use warp::{reject::Reject, Rejection};
use crate::{
database::{
db,
users::{self, UserSelect, Users},
},
sec,
};
#[derive(Clone)]
pub struct Profiler {
db: Users,
}
impl Profiler {
pub fn new(db: Users) -> Self {
Self { db }
}
pub async fn profile(&self, username: String) -> Result<User, UserError> {
let select = if username.contains("@") {
UserSelect::FullUsername(username)
} else {
UserSelect::Username(username)
};
Ok(User::from(self.db.user(select).await?))
}
pub async fn create_user(&self, username: String, password: String) -> Result<User, UserError> {
let result = self
.db
.create_user(users::User {
id: String::new(),
username,
host: None,
display_name: None,
password_hash: sec::hash(password),
})
.await?;
Ok(User::from(result))
}
}
#[derive(Clone, Debug, Serialize)]
pub struct User {
pub id: String,
pub username: String,
pub display_name: Option<String>,
pub host: Option<String>,
}
impl From<users::User> for User {
fn from(u: users::User) -> Self {
Self {
id: u.id,
username: u.username,
display_name: u.display_name,
host: u.host,
}
}
}
#[derive(Debug, Clone)]
pub enum UserError {
Duplicate,
NotFound,
Other(String),
}
impl From<anyhow::Error> for UserError {
fn from(err: anyhow::Error) -> Self {
Self::Other(format!("UserError: {}", err))
}
}
impl From<db::DBError> for UserError {
fn from(err: db::DBError) -> Self {
match err {
db::DBError::Duplicate => Self::Duplicate,
db::DBError::NotFound => Self::NotFound,
db::DBError::Other(e) => Self::Other(e.to_string()),
}
}
}
impl ToString for UserError {
fn to_string(&self) -> String {
match self {
Self::Duplicate => String::from("duplicate insert"),
Self::NotFound => String::from("not found"),
Self::Other(err) => err.clone(),
}
}
}
impl Reject for UserError {}