Ejemplo n.º 1
0
        //public Task SendAsync(IdentityMessage message)
        public async Task SendAsync(IdentityMessage message)
        {
            // Plug in your email service here to send an email.
            bool IsSmtpServer = RBAC_ExtendedMethods.GetConfigSettingAsBool("");

            //await Send(message);
            Send2HotmailAccount(message);
        }
Ejemplo n.º 2
0
 public EmailService()
 {
     this.m_Server    = RBAC_ExtendedMethods.GetConfigSetting(cKey_SmtpServer);
     this.m_Port      = RBAC_ExtendedMethods.GetConfigSettingAsInt(cKey_SmtpPort);
     this.m_Username  = RBAC_ExtendedMethods.GetConfigSetting(cKey_SmtpUsername);
     this.m_Password  = RBAC_ExtendedMethods.GetConfigSetting(cKey_SmtpPassword);
     this.m_EMailFrom = RBAC_ExtendedMethods.GetConfigSetting(cKey_SmtpEMailFrom);
     this.m_IsSmtpNetworkDeliveryMethodEnabled = RBAC_ExtendedMethods.GetConfigSettingAsBool(cKey_SmtpNetworkDeliveryMethodEnabled);
 }
Ejemplo n.º 3
0
        public Task SendAsync(IdentityMessage message)
        {
            var Twilio = new TwilioRestClient(RBAC_ExtendedMethods.GetConfigSetting(RBAC_ExtendedMethods.cKey_SMSSid), RBAC_ExtendedMethods.GetConfigSetting(RBAC_ExtendedMethods.cKey_SMSToken));

            var result = Twilio.SendMessage(RBAC_ExtendedMethods.GetConfigSetting(RBAC_ExtendedMethods.cKey_SMSFromPhone), message.Destination, message.Body, "");

            // Plug in your SMS service here to send a text message.
            return(Task.FromResult(0));
        }
Ejemplo n.º 4
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);
    }
