Example #1
0
        public ActionResult RequestEmailVerification(TOTP4EmailViewModelGet model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            IEnumerable <string> _errors = new string[0];
            RBACStatus           result  = this.RequestAccountVerification(model.UserId, model.Email, this.UserManager, out _errors);

            if (result == RBACStatus.RequiresAccountActivation)
            {
                ViewBag.Message = string.Format("To verify your identity, please activate this account using the e-mail sent to '{0}'", model.Email);

                var user = this.UserManager.FindById(model.UserId);
                if (user != null)
                {
                    ViewBag.Username = user.UserName;
                    ViewBag.Email    = model.Email;
                    return(View("ConfirmEmailSent"));
                }
            }
            AddErrors(new IdentityResult(_errors));
            return(View(model));
        }
Example #2
0
        public ActionResult RequestEmailVerification(TOTP4EmailViewModelGet model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            IEnumerable <string> _errors = new string[0];
            RBACStatus           result  = this.RequestAccountVerification(model.UserId, model.Email, this.UserManager, out _errors);

            if (result == RBACStatus.RequiresAccountActivation)
            {
                ViewBag.Message = string.Format("Pour verifier votre identité, prière de suivre le lien envoyé par mail '{0}'", model.Email);

                var user = this.UserManager.FindById(model.UserId);
                if (user != null)
                {
                    ViewBag.Username = user.UserName;
                    ViewBag.Email    = model.Email;
                    return(View("ConfirmEmailSent"));
                }
            }
            AddErrors(new IdentityResult(_errors));
            return(View(model));
        }
Example #3
0
    public static RBACStatus RequestAccountVerification(this ControllerBase controller, int _userId, string _email, ApplicationUserManager userMngr, out IEnumerable <string> _errors)
    {
        RBACStatus _retVal = RBACStatus.Failure;

        _errors = new List <string>();

        try
        {
            if (userMngr.EmailService != null)
            {
                string _code = userMngr.GenerateEmailConfirmationToken(_userId);

                var callbackUrl = new UrlHelper(controller.ControllerContext.RequestContext).Action("ConfirmEmail", "Account", new { userId = _userId, code = _code }, protocol: controller.ControllerContext.RequestContext.HttpContext.Request.Url.Scheme);
                var message     = new IdentityMessage {
                    Subject = "Account Verification", Destination = _email, Body = string.Format("Please <a href='{0}'>verify</a> your account before attempting to log in to the system.", callbackUrl)
                };
                userMngr.EmailService.Send(message);

                _retVal = RBACStatus.RequiresAccountActivation;
            }
            else
            {
                _errors = new List <string> {
                    "Smtp Service has not been configured!", "Unable to send e-mail Confirmation Token..."
                };
            }
        }
        catch (Exception)
        {
            throw;
        }


        return(_retVal);
    }
    public static RBACStatus RequestAccountVerification(this ControllerBase controller, int _userId, string _email, ApplicationUserManager userMngr, out IEnumerable <string> _errors)
    {
        RBACStatus _retVal = RBACStatus.Failure;

        _errors = new List <string>();

        try
        {
            if (userMngr.EmailService != null)
            {
                string _code = userMngr.GenerateEmailConfirmationToken(_userId);

                var callbackUrl = new UrlHelper(controller.ControllerContext.RequestContext).Action("ConfirmEmail", "Account", new { userId = _userId, code = _code }, protocol: controller.ControllerContext.RequestContext.HttpContext.Request.Url.Scheme);
                var message     = new IdentityMessage {
                    Subject = "Verification de votre compte", Destination = _email, Body = string.Format("Prière de <a href='{0}'>vérifier</a> votre compte pour pouvoir vous connecter...", callbackUrl)
                };
                userMngr.EmailService.Send(message);

                _retVal = RBACStatus.RequiresAccountActivation;
            }
            else
            {
                _errors = new List <string> {
                    "Le service Smtp n'est pas configuré!", "Impossible d'envoyer le token par mail..."
                };
            }
        }
        catch (Exception)
        {
            throw;
        }


        return(_retVal);
    }
