benschaf / waste-schedule

This is a waste-management App with CRUD functionality. Never forget to take out your bins on time! Connect with your community and be Eco-Conscious together.
0 stars 0 forks source link

Change the repeating user authentification code to a function decorator for code readability #46

Closed benschaf closed 3 months ago

benschaf commented 3 months ago

Like this

def author_required(view_func):
    @wraps(view_func)
    def _wrapped_view(view, request, *args, **kwargs):
        if view.get_object().author != request.user:
            messages.add_message(request, messages.ERROR, "You are not the owner of this schedule.")
            return redirect(request.META.get('HTTP_REFERER', 'landing_page'))
        return view_func(view, request, *args, **kwargs)
    return _wrapped_view

and then add it to a get or post function like so

class View(...):
    @author_required
    def get(self, request: HttpRequest, *args: str, **kwargs: Any) -> HttpResponse:
        return super().get(request, *args, **kwargs)

this should work but i'll add it if there is time

benschaf commented 3 months ago

probably the best way would be to use django permissions

benschaf commented 3 months ago

this would just be nice to have but i will not implement it as the current code works as well