Refactor recipe editing logic to use User's method for permission check and update template accordingly

This commit is contained in:
Greg Burri 2025-04-28 12:52:45 +02:00
parent be6905cc3b
commit c296689c6b
4 changed files with 9 additions and 7 deletions

View file

@ -16,6 +16,12 @@ pub struct User {
pub is_admin: bool, pub is_admin: bool,
} }
impl User {
pub fn can_edit_recipe(&self, recipe: &Recipe) -> bool {
self.is_admin || recipe.user_id == self.id
}
}
#[derive(Debug, FromRow)] #[derive(Debug, FromRow)]
pub struct UserLoginInfo { pub struct UserLoginInfo {
pub last_login_datetime: DateTime<Utc>, pub last_login_datetime: DateTime<Utc>,
@ -45,10 +51,6 @@ pub struct Recipe {
pub groups: Vec<Group>, pub groups: Vec<Group>,
} }
pub fn can_user_edit_recipe(user: &User, recipe: &Recipe) -> bool {
user.is_admin || recipe.user_id == user.id
}
#[derive(Debug, FromRow)] #[derive(Debug, FromRow)]
pub struct Group { pub struct Group {
pub id: i64, pub id: i64,

View file

@ -104,7 +104,7 @@ pub async fn dev_panel(
} }
} }
///// DEV_PANEL ///// ///// LOGS /////
#[derive(Deserialize)] #[derive(Deserialize)]
pub struct LogFile { pub struct LogFile {

View file

@ -41,7 +41,7 @@ pub async fn edit(
) -> Result<Response> { ) -> Result<Response> {
if let Some(ref user) = context.user { if let Some(ref user) = context.user {
if let Some(recipe) = connection.get_recipe(recipe_id, false).await? { if let Some(recipe) = connection.get_recipe(recipe_id, false).await? {
if model::can_user_edit_recipe(user, &recipe) { if user.can_edit_recipe(&recipe) {
Ok(Html( Ok(Html(
RecipeEditTemplate { RecipeEditTemplate {
recipes: Recipes::new( recipes: Recipes::new(

View file

@ -6,7 +6,7 @@
<h2 class="recipe-title" >{{ recipe.title }}</h2> <h2 class="recipe-title" >{{ recipe.title }}</h2>
{% if let Some(user) = context.user %} {% if let Some(user) = context.user %}
{% if crate::data::model::can_user_edit_recipe(user, recipe) %} {% if user.can_edit_recipe(recipe) %}
<a class="edit-recipe button" href="/{{ context.tr.current_lang_code() }}/recipe/edit/{{ recipe.id }}" >Edit</a> <a class="edit-recipe button" href="/{{ context.tr.current_lang_code() }}/recipe/edit/{{ recipe.id }}" >Edit</a>
{% endif %} {% endif %}
{% endif %} {% endif %}