Example #5
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                List <string> _errors = new List <string>();
                try
                {
                    RBACStatus _retVal = this.Login(model, this.UserManager, this.SignInManager, out _errors);
                    switch (_retVal)
                    {
                    case RBACStatus.Success:
                    {
                        var user = UserManager.FindByName(model.UserName);
                        Session["UserProfile"] = user;
                        RBAC_ExtendedMethods.Parameters.RefreshAppParameters();
                        AuditHelpers.AppEventInfo(user.Id.ToString(), String.Format(AuditHelpers.MemberLoggedIn, user.UserName, user.Email));
                        return(RedirectToLocal(returnUrl));
                    }

                    case RBACStatus.EmailUnconfirmed:
                    {
                        //Do nothing, message will be display on login page...
                        break;
                    }

                    case RBACStatus.PhoneNumberUnconfirmed:
                    {
                        var user = UserManager.FindByName(model.UserName);
                        if (user != null)
                        {
                            if (this.SendOTP2Phone(this.UserManager, user.Id, user.PhoneNumber))
                            {
                                return(RedirectToAction("OTP4PhoneVerification", new { UserId = user.Id, phoneNumber = user.PhoneNumber, displayError = true }));
                            }
                        }
                        break;
                    }

                    case RBACStatus.RequiresVerification:
                        return(RedirectToAction("SendSecurityCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));
                    }
                }
                catch (Exception ex)
                {
                    AddErrors(new IdentityResult(ex.Message));
                }

                if (_errors.Count() > 0)
                {
                    AddErrors(new IdentityResult(_errors));
                }
            }
            // If we reach this point, something failed, redisplay form displaying error message(s)...
            return(View(model));
        }
Example #6
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                List <string> _errors = new List <string>();
                try
                {
                    RBACStatus _retVal = this.Register(model, this.UserManager, this.SignInManager, out _errors);
                    switch (_retVal)
                    {
                    case RBACStatus.Success:
                    {
                        ViewBag.Message = "Your account has been created successfully.  You can now continue and login...";
                        AuditHelpers.AppEventInfo(AppSession.Profile.Id.ToString(), String.Format("The Account  \"{0}\"<{1}> account has be created succesfully", model.UserName, model.Email));
                        return(View("Confirmation"));
                    }

                    case RBACStatus.RequiresAccountActivation:
                    {
                        ViewBag.Username = model.UserName;
                        ViewBag.Email    = model.Email;
                        return(View("ConfirmEmailSent"));
                    }

                    case RBACStatus.EmailVerification:
                    {
                        return(RedirectToAction("RequestEmailVerification", new { Username = model.UserName }));
                        //return RedirectToAction("TOTPEmailVerification4Registration", new { UserId = model.Id, email = model.Email });
                    }

                    case RBACStatus.PhoneVerification:
                    {
                        return(RedirectToAction("OTP4PhoneVerification", new { UserId = model.Id, phoneNumber = model.Mobile }));
                    }
                    }
                }
                catch (Exception ex)
                {
                    AddErrors(new IdentityResult(ex.Message));
                }

                if (_errors.Count() > 0)
                {
                    AddErrors(new IdentityResult(_errors));
                }
            }

            //If we got this far, something failed, redisplay form
            //Errors will be displayed back to the user because we have set the ModelState object with our _errors list...
            return(View(model));
        }
