Esempio n. 1
0
        public async Task <int> ResetPassword(IOwinContext owinContext, HttpRequestBase Request, ResetPasswordItem model)
        {
            try
            {
                InstanceUserManager instanceUserManager = owinContext.GetUserManager <InstanceUserManager>();
                IdentityUserItem    user = await instanceUserManager.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    IdentityResult result = await instanceUserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

                    if (result.Succeeded)
                    {
                        return(1);
                    }
                    else
                    {
                        foreach (var error in result.Errors)
                        {
                            strErrorMessage = strErrorMessage + " " + error;
                        }
                        return(2);
                    }
                }
                else
                {
                    return(0);
                }
            }
            catch (Exception ex)
            {
                serviceException = ex;
                return(-1);
            }
        }
Esempio n. 2
0
        public async Task <int> ForgotPassword(IOwinContext owinContext, HttpRequestBase Request, ForgotPasswordItem model)
        {
            try
            {
                InstanceUserManager instanceUserManager = owinContext.GetUserManager <InstanceUserManager>();
                var user = await instanceUserManager.FindByEmailAsync(model.Email);

                if (user == null || !(await instanceUserManager.IsEmailConfirmedAsync(user.Id)))
                {
                    //return View("ForgotPasswordConfirmation");
                    return(0);
                }
                string code = await instanceUserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = new UrlHelper(Request.RequestContext).Action("ResetPassword", "Login", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                //var callbackUrl = Url.Action("ResetPassword", "Login", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await instanceUserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking this link " + callbackUrl);

                //return RedirectToAction("ForgotPasswordConfirmation", "Login");
                return(1);
            }
            catch (Exception ex)
            {
                serviceException = ex;
                //return LoginStatus.SystemFailure;
                return(-1);
            }
        }
        public static InstanceUserManager Create(IdentityFactoryOptions <InstanceUserManager> options, IOwinContext context)
        {
            var manager = new InstanceUserManager(new UserStore <IdentityUserItem>(context.Get <UserContext>()));

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

            // Configure validation logic for passwords
            manager.PasswordValidator = new PasswordValidator
            {
                RequiredLength          = 6,
                RequireNonLetterOrDigit = false,
                RequireDigit            = true,
                RequireLowercase        = true,
                RequireUppercase        = true,
            };

            // Configure user lockout defaults
            manager.UserLockoutEnabledByDefault          = true;
            manager.DefaultAccountLockoutTimeSpan        = TimeSpan.FromMinutes(5);
            manager.MaxFailedAccessAttemptsBeforeLockout = 5;

            // 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 <IdentityUserItem>
            {
                MessageFormat = "Your security code is {0}"
            });
            manager.RegisterTwoFactorProvider("Email Code", new EmailTokenProvider <IdentityUserItem>
            {
                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 <IdentityUserItem>(dataProtectionProvider.Create("ASP.NET Identity"));
            }
            return(manager);
        }
Esempio n. 4
0
        public int Delete(string Id, IOwinContext owinContext)
        {
            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    InstanceUserManager instanceUsermanager = owinContext.GetUserManager <InstanceUserManager>();

                    IdentityUserItem identityUserItem = instanceUsermanager.FindById(Id);

                    ICollection <IdentityUserLogin> logins = identityUserItem.Logins;
                    foreach (var login in logins.ToList())
                    {
                        instanceUsermanager.RemoveLogin(login.UserId, new UserLoginInfo(login.LoginProvider, login.ProviderKey));
                    }

                    IList <string> rolesForUser = instanceUsermanager.GetRoles(Id);
                    if (rolesForUser.Count() > 0)
                    {
                        foreach (var item in rolesForUser.ToList())
                        {
                            IdentityResult result = instanceUsermanager.RemoveFromRole(identityUserItem.Id, item);
                        }
                    }

                    IdentityResult userResult = instanceUsermanager.Delete(identityUserItem);

                    if (userResult.Succeeded)
                    {
                        scope.Complete();
                        return(1);
                    }
                    else
                    {
                        scope.Dispose();
                        return(0);
                    }
                }
                catch (Exception ex)
                {
                    serviceException = ex;
                    scope.Dispose();
                    return(-1);
                }
            }
        }
Esempio n. 5
0
        public async Task <LoginStatus> Login(IOwinContext owinContext, HttpRequestBase Request, LoginItem model)
        {
            try
            {
                InstanceUserManager   instanceUserManager   = owinContext.GetUserManager <InstanceUserManager>();
                InstanceSignInManager instanceSignInManager = owinContext.GetUserManager <InstanceSignInManager>();
                IdentityUserItem      signedUser            = instanceUserManager.FindByEmail(model.Email);
                var result = await instanceSignInManager.PasswordSignInAsync(signedUser.UserName, model.Password, model.RememberMe, shouldLockout : true);

                switch (result)
                {
                case SignInStatus.Success:
                    var currentUser = await instanceUserManager.FindByNameAsync(signedUser.UserName);

                    if (!await instanceUserManager.IsEmailConfirmedAsync(currentUser.Id))
                    {
                        var code = await instanceUserManager.GenerateEmailConfirmationTokenAsync(currentUser.Id);

                        var callbackUrl = new UrlHelper(Request.RequestContext).Action("ConfirmEmail", "Login", new { userId = currentUser.Id, code = code }, protocol: Request.Url.Scheme);
                        instanceUserManager.SendEmail(currentUser.Id, "Confirm your account", "Please confirm your account by clicking this link " + callbackUrl);
                        return(LoginStatus.RequireConfirmation);
                    }
                    else
                    {
                        return(LoginStatus.Success);
                    }

                case SignInStatus.LockedOut:
                    return(LoginStatus.LockedOut);

                case SignInStatus.Failure:
                    return(LoginStatus.Failure);

                default:
                    return(LoginStatus.Failure);
                }
            }
            catch (Exception ex)
            {
                serviceException = ex;
                return(LoginStatus.SystemFailure);
            }
        }
 public InstanceSignInManager(InstanceUserManager userManager, IAuthenticationManager authenticationManager)
     : base(userManager, authenticationManager)
 {
 }
