Can anyone recommend how to tidy up my piece of code/make it more use able. This is what happens:
If controller has [Authorize]
the first line's of code within that function read
var user = GetUser(_userService);
if (user == null)
return RedirectToAction("Logout", "User");
This allows me not only to check if the authentication cookie is there, but you also check that the user still lives within the database.
My get user function is pretty simple, Gets the cookie, decrypt's it and then uses the service layer to return the user this function is declared in a class all my controller inherit from.
public User GetUser(IUserService service)
{
var name = HttpContext.User.Identity.Name;
var faDecrypt = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value);
if (faDecrypt == null)
return null;
var userString = faDecrypt.Name;
if (String.IsNullOrEmpty(userString))
return null;
return service.Find(userString);
}
All my controllers parameteres are injected using Ninject and look like below:
public UserController(IUserService service, IUnitOfWork unitOfWork)
{
_service = service;
_unitOfWork = unitOfWork;
}
The problem I am facing is I want to move this out to somewhere where it says:
"Authorize tag is in place, Run get user to ensure the user is real, if real continue, if not redirect"
I also require this function to be able to be inject within Ninject as each service has a HTTP Request Lifetime.
---Update---
After implementing a CustomAttribute shown below:
public class EnhanchedAuthorize : ActionFilterAttribute
{
private readonly IUserService _service;
public EnhanchedAuthorize(IUserService service)
{
_service = service;
}
}
When using it like this:
[HttpPost]
[EnhanchedAuthorize]
public ActionResult Edit(VenueCreateEditViewModel model)
I get the following error
"Constructor EnhanchedAuthorize has 1 parameter(s) but is invoked with 0 parameter(s)"
Why does Ninject not handle this?