First define a nice enum somewhere as I'm scared of string literals.
public enum MembershipFlagType
{
RequirePasswordChange
}
Next we'll put in the code that sets the flag - e.g. in an ActionMethod where the user password is reset:
MembershipUser user = Membership.GetUser(User.Identity.Name);
user.Comment = MembershipFlagType.RequirePasswordChange.ToString();
Membership.UpdateUser(user);
string newPassword = user.ResetPassword();
Now we define a new Action Filter Attribute to perform a check for the RequirePasswordChange flag:
public class EnforcePasswordPolicy : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
MembershipUser user = Membership.GetUser(filterContext.HttpContext.User.Identity.Name);
if (user.Comment == MembershipFlagType.RequirePasswordChange.ToString())
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new {controller = "account", action = "changepassword"}));
base.OnActionExecuting(filterContext);
}
}
Then all you have to do is decorate your ActionMethods with the new attribute:
[Authorize]
[EnforcePasswordPolicy]
public ActionResult Index(IndexViewModel viewModel)
{
...
}
Don't forget to clear the comment field after the user has changed their password, otherwise they'll be stuck in a loop.
I've been looking for something like this. But instead of use the Comment field. My check is if CreationDate == LastPasswordChangeDate. Those match on user creation.
ReplyDeleteThank you. This is exactly what I was looking for.
ReplyDeleteExcellent! A bit hacky, but mission accomplished...
ReplyDeleteCan you please tell me how to Clear the comment field?
ReplyDelete