Add insert_principal method to AuthenticationProvider

This commit is contained in:
Lennart
2025-04-13 15:29:43 +02:00
parent 63c16f411d
commit f132f9ccc8
3 changed files with 14 additions and 3 deletions

View File

@@ -7,6 +7,7 @@ use async_trait::async_trait;
#[async_trait] #[async_trait]
pub trait AuthenticationProvider: 'static { pub trait AuthenticationProvider: 'static {
async fn get_principal(&self, id: &str) -> Result<Option<User>, crate::Error>; async fn get_principal(&self, id: &str) -> Result<Option<User>, crate::Error>;
async fn insert_principal(&self, user: User) -> Result<(), crate::Error>;
async fn validate_user_token(&self, user_id: &str, token: &str) -> Result<Option<User>, Error>; async fn validate_user_token(&self, user_id: &str, token: &str) -> Result<Option<User>, Error>;
async fn add_app_token(&self, user_id: &str, name: String, token: String) -> Result<(), Error>; async fn add_app_token(&self, user_id: &str, name: String, token: String) -> Result<(), Error>;
} }

View File

@@ -1,11 +1,11 @@
use super::{user::AppToken, AuthenticationProvider}; use super::{AuthenticationProvider, user::AppToken};
use crate::{auth::User, error::Error}; use crate::{auth::User, error::Error};
use anyhow::anyhow; use anyhow::anyhow;
use async_trait::async_trait; use async_trait::async_trait;
use password_hash::PasswordHasher; use password_hash::PasswordHasher;
use pbkdf2::{ use pbkdf2::{
password_hash::{self, rand_core::OsRng, SaltString},
Params, Params,
password_hash::{self, SaltString, rand_core::OsRng},
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::{collections::HashMap, fs, io, ops::Deref}; use std::{collections::HashMap, fs, io, ops::Deref};
@@ -65,6 +65,16 @@ impl AuthenticationProvider for TomlPrincipalStore {
Ok(self.principals.read().await.get(id).cloned()) Ok(self.principals.read().await.get(id).cloned())
} }
async fn insert_principal(&self, user: User) -> Result<(), crate::Error> {
let mut principals = self.principals.write().await;
if principals.contains_key(&user.id) {
return Err(Error::AlreadyExists);
}
principals.insert(user.id.clone(), user);
self.save(principals.deref())?;
Ok(())
}
async fn validate_user_token(&self, user_id: &str, token: &str) -> Result<Option<User>, Error> { async fn validate_user_token(&self, user_id: &str, token: &str) -> Result<Option<User>, Error> {
let user: User = match self.get_principal(user_id).await? { let user: User = match self.get_principal(user_id).await? {
Some(user) => user, Some(user) => user,

View File

@@ -54,7 +54,7 @@ pub struct User {
#[serde(default)] #[serde(default)]
pub app_tokens: Vec<AppToken>, pub app_tokens: Vec<AppToken>,
#[serde(default)] #[serde(default)]
memberships: Vec<String>, pub memberships: Vec<String>,
} }
impl User { impl User {