BudgetSquirrel / BudgetTracker

Budget Tracker allows users to manage their money more efficiently. This API has endpoint to save, create, and manage your budgets and goals.
4 stars 0 forks source link

Use decorators to handle 403 responses on unauthorized controllers #58

Closed ianmann56 closed 5 years ago

ianmann56 commented 5 years ago

For API controllers, if the Api request is unauthorized, we're catching the validation error and returning 403 in every controller. Instead, lets create a decorator to handle that so that controllers that should throw 403s on unauthorized requests do so without us having to try catch every time. Make the change to every controller.

Example:

[HttpPost("create")]
public async Task<IActionResult> CreateBudget(ApiRequest request)
{
    try
    {
        return new JsonResult(await _budgetApi.CreateBudget(request));
    }
    catch (AuthenticationException)
    {
        return Forbid();
    }
}

becomes:

[HttpPost("create")]
[403OnUnauthorized] // Or whatever else you want to call the decorator
public async Task<IActionResult> CreateBudget(ApiRequest request)
{
    return new JsonResult(await _budgetApi.CreateBudget(request));
}
ianmann56 commented 5 years ago

Soooooo... Apparently C#'s attributes are not actually what I thought they were. I thought they were like Python's decorators where you can add logic that is run before and after a function is called. It looks like C# attributes are just declarative and don't allow extended logic.

https://stackoverflow.com/questions/15323009/implement-method-decorators-in-c-sharp

Apparently there is a way to do this in C# but you have to pay or there's a large library for it but it looks way to complicated which is not good for code practices.

So I'm gonna close this.