Ejemplo n.º 5
0
        public static ApplicationUserManager Create(IdentityFactoryOptions <ApplicationUserManager> options, IOwinContext context)
        {
            var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get <RBACDbContext>()));

            // Configure validation logic for usernames
            manager.UserValidator = new UserValidator <ApplicationUser, int>(manager)
            {
                AllowOnlyAlphanumericUserNames = false,
                RequireUniqueEmail             = true
            };

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = RBAC_ExtendedMethods.GetConfigSettingAsInt(RBAC_ExtendedMethods.cKey_PasswordRequiredLength, 6),
                RequireNonLetterOrDigit = RBAC_ExtendedMethods.GetConfigSettingAsBool(RBAC_ExtendedMethods.cKey_PasswordRequireNonLetterOrDigit, true),
                RequireDigit            = RBAC_ExtendedMethods.GetConfigSettingAsBool(RBAC_ExtendedMethods.cKey_PasswordRequireDigit, true),
                RequireLowercase        = RBAC_ExtendedMethods.GetConfigSettingAsBool(RBAC_ExtendedMethods.cKey_PasswordRequireLowercase, true),
                RequireUppercase        = RBAC_ExtendedMethods.GetConfigSettingAsBool(RBAC_ExtendedMethods.cKey_PasswordRequireUppercase, true),
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault          = RBAC_ExtendedMethods.GetConfigSettingAsBool(RBAC_ExtendedMethods.cKey_UserLockoutEnabled);
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(RBAC_ExtendedMethods.GetConfigSettingAsDouble(RBAC_ExtendedMethods.cKey_AccountLockoutTimeSpan));
            manager.MaxFailedAccessAttemptsBeforeLockout = RBAC_ExtendedMethods.GetConfigSettingAsInt(RBAC_ExtendedMethods.cKey_MaxFailedAccessAttemptsBeforeLockout);

            // Register two factor authentication providers. This application uses Phone and Emails as a step of receiving a code for verifying the user
            // You can write your own provider and plug it in here.
            manager.RegisterTwoFactorProvider("Phone Code", new PhoneNumberTokenProvider <ApplicationUser, int>
            {
                MessageFormat = "Your security code is {0}"
            });

            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <ApplicationUser, int>
            {
                Subject    = "Security Code",
                BodyFormat = "Your security code is {0}"
            });

            manager.EmailService = new EmailService();
            manager.SmsService   = new SmsService();
            var dataProtectionProvider = options.DataProtectionProvider;

            if (dataProtectionProvider != null)
            {
                manager.UserTokenProvider =
                    new DataProtectorTokenProvider <ApplicationUser, int>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
Ejemplo n.º 6
0
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        try
        {
            //Redirect user to Offline if Maintenance is Enabled!
            if (RBAC_ExtendedMethods.GetConfigSettingAsBool(RBAC_ExtendedMethods.cKey_GeneralMaintenanceEnabled))
            {
                string allowedIPs = RBAC_ExtendedMethods.GetConfigSetting(RBAC_ExtendedMethods.cKey_GeneralMaintenanceAllowedIPs);
                if (/*!filterContext.HttpContext.Request.IsLocal && */ !allowedIPs.Contains(filterContext.HttpContext.Request.UserHostAddress))
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Unauthorised", action = "Offline" }));
                }
            }
            //Audit params
            //string strController = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            //string strAction = filterContext.ActionDescriptor.ActionName;
            //AuditHelpers.AppEventInfo(AppSession.Profile.Id.ToString(), String.Format("Your are accessing to : {0}/{1}", strController, strAction), filterContext.HttpContext.Request.RawUrl);

            if (!filterContext.HttpContext.Request.IsAuthenticated)
            {
                //Redirect user to login page if not yet authenticated.  This is a protected resource!
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "Login", returnUrl = filterContext.HttpContext.Request.FilePath }));
            }

            else
            {
                //Create permission string based on the requested controller name and action name in the format 'controllername-action'
                string requiredPermission = String.Format("{0}-{1}", filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.ActionDescriptor.ActionName);

                if (!filterContext.HttpContext.User.HasPermission(requiredPermission) & !filterContext.HttpContext.User.IsSysAdmin())
                {
                    //User doesn't have the required permission and is not a SysAdmin, return our custom “401 Unauthorized” access error
                    //Since we are setting filterContext.Result to contain an ActionResult page, the controller's action will not be run.
                    //The custom “401 Unauthorized” access error will be returned to the browser in response to the initial request.
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary {
                        { "action", "Index" }, { "controller", "Unauthorised" }
                    });
                }
                //If the user has the permission to run the controller's action, the filterContext.Result will be uninitialized and
                //executing the controller's action is dependant on whether filterContext.Result is uninitialized.
            }
        }
        catch (Exception ex)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Unauthorised", action = "Error", _errorMsg = ex.Message }));
        }
    }
Ejemplo n.º 7
0
        public ActionResult OTP4EmailVerification(TOTP4EmailViewModelPost model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            IEnumerable <string> _errors = new string[0];
            bool result = RBAC_ExtendedMethods.VerifyOTP4Email(model.UserId, model.SecurityPIN, this.UserManager, this.SignInManager, out _errors);

            if (result)
            {
                return(RedirectToAction("Index", "Home"));
            }
            AddErrors(new IdentityResult(_errors));
            return(View(model));
        }
Ejemplo n.º 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));
        }
Ejemplo n.º 9
0
 public ActionResult ResetPassword(string code)
 {
     ViewBag.RequiredLength = RBAC_ExtendedMethods.GetConfigSettingAsInt(RBAC_ExtendedMethods.cKey_PasswordRequiredLength, 6);
     return(code == null?View("Error") : View());
 }
Ejemplo n.º 10
0
 //
 // GET: /Manage/ChangePassword
 public ActionResult ChangePassword()
 {
     ViewBag.RequiredLength = RBAC_ExtendedMethods.GetConfigSettingAsInt(RBAC_ExtendedMethods.cKey_PasswordRequiredLength, 6);
     return(View());
 }
Ejemplo n.º 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));
        }
Ejemplo n.º 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));
        }