Esempio n. 7
0
        public int Insert(UserItem userItem, IOwinContext owinContext, HttpRequestBase Request)
        {
            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    InstanceUserManager instanceUserManager = owinContext.GetUserManager <InstanceUserManager>();

                    var user = new IdentityUserItem
                    {
                        UserName  = userItem.UserName,
                        Email     = userItem.Email,
                        FirstName = userItem.FirstName,
                        LastName  = userItem.LastName,
                    };

                    IdentityResult result = instanceUserManager.Create(user, userItem.Password);

                    if (result.Succeeded)
                    {
                        foreach (string item in userItem.UserItemSelectedRoles)
                        {
                            var roles = context.Roles.ToList();

                            if (roles.Count() > 0)
                            {
                                foreach (IdentityRole identityRole in roles)
                                {
                                    if (identityRole.Name == item)
                                    {
                                        instanceUserManager.AddToRole(user.Id, identityRole.Name);
                                    }
                                }
                                ;
                            }
                        }

                        string code        = instanceUserManager.GenerateEmailConfirmationToken(user.Id);
                        string callbackUrl = new UrlHelper(Request.RequestContext).Action("ConfirmEmail", "Login", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        instanceUserManager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking this link " + callbackUrl);
                        scope.Complete();
                        return(1);
                    }
                    else
                    {
                        userItem.UserItemRoles = context.Roles.Select(x => new SelectListItem {
                            Text = x.Name, Value = x.Id.ToString()
                        }).ToList();
                        foreach (var error in result.Errors)
                        {
                            strErrorMessage = ErrorMessage + " " + error;
                        }
                        scope.Dispose();
                        return(0);
                    }
                }
                catch (Exception ex)
                {
                    serviceException       = ex;
                    userItem.UserItemRoles = context.Roles.Select(x => new SelectListItem {
                        Text = x.Name, Value = x.Id.ToString()
                    }).ToList();
                    if (ex.Message != null)
                    {
                        strErrorMessage = ex.Message;
                    }
                    else
                    {
                        strErrorMessage = ex.InnerException.Message;
                    }
                    scope.Dispose();
                    return(-1);
                }
            }
        }
Esempio n. 8
0
        public int Update(UpdateUserItem updateUserItem, IOwinContext owinContext)
        {
            using (var scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    InstanceUserManager instanceUserManager = owinContext.GetUserManager <InstanceUserManager>();

                    IdentityUserItem identityUserItem = instanceUserManager.FindById(updateUserItem.Id.ToString());

                    if (updateUserItem != null)
                    {
                        identityUserItem.Email     = updateUserItem.Email;
                        identityUserItem.UserName  = updateUserItem.UserName;
                        identityUserItem.FirstName = updateUserItem.FirstName;
                        identityUserItem.LastName  = updateUserItem.LastName;

                        IdentityResult result = instanceUserManager.Update(identityUserItem);

                        if (result.Succeeded)
                        {
                            //this part is not similar to create need more investigation
                            foreach (string item in updateUserItem.UserItemSelectedRoles)
                            {
                                string roleName = context.Roles.Find(item).Name; //sometimes this part not works, may be the context is not initialized?
                                instanceUserManager.AddToRole(identityUserItem.Id, roleName);
                            }

                            List <IdentityUserRole> listIdentityUserRole = instanceUserManager.FindById(identityUserItem.Id).Roles.ToList();

                            foreach (IdentityUserRole item in listIdentityUserRole)
                            {
                                if (!updateUserItem.UserItemSelectedRoles.Contains(item.RoleId))
                                {
                                    string roleToRemove = context.Roles.Find(item.RoleId).Name;
                                    instanceUserManager.RemoveFromRole(identityUserItem.Id, roleToRemove);
                                }
                            }
                            scope.Complete();
                            return(1);
                        }
                        else
                        {
                            updateUserItem.UserItemRoles = context.Roles.Select(x => new SelectListItem {
                                Text = x.Name, Value = x.Id.ToString()
                            }).ToList();
                            foreach (var error in result.Errors)
                            {
                                strErrorMessage = ErrorMessage + " " + error;
                            }
                            scope.Dispose();
                            return(0);
                        }
                    }
                    else
                    {
                        updateUserItem.UserItemRoles = context.Roles.Select(x => new SelectListItem {
                            Text = x.Name, Value = x.Id.ToString()
                        }).ToList();
                        strErrorMessage = "There is no user with provided ID";
                        return(0);
                    }
                }
                catch (Exception ex)
                {
                    serviceException             = ex;
                    updateUserItem.UserItemRoles = context.Roles.Select(x => new SelectListItem {
                        Text = x.Name, Value = x.Id.ToString()
                    }).ToList();
                    if (ex.Message != null)
                    {
                        strErrorMessage = ex.Message;
                    }
                    else
                    {
                        strErrorMessage = ex.InnerException.Message;
                    }
                    scope.Dispose();
                    return(-1);
                }
            }
        }