Example #7
0
    public static RBACStatus Register(this ControllerBase controller, RegisterViewModel model, ApplicationUserManager userMngr, ApplicationSignInManager signInMngr, out List <string> _errors)
    {
        RBACStatus _retVal = RBACStatus.Failure;

        try
        {
            //Logic driven by settings defined in the application’s configuration file...
            int _userId = RBAC_ExtendedMethods.RegisterUser(controller, model, userMngr, out _errors);
            if (_userId > -1)
            {
                model.Id = _userId;
                if (userMngr != null)
                {
                    //Check if we require an Account Verification Email as part of our registration process...
                    bool   IsAccountVerificationRequired = GetConfigSettingAsBool(cKey_AccountVerificationRequired);
                    bool   Is2FAEnabled = GetConfigSettingAsBool(cKey_2FAEnabled);
                    string DeviceType   = GetConfigSetting(cKey_2FADeviceType);

                    //if ((IsAccountVerificationRequired) || (Is2FAEnabled && DeviceType == c_EmailCode))
                    if ((IsAccountVerificationRequired && DeviceType == c_EmailCode) || (Is2FAEnabled && DeviceType == c_EmailCode))
                    {
                        //Generate Email Confirmation Token
                        _retVal = RBACStatus.Failure;
                        if (SendOTP2Email(controller, userMngr, _userId, model.Email))
                        {
                            _retVal = RBACStatus.RequiresAccountActivation;
                        }

                        return(_retVal);
                    }
                    //else if (Is2FAEnabled && DeviceType == c_PhoneCode)
                    else if ((IsAccountVerificationRequired && DeviceType == c_PhoneCode) || (Is2FAEnabled && DeviceType == c_PhoneCode))
                    {
                        _retVal = RBACStatus.Failure;
                        if (SendOTP2Phone(controller, userMngr, _userId, model.Mobile))
                        {
                            _retVal = RBACStatus.PhoneVerification;
                        }

                        return(_retVal);
                    }
                }
                _retVal = RBACStatus.Success;
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return(_retVal);
    }
Example #8
0
        public ActionResult OTP4PhoneVerification(VerifyOTPPhoneViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            IEnumerable <string> _errors = new string[0];
            RBACStatus           result  = RBAC_ExtendedMethods.VerifyOTP4Phone(model.UserId, model.PhoneNumber, model.Code, this.UserManager, this.SignInManager, out _errors);

            if (result == RBACStatus.Success)
            {
                return(RedirectToAction("Index", "Home"));
            }
            AddErrors(new IdentityResult(_errors));
            return(View(model));
        }
Example #9
0
    public static RBACStatus VerifyOTP4Phone(int _userId, string _phoneNumber, string _token, ApplicationUserManager userMngr, ApplicationSignInManager signInMngr, out IEnumerable <string> _errors)
    {
        RBACStatus _retVal = RBACStatus.Failure;

        try
        {
            IdentityResult result = userMngr.ChangePhoneNumber(_userId, _phoneNumber, _token);
            if (result == IdentityResult.Success)
            {
                ApplicationUser user = userMngr.FindById(_userId);
                if (user != null)
                {
                    signInMngr.SignIn(user, isPersistent: false, rememberBrowser: false);
                }
                _retVal = RBACStatus.Success;
            }
            _errors = result.Errors;
        }
        catch (Exception)
        {
            throw;
        }
        return(_retVal);
    }
Example #10
0
    public static RBACStatus Login(this ControllerBase controller, LoginViewModel model, ApplicationUserManager userMngr, ApplicationSignInManager signInMngr, out List <string> _errors)
    {
        RBACStatus _retVal = RBACStatus.Failure;

        _errors = new List <string>();
        try
        {
            var user = userMngr.FindByName(model.UserName);
            if (user != null)
            {
                var validCredentials = userMngr.Find(model.UserName, model.Password);
                if (userMngr.IsLockedOut(user.Id))
                {
                    _errors.Add(string.Format(c_AccountLockout, GetConfigSettingAsDouble(cKey_AccountLockoutTimeSpan)));
                    return(RBACStatus.LockedOut);
                }
                else if (userMngr.GetLockoutEnabled(user.Id) && validCredentials == null)
                {
                    userMngr.AccessFailed(user.Id);
                    if (userMngr.IsLockedOut(user.Id))
                    {
                        _errors.Add(string.Format(c_AccountLockout, GetConfigSettingAsDouble(cKey_AccountLockoutTimeSpan)));
                        return(RBACStatus.LockedOut);
                    }
                    else
                    {
                        int _attemptsLeftB4Lockout = (GetConfigSettingAsInt(cKey_MaxFailedAccessAttemptsBeforeLockout) - userMngr.GetAccessFailedCount(user.Id));
                        _errors.Add(string.Format(c_InvalidCredentials, _attemptsLeftB4Lockout));
                        return(_retVal);
                    }
                }
                else if (validCredentials == null)
                {
                    _errors.Add(c_InvalidLogin);
                    return(_retVal);
                }
                else
                {
                    //Valid credentials entered, we need to check whether email verification is required...
                    bool   IsAccountVerificationRequired = GetConfigSettingAsBool(cKey_AccountVerificationRequired);
                    bool   Is2FAEnabled = GetConfigSettingAsBool(cKey_2FAEnabled);
                    string DeviceType   = GetConfigSetting(cKey_2FADeviceType);

                    if ((IsAccountVerificationRequired && DeviceType == c_EmailCode) || (Is2FAEnabled && DeviceType == c_EmailCode))
                    {
                        //Check if email verification has been confirmed!
                        if (!userMngr.IsEmailConfirmed(user.Id))
                        {
                            //Display error message on login page, take no further action...
                            _errors.Add(c_AccountEmailUnconfirmed);
                            return(RBACStatus.EmailUnconfirmed);
                        }
                    }
                    //else if (Is2FAEnabled && DeviceType == c_PhoneCode)
                    else if ((IsAccountVerificationRequired && DeviceType == c_PhoneCode) || (Is2FAEnabled && DeviceType == c_PhoneCode))
                    {
                        if (!userMngr.IsPhoneNumberConfirmed(user.Id))
                        {
                            _errors.Add(c_AccountPhoneNumberUnconfirmed);
                            return(RBACStatus.PhoneNumberUnconfirmed);
                        }
                    }

                    bool _userLockoutEnabled = GetConfigSettingAsBool(cKey_UserLockoutEnabled);

                    //Before we signin, check that our 2FAEnabled config setting agrees with the database setting for this user...
                    if (Is2FAEnabled != userMngr.GetTwoFactorEnabled(user.Id))
                    {
                        userMngr.SetTwoFactorEnabled(user.Id, Is2FAEnabled);
                    }

                    _retVal = (RBACStatus)signInMngr.PasswordSignIn(model.UserName, model.Password, model.RememberMe, shouldLockout: _userLockoutEnabled);
                    switch (_retVal)
                    {
                    case RBACStatus.Success:
                    {
                        userMngr.ResetAccessFailedCount(user.Id);
                        break;
                    }

                    default:
                    {
                        _errors.Add(c_InvalidLogin);
                        break;
                    }
                    }
                }
            }
            else
            {
                _errors.Add(c_InvalidUser);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        return(_retVal);
    }
Example #11
0
        public HttpResponseMessage Create(RegisterViewModel user)
        {
            if (ModelState.IsValid)
            {
                List <string> _errors = new List <string>();
                try
                {
                    RBACStatus _retVal = RBAC_ExtendedMethods.Register(user, this.UserManager, this.SignInManager, out _errors);
                    switch (_retVal)
                    {
                    case RBACStatus.Success:
                    {
                        user.message   = "Account correttamente creato.  E' ora possibile autenticarsi...";
                        user.returnUrl = "Confirmation";
                        user.success   = "true";
                    }
                    break;

                    case RBACStatus.RequiresAccountActivation:
                    {
                        user.returnUrl = "ConfirmEmailSent";
                        user.success   = "true";
                    }
                    break;

                    case RBACStatus.EmailVerification:
                    {
                        user.success   = "true";
                        user.returnUrl = "RequestEmailVerification";
                    }
                    break;

                    case RBACStatus.PhoneVerification:
                    {
                        user.success   = "true";
                        user.returnUrl = "OTP4PhoneVerification";
                    }
                    break;
                    }
                }
                catch (Exception ex)
                {
                    user.message = ex.Message;
                    user.success = "false";
                }
                if (_errors.Count() > 0)
                {
                    foreach (string e in _errors)
                    {
                        user.message += e;
                    }
                    user.success = "false";
                }
            }
            else
            {
                user.success = "false";
                foreach (var e in ModelState.Values)
                {
                    foreach (var error in e.Errors)
                    {
                        user.message += "Campo non valido " + error.ErrorMessage;
                    }
                }
            }
            return(this.Request.CreateResponse <RegisterViewModel>(HttpStatusCode.OK, user));
        }
Example #12
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                List <string> _errors = new List <string>();
                try
                {
                    RBACStatus _retVal = this.Login(model, this.UserManager, this.SignInManager, out _errors);
                    switch (_retVal)
                    {
                    case RBACStatus.Success:
                        // return RedirectToLocal(returnUrl);
                        model.ResponseUrl = "GovHistory/Home/Index";
                        model.success     = "true";
                        break;

                    case RBACStatus.EmailUnconfirmed:
                    {
                        //Do nothing, message will be display on login page...
                        model.ResponseUrl = "";
                        model.success     = "false";
                        model.message     = _errors;
                        break;
                    }

                    case RBACStatus.PhoneNumberUnconfirmed:
                    {
                        var user = UserManager.FindByName(model.UserName);
                        if (user != null)
                        {
                            if (RBAC_ExtendedMethods.SendOTP2Phone(this.UserManager, user.Id, user.PhoneNumber))
                            {
                                model.ResponseUrl = "";
                                model.success     = "false";
                                model.message     = _errors;
                            }
                            //  return RedirectToAction("OTP4PhoneVerification", new { UserId = user.Id, phoneNumber = user.PhoneNumber, displayError = true });
                        }
                        break;
                    }

                    case RBACStatus.RequiresVerification:
                        model.ResponseUrl = "SendSecurityCode";
                        model.success     = "false";
                        break;
                        // return RedirectToAction("SendSecurityCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
                    }
                }
                catch (Exception ex)
                {
                    //AddErrors(new IdentityResult(ex.Message));
                    model.ResponseUrl = "";
                    model.success     = "false";
                    model.message     = new IdentityResult(ex.Message).Errors.ToList();
                }

                if (_errors.Count() > 0)
                {
                    //AddErrors(new IdentityResult(_errors));
                    model.success = "false";
                    model.message = new IdentityResult(_errors).Errors.ToList();
                }
            }
            else
            {
                model.ResponseUrl = "";
                model.success     = "false";
                model.message     = new List <string> {
                    "inserire i campi obbligatori"
                };
            }
            // If we reach this point, something failed, redisplay form displaying error message(s)...
            return(Json(model, JsonRequestBehavior.AllowGet));
        }