public async Task<JsonData> ChangePassword(ChangePasswordModel changePass)
        {
            try
            {
                var db = new DataContext();
                var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));
                userMan.UserValidator = new UserValidator<MyUser>(userMan)
                {
                    AllowOnlyAlphanumericUserNames =
                        false
                };

                var user = await userMan.FindByIdAsync(User.Identity.GetUserId());
                if (user == null) throw new Exception("please check your old password");

                var newPassword = changePass.NewPassword;
                var result = await userMan.RemovePasswordAsync(user.Id);
                if (!result.Succeeded) throw new Exception(string.Join(", ", result.Errors));
                var result2 = await userMan.AddPasswordAsync(user.Id, newPassword);
                if (!result2.Succeeded) throw new Exception(string.Join(", ", result2.Errors));
                return DataHelpers.ReturnJsonData(null, true, "Password changed successful");
            }
            catch (Exception e)
            {
                return DataHelpers.ExceptionProcessor(e);
            }
        }
        public async Task <IActionResult> Edit(string id, UserEditVm userEditVm)
        {
            if (id != userEditVm.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByIdAsync(userEditVm.Id);

                if (user == null)
                {
                    return(NotFound());
                }

                if (!string.IsNullOrWhiteSpace(userEditVm.Password))
                {
                    var removePassResult = await _userManager.RemovePasswordAsync(user);

                    if (!removePassResult.Succeeded)
                    {
                        foreach (var error in removePassResult.Errors)
                        {
                            ModelState.AddModelError("", error.Description);
                        }

                        return(View(userEditVm));
                    }

                    user.PasswordHash = _passwordHasher.HashPassword(user, userEditVm.Password);
                }

                user.UserName = userEditVm.UserName;

                var result = await _userManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    return(Redirect("/Panel"));
                }

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError("", error.Description);
                }

                return(View(userEditVm));
            }

            return(View(userEditVm));
        }
Exemplo n.º 3
0
        public async Task <(ApplicationUser, Error[])> UpdateAsync(EditUserViewModel viewModel)
        {
            var user = await userManager.FindByIdAsync(viewModel.Id).ConfigureAwait(false);

            if (user == null)
            {
                return(null, Error.Create(AccountServiceErrors.UserNotFound));
            }

            return(await accountDbContext.DoTransaction(async() =>
            {
                user.UserName = viewModel.Login;
                user.SecurityStamp = Guid.NewGuid().ToString();

                var updateResult = await userManager.UpdateAsync(user).ConfigureAwait(false);
                if (!updateResult.Succeeded)
                {
                    return (null, ToError(updateResult));
                }

                var removePasswordResult = await userManager.RemovePasswordAsync(user).ConfigureAwait(false);
                if (!removePasswordResult.Succeeded)
                {
                    return (null, ToError(removePasswordResult));
                }

                var addPasswordResult = await userManager.AddPasswordAsync(user, viewModel.Password).ConfigureAwait(false);
                if (!addPasswordResult.Succeeded)
                {
                    return (null, ToError(addPasswordResult));
                }

                if (!await userManager.IsInRoleAsync(user, viewModel.Role).ConfigureAwait(false))
                {
                    var roles = await userManager.GetRolesAsync(user).ConfigureAwait(false);
                    var removeRolesResult = await userManager.RemoveFromRolesAsync(user, roles).ConfigureAwait(false);
                    if (!removeRolesResult.Succeeded)
                    {
                        return (null, ToError(removeRolesResult));
                    }

                    var roleAssignResult = await userManager.AddToRoleAsync(user, viewModel.Role).ConfigureAwait(false);
                    if (!roleAssignResult.Succeeded)
                    {
                        return (null, ToError(roleAssignResult));
                    }
                }

                var createdUser = await FindUserByLoginAsync(viewModel.Login).ConfigureAwait(false);
                return (createdUser, Error.NoError);
            }).ConfigureAwait(false));
        }
Exemplo n.º 4
0
        public ActionResult Update(string id, [FromBody] UserDTO usuarioDTO, [FromHeader(Name = "Accept")] string mediaType)
        {
            ApplicationUser user = _userManager.GetUserAsync(HttpContext.User).Result;

            if (user.Id != id)
            {
                return(Forbid());
            }

            if (ModelState.IsValid)
            {
                user.FullName = usuarioDTO.Name;
                user.UserName = usuarioDTO.Email;
                user.Email    = usuarioDTO.Email;
                user.Slogan   = usuarioDTO.Slogan;

                var resultado = _userManager.UpdateAsync(user).Result;
                _userManager.RemovePasswordAsync(user);
                _userManager.AddPasswordAsync(user, usuarioDTO.Password);

                if (!resultado.Succeeded)
                {
                    List <string> erros = new List <string>();
                    foreach (var erro in resultado.Errors)
                    {
                        erros.Add(erro.Description);
                    }
                    return(UnprocessableEntity(erros));
                }
                else
                {
                    if (mediaType == CustomMediaType.Hateoas)
                    {
                        var userDTO = _mapper.Map <ApplicationUser, UserDTO>(user);

                        userDTO.Links.Add(new LinkDTO("_self", Url.Link("Update", new { id = userDTO.Id }), "PUT"));
                        userDTO.Links.Add(new LinkDTO("_get", Url.Link("GetUser", new { id = userDTO.Id }), "GET"));

                        return(Ok(userDTO));
                    }
                    else
                    {
                        var usersStandardDTO = _mapper.Map <ApplicationUser, UserStandardDTO>(user);
                        return(Ok(usersStandardDTO));
                    }
                }
            }
            else
            {
                return(UnprocessableEntity(ModelState));
            }
        }
        public async Task <ActionResult> SetNewPassword(SetNewPasswordModel model)
        {
            var answer = new SetNewPasswordModel
            {
                RequestId = model.RequestId
            };

            if (!ModelState.IsValid)
            {
                answer.Errors = ModelState.Values.SelectMany(state => state.Errors.Select(error => error.ErrorMessage)).ToArray();
                return(View(answer));
            }

            var userId = requestRepo.FindUserId(model.RequestId);

            if (userId == null)
            {
                answer.Errors    = new[] { "Запрос не найден" };
                answer.RequestId = null;
                return(View(answer));
            }

            var result = await userManager.RemovePasswordAsync(userId);

            if (!result.Succeeded)
            {
                answer.Errors = result.Errors.ToArray();
                return(View(answer));
            }

            result = await userManager.AddPasswordAsync(userId, model.NewPassword);

            if (!result.Succeeded)
            {
                answer.Errors = result.Errors.ToArray();
                return(View(answer));
            }
            metricSender.SendCount("restore_password.set_new_password");

            await requestRepo.DeleteRequest(model.RequestId);

            var user = await userManager.FindByIdAsync(userId);

            if (user == null)
            {
                answer.Errors = new[] { "Пользователь был удалён администраторами" };
                return(View(answer));
            }
            await AuthenticationManager.LoginAsync(HttpContext, user, false);

            return(RedirectToAction("Index", "Home"));
        }
Exemplo n.º 6
0
        public async Task SetPassword(int userId, UserPasswordSetModel model)
        {
            var user = await DbContext.Users.FindAsync(userId);

            var removeResult = await UserManager.RemovePasswordAsync(user);

            var addResult = await UserManager.AddPasswordAsync(user, model.Password);

            if (!removeResult.Succeeded || !addResult.Succeeded)
            {
                throw new RestaurantInternalServerErrorException("Sikertelen jelszó változtatás!");
            }
        }
        public async Task HandleAsync(UserChangePasswordCommand command)
        {
            var user = await _userManager.FindByIdAsync(command.Id);

            if (user == null)
            {
                throw new EntityNotFoundException();
            }

            await _userManager.RemovePasswordAsync(user);

            await _userManager.AddPasswordAsync(user, command.Password);
        }
Exemplo n.º 8
0
        public async Task <IActionResult> Edit(IdentityUser identityUser)
        {
            if (!AuthorizeManager.InAdminGroup(User.Identity.Name))
            {
                return(NotFound());
            }

            var user = _context.Users.FirstOrDefault(u => u.Id == identityUser.Id);

            // 令超級管理員不能被編輯
            if (user.Email == AuthorizeManager.SuperAdmin)
            {
                return(NotFound());
            }
            else
            {
                // 如果是特權用戶,則變更此特權用戶的郵件
                if (AuthorizeManager.InAuthorizedMember(user.Email))
                {
                    AuthorizeManager.UpdateAuthority("ModifyEmail", _context, user.Email, identityUser.Email);
                }

                user.Email    = identityUser.Email;
                user.UserName = identityUser.Email;
            }

            // 若沒先 RemovePassword 則 LOG 會出現內建的 Warning
            await _userManager.RemovePasswordAsync(user);

            await _userManager.AddPasswordAsync(user, identityUser.PasswordHash);

            _logger.LogInformation($"[{User.Identity.Name}]修改了[{user.Email}]的資料");

            // 返回之前的分頁
            int?TryGetPage = HttpContext.Session.GetInt32("returnPage");
            int page       = TryGetPage != null ? (int)TryGetPage : 1;

            return(RedirectToAction("Index", new { page }));
        }
Exemplo n.º 9
0
        public async Task RemovePasswordAsync()
        {
            var user   = UserManager.Users.FirstOrDefault(d => d.UserName != "");
            var result = await UserManager.RemovePasswordAsync(user);

            if (result.Errors != null)
            {
                foreach (var item in result.Errors)
                {
                    Debug.WriteLine(item);
                }
            }
        }
Exemplo n.º 10
0
        public async Task <IdentityResult> SetPassword(ApplicationUser user, string password)
        {
            if (await _userManager.HasPasswordAsync(user.Id))
            {
                await _userManager.RemovePasswordAsync(user.Id);
            }

            var addPwd = await _userManager.AddPasswordAsync(user.Id, password);

            await _userManager.UpdateAsync(user);

            return(addPwd);
        }
Exemplo n.º 11
0
        public async Task<ActionResult> ChangeCustomerPasswordAsync(ChangeCustomerPasswordViewModel ccpvm)
        {
            AppUser dbUsers = _context.Users.Where(u => u.Email == ccpvm.Email).FirstOrDefault();

            if (ModelState.IsValid == false)
            {
                return View(ccpvm);
            }

            AppUser userLoggedIn = await _userManager.FindByNameAsync(User.Identity.Name);

            var removepassword =  await _userManager.RemovePasswordAsync(dbUsers);
            var addpassword = await _userManager.AddPasswordAsync(dbUsers, ccpvm.NewCustomerPassword);

            if (addpassword.Succeeded)
            {
                return RedirectToAction(nameof(IndexCustomer));
            }

            else
                return View("Error", new String[] { "There was a problem updating the customer's password!" });
        }
Exemplo n.º 12
0
        public async Task <IHttpActionResult> PasswordReset(ResetPasswordBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            PasswordResetToken _token = await UnitOfWork.PasswordResetTokenStore.FindByToken(model.ResetToken);

            if (_token == null)
            {
                return(BadRequest("Invalid Token"));
            }
            if (_token.Expires < DateTime.Now)
            {
                return(BadRequest("Expired Token"));
            }
            if (_token.Used.HasValue)
            {
                return(BadRequest("Token Already Used"));
            }
            ISS.Authentication.Domain.Models.User _user = await UnitOfWork.UserStore.FindByIdAsync(_token.UserId);

            if (_user == null)
            {
                return(BadRequest("User not Found"));
            }
            IdentityResult _result = await UserManager.RemovePasswordAsync(_user.Id);

            _result = await UserManager.AddPasswordAsync(_user.Id, model.NewPassword);

            _token.Used = DateTime.Now;
            if (_result.Succeeded)
            {
                await UnitOfWork.PasswordResetTokenStore.UpdateAsync(_token);

                return(Ok());
            }
            else
            {
                string _errors = "";
                foreach (string _error in _result.Errors)
                {
                    if (_errors != "")
                    {
                        _errors += "; ";
                    }
                    _errors += _error;
                }
                return(BadRequest(_errors));
            }
        }
Exemplo n.º 13
0
        public async Task <IActionResult> ResetPasswordAsync(
            string code,
            string email    = "*****@*****.**",
            string password = "******",
            CancellationToken cancellationToken = default
            )
        {
            User user = await UserManager.FindByEmailAsync(email);

            if (user == null)
            {
                ModelState.AddModelError(string.Empty, "کاربر نا معتبر");
                return(View());
            }

            user.PasswordHash = UserManager.PasswordHasher.HashPassword(user, password);
            var resultt = await UserManager.UpdateAsync(user);

            if (!resultt.Succeeded)
            {
            }
            var token = await UserManager.GeneratePasswordResetTokenAsync(user);

            var resulttt = await UserManager.ResetPasswordAsync(user, token, password);

            var resultttt = await UserManager.ChangePasswordAsync(user, password, password);

            await UserManager.RemovePasswordAsync(user);

            await UserManager.AddPasswordAsync(user, password);

            if (!await UserManager.CheckPasswordAsync(user, password))
            {
                ViewBag.Notification = "Incorrect password ..";
                return(View());
            }

            IdentityResult result = await UserManager.ResetPasswordAsync(user, code, password);

            if (result.Succeeded)
            {
                return(RedirectToAction(nameof(ResetPassword)));
            }

            foreach (IdentityError error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            return(View());
        }
        public async Task <IActionResult> Put(string id, [FromBody] UserRequestModel model)
        {
            if (ModelState.IsValid && !string.IsNullOrEmpty(id))
            {
                var user = await _userManager.FindByIdAsync(id);

                if (user == null)
                {
                    return(BadRequest());
                }

                if (model.CustomerId != null)
                {
                    var customer = await _databaseContext.Customers.FirstOrDefaultAsync(e => e.Id == model.CustomerId);

                    if (customer != null)
                    {
                        user.Customer = customer;
                    }
                }
                else
                {
                    user.Customer = null;
                }

                var userRoles = await _userManager.GetRolesAsync(user);

                var addedRoles   = model.Roles.Except(userRoles).ToList();
                var removedRoles = userRoles.Except(model.Roles).ToList();

                await _userManager.AddToRolesAsync(user, addedRoles);

                await _userManager.RemoveFromRolesAsync(user, removedRoles);

                if (!string.IsNullOrEmpty(model.Password))
                {
                    var passwordRemove = await _userManager.RemovePasswordAsync(user);

                    if (passwordRemove.Succeeded)
                    {
                        await _userManager.AddPasswordAsync(user, model.Password);
                    }
                }

                await _databaseContext.SaveChangesAsync();

                return(Ok());
            }

            return(BadRequest()); //TODO Specify errors
        }
Exemplo n.º 15
0
    public async Task <bool> UpdateUser(UpdateUserModel model)
    {
        //var user = _context.Users.Include(q=>q.)
        var user = _context.Users.FirstOrDefault(q => q.UserName == model.Username);

        if (user == null)
        {
            throw new Exception("User not found.");
        }
        user.Name        = model.Name;
        user.ProfileId   = model.ProfileId;
        user.UpdatedAt   = DateTime.UtcNow;
        user.PhoneNumber = model.PhoneNumber;
        user.Email       = model.Email;

        var res = await _userManager.UpdateAsync(user);

        if (!res.Succeeded)
        {
            throw new Exception(ExceptionHelper.ProcessException(res));
        }

        //Update user roles
        var profile = await _context.UserProfiles.FindAsync(model.ProfileId);

        if (profile != null)
        {
            var oldRoles = await _userManager.GetRolesAsync(user);

            var clearRoles = await _userManager.RemoveFromRolesAsync(user, oldRoles);

            if (clearRoles.Succeeded)
            {
                var privileges = profile.Privileges?.Split(',').ToList().Select(q => q.Trim());
                await _userManager.AddToRolesAsync(user, privileges);
            }
        }

        //Change Password
        if (!string.IsNullOrEmpty(model.Password))
        {
            var clearPassword = await _userManager.RemovePasswordAsync(user);

            if (clearPassword.Succeeded)
            {
                await _userManager.AddPasswordAsync(user, model.Password);
            }
        }

        return(true);
    }
Exemplo n.º 16
0
        public async Task <IdentityResult> UpdateUser(string email, string newPass)
        {
            IdentityUser user = await _userManager.FindByNameAsync(email);

            if (user == null)
            {
                return(new IdentityResult("User chưa có"));
            }
            var result = await _userManager.RemovePasswordAsync(user.Id);

            result = await _userManager.AddPasswordAsync(user.Id, newPass);

            return(result);
        }
        }//end ApproveVerificationToken

        public async Task <int> ResetPassword(ApplicationUser _User)
        {
            if (_User != null)
            {
                var setting           = _db.Setting.FirstOrDefault();
                var isUserName_Number = double.TryParse(_User.UserName, out double r) ? r : 0;

                var token = await GeneratePhoneNumberTokenAsync(_User);

                if (token != null)
                {
                    // string message = $"کد بازیابی کلمه عبور: {token}";
                    string message = token;

                    if (isUserName_Number > 0)
                    {
                        string mobileNumber = _User.UserName;
                        var    result       = SmsIrService.SendVerificationCode(setting.SMSApiAddress, setting.SMSUsername, message, mobileNumber);
                    }
                    else
                    {
                        EmailViewModel emailViewModel = new EmailViewModel()
                        {
                            Subject       = "ایمیل تاییدیه ثبت نام",
                            ReceiverEmail = _User.UserName,
                            Content       = message,
                            SenderEmail   = setting.AdminEmail,
                            Password      = setting.AdminEmailPassword
                        };
                        var port = int.TryParse(setting.EmailPort, out int rr) ? rr : 587;
                        EmailService.EmailService.Send(emailViewModel, setting.EmailServiceProvider, port);
                    }

                    var hasPassword = await _userManager.HasPasswordAsync(_User);

                    if (hasPassword == true)
                    {
                        var removePassword = await _userManager.RemovePasswordAsync(_User);
                    }
                    return(1);
                }


                return(-2);
            }
            else
            {
                return(0);
            }
        }
Exemplo n.º 18
0
        public async Task UpdateAsync(AppUserViewModel userVM)
        {
            var user = await _userManager.FindByIdAsync(userVM.Id.ToString());

            //AppUserRole appUserRole = new AppUserRole();

            var roles = await _userManager.GetRolesAsync(user);

            var roleVM = userVM.Roles.ToList();

            foreach (var item in roles)
            {
                // kiểm tra roles xem có tồn tại trong roles mới hay ko nếu ko (false) thì xóa
                if (roleVM.Contains(item) == false)
                {
                    object[] Params =
                    {
                        new SqlParameter("userId",   userVM.Id),
                        new SqlParameter("nameRole", item)
                    };
                    int res = db.Database.ExecuteSqlCommand("tbl_UserAppRoles_Delete_Single @userId,@nameRole", Params);
                }
            }
            // add roles new for user
            var rs = await _userManager.AddToRolesAsync(user, roleVM.Except(roles));

            if (rs.Succeeded)
            {
                if (user.PasswordHash != userVM.PasswordHash)
                {
                    //user.PasswordHash = userVM.PasswordHash;
                    var response = await _userManager.RemovePasswordAsync(user);

                    if (response.Succeeded)
                    {
                        var x = await _userManager.AddPasswordAsync(user, userVM.PasswordHash);
                    }
                }
                user.FullName     = userVM.FullName;
                user.Email        = userVM.Email;
                user.DateModified = DateTime.Now;
                user.PhoneNumber  = userVM.PhoneNumber;
                user.Status       = userVM.Status;
                // update user
                await _userManager.UpdateAsync(user);
            }


            //throw new NotImplementedException();
        }
Exemplo n.º 19
0
        public async Task <bool> SaveChangePassword(string ID, string datacurrent, string data)
        {
            var getuser = await _userManager.FindByIdAsync(ID);

            await _userManager.RemovePasswordAsync(getuser);

            var result = await _userManager.AddPasswordAsync(getuser, data);

            if (result.Succeeded)
            {
                return(true);
            }
            return(false);
        }
Exemplo n.º 20
0
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            // Something failed, redisplay form
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // Check if the user exists in the data store
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user != null)
            {
                var password = PasswordUtil.Password + GenerateNumber.Generate().ToString();
                await _userManager.RemovePasswordAsync(user);

                await _userManager.AddPasswordAsync(user, password);

                user.EmailConfirmed = false;
                await _userManager.UpdateAsync(user);

                var mensaje = "Recuperar contraseña"
                              + "\n \n Hola Señor(a): " + user.Name + " " + user.LastName
                              + "\n \n Le informamos que se ha reseteado su contraseña."
                              + "\n \n Nuevas credenciales de ingreso al sistema."
                              + "\n \n Usuario:  " + user.Email
                              + "\n \n Contraseña temporal: " + password
                              + "\n \n Click en el siguiente enlace para acceder al sistema" + "\n \n"
                              + Configuration.GetSection("EmailLink").Value
                              + Configuration.GetSection("EmailFooter").Value;

                Mail mail = new Mail
                {
                    Body = mensaje
                    ,
                    EmailTo = user.Email
                    ,
                    NameTo = "Name To"
                    ,
                    Subject = "Recuperar contraseña",
                };

                //execute the method Send Mail or SendMailAsync
                var a = await Emails.SendEmailAsync(mail);

                return(RedirectToAction(nameof(ForgotPasswordConfirmation)));
            }
            ModelState.AddModelError(string.Empty, "El correo electrónico ingresado no existe.");
            return(View(model));
        }
Exemplo n.º 21
0
        public async Task <IActionResult> ResetPassword([FromBody] ResetPasswordModel model)
        {
            var user = await _userManager.FindByIdAsync(model.Id);

            var result = await _userManager.RemovePasswordAsync(user);

            if (result.Succeeded)
            {
                var setPasswordResult = await _userManager.AddPasswordAsync(user, model.Password);

                return(Ok(setPasswordResult));
            }
            return(Ok(result));
        }
        public async Task <IActionResult> OnPostAsync(string code)
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }
            var user = _db.Users.Where(u => u.UserName.Equals(Input.UserName)).Single();
            //var user = await _userManager.FindByEmailAsync(Input.Email);
            await _userManager.RemovePasswordAsync(user);

            await _userManager.AddPasswordAsync(user, Input.ConfirmPassword);

            return(Page());
        }
Exemplo n.º 23
0
        public async Task <IUser> UpdateAsync(string id, UserValues values)
        {
            Guard.NotNullOrEmpty(id, nameof(id));
            Guard.NotNull(values, nameof(values));

            var user = await GetUserAsync(id);

            var oldUser = await ResolveAsync(user);

            if (!string.IsNullOrWhiteSpace(values.Email) && values.Email != user.Email)
            {
                await userManager.SetEmailAsync(user, values.Email).Throw(log);

                await userManager.SetUserNameAsync(user, values.Email).Throw(log);
            }

            await userManager.SyncClaims(user, values).Throw(log);

            if (!string.IsNullOrWhiteSpace(values.Password))
            {
                if (await userManager.HasPasswordAsync(user))
                {
                    await userManager.RemovePasswordAsync(user).Throw(log);
                }

                await userManager.AddPasswordAsync(user, values.Password).Throw(log);
            }

            if (!string.IsNullOrWhiteSpace(values.Role) && !await userManager.IsInRoleAsync(user, values.Role))
            {
                await userManager.AddToRoleAsync(user, values.Role).Throw(log);
            }

            var resolved = await ResolveAsync(user);

            foreach (var @events in userEvents)
            {
                @events.OnUserUpdated(resolved);
            }

            if (HasConsentGiven(values, oldUser))
            {
                foreach (var @events in userEvents)
                {
                    @events.OnConsentGiven(resolved);
                }
            }

            return(resolved);
        }
Exemplo n.º 24
0
        public ActionResult Atualizar(string id, [FromBody] UsuarioDTO usuarioDTO, [FromHeader(Name = "Accept")] string mediaType)
        {
            ApplicationUser usuario = _userInManager.GetUserAsync(HttpContext.User).Result;

            if (usuario.Id != id)
            {
                return(Forbid());
            }

            if (ModelState.IsValid)
            {
                usuario.FullName = usuarioDTO.Nome;
                usuario.UserName = usuarioDTO.Email;
                usuario.Email    = usuarioDTO.Email;
                usuario.Slogan   = usuarioDTO.Slogan;
                var resultado = _userInManager.UpdateAsync(usuario).Result;
                _userInManager.RemovePasswordAsync(usuario);
                _userInManager.AddPasswordAsync(usuario, usuarioDTO.Senha);

                if (!resultado.Succeeded)
                {
                    List <string> erros = new List <string>();
                    foreach (var error in resultado.Errors)
                    {
                        erros.Add(error.Description);
                    }
                    return(UnprocessableEntity(erros));
                }
                else
                {
                    if (mediaType == CustomMediaTypes.Hateoas)
                    {
                        var usuarioDTODB = _mapper.Map <ApplicationUser, UsuarioDTO>(usuario);
                        usuarioDTODB.Links.Add(new v1.Models.DTO.LinkDTO("self", Url.Link("UsuaripAtualizar", new { id = usuarioDTODB.Id }), "PUT"));
                        usuarioDTODB.Links.Add(new v1.Models.DTO.LinkDTO("obterUsuario", Url.Link("UsuarioObter", new { id = usuarioDTODB.Id }), "GET"));
                        return(Ok(usuarioDTODB));
                    }
                    else
                    {
                        var usuarioresult = _mapper.Map <ApplicationUser, UsuarioDTOSemHyperLink>(usuario);
                        return(Ok(usuarioresult));
                    }
                }
            }
            else
            {
                return(UnprocessableEntity());
            }
        }
Exemplo n.º 25
0
        public async Task Initialize()
        {
            try
            {
                //Create the Administartor Role
                string administratorRoleName = "Administrator";
                bool   adminRoleExists       = _roleManager.RoleExistsAsync("Administrator").Result;
                if (!adminRoleExists)
                {
                    Global.Logger.Information("Adding Administrator role");
                    var resultRoleManager = _roleManager.CreateAsync(new IdentityRole()
                    {
                        Name           = administratorRoleName,
                        NormalizedName = administratorRoleName.ToUpper()
                    }).Result;
                }

                //Create the default Admin account and apply the Administrator role
                string userName     = Global.Configuration.SystemOptions.DefaultUserName;
                string userEmail    = Global.Configuration.SystemOptions.DefaultUserEmail;
                string userPassword = Global.Configuration.SystemOptions.DefaultUserPassword;

                ApplicationUser user = _userManager.FindByEmailAsync(userEmail).Result;

                if (user == null)
                {
                    Global.Logger.Information("Adding user " + userEmail);
                    //Like on registration UserName is userEmail
                    var userCreated = new ApplicationUser
                    {
                        UserName       = userEmail,
                        Email          = userEmail,
                        EmailConfirmed = true,
                        AccountEnabled = true
                    };
                    var resultCreateAsync    = _userManager.CreateAsync(userCreated, userPassword).Result;
                    var resultAddToRoleAsync = _userManager.AddToRoleAsync(userCreated, administratorRoleName.ToUpper()).Result;
                }
                else
                {
                    var resultDeletePassword = _userManager.RemovePasswordAsync(user).Result;
                    var resultResetPassword  = _userManager.AddPasswordAsync(user, userPassword).Result;
                }
            }
            catch (Exception e)
            {
                Global.Logger.Error("Cant update admin user - Error: " + e);
            }
        }
Exemplo n.º 26
0
        public async Task <IUser> UpdateAsync(string id, UserValues values, bool silent = false,
                                              CancellationToken ct = default)
        {
            Guard.NotNullOrEmpty(id);
            Guard.NotNull(values);

            var user = await GetUserAsync(id);

            var oldUser = await ResolveAsync(user);

            if (!string.IsNullOrWhiteSpace(values.Email) && values.Email != user.Email)
            {
                await userManager.SetEmailAsync(user, values.Email).Throw(log);

                await userManager.SetUserNameAsync(user, values.Email).Throw(log);
            }

            await userManager.SyncClaims(user, values).Throw(log);

            if (!string.IsNullOrWhiteSpace(values.Password))
            {
                if (await userManager.HasPasswordAsync(user))
                {
                    await userManager.RemovePasswordAsync(user).Throw(log);
                }

                await userManager.AddPasswordAsync(user, values.Password).Throw(log);
            }

            var resolved = await ResolveAsync(user);

            if (!silent)
            {
                foreach (var @events in userEvents)
                {
                    await @events.OnUserUpdatedAsync(resolved, oldUser);
                }

                if (HasConsentGiven(values, oldUser))
                {
                    foreach (var @events in userEvents)
                    {
                        await @events.OnConsentGivenAsync(resolved);
                    }
                }
            }

            return(resolved);
        }
Exemplo n.º 27
0
        public async Task <IActionResult> ResetPassword([FromBody] int id)
        {
            var user = await _context.Users.SingleAsync(x => x.Id == id);

            if (User.Identity.Name.ToUpper() == "SYSTEMADMIN")
            {
                await _userManager.RemovePasswordAsync(user);

                await _userManager.AddPasswordAsync(user, "password");

                return(Ok());
            }

            return(BadRequest("You cant change someone elses password"));
        }
Exemplo n.º 28
0
        public async Task CambiarContraseña(UserInfo userInfo)
        {
            ApplicationUser user = await _context.Users.SingleAsync(w => w.UserName == userInfo.username);

            try
            {
                await _userManager.RemovePasswordAsync(user);

                await _userManager.AddPasswordAsync(user, userInfo.Password);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Exemplo n.º 29
0
        public async Task <IActionResult> ChangePassword(ChangePasswordViewModel changePassword)
        {
            var user = await userManger.GetUserAsync(User);

            var passwordHash = userManger.PasswordHasher.HashPassword(user, changePassword.Password);
            var result       = await userManger.RemovePasswordAsync(user);

            if (result.Succeeded)
            {
                await userManger.AddPasswordAsync(user, changePassword.Password);

                return(RedirectToAction("Index", "Home"));
            }
            return(View());
        }
Exemplo n.º 30
0
        public async Task <ActionResult> ChangeDetailsPartial(UserViewModel userModel)
        {
            var user = await userManager.FindByIdAsync(userModel.UserId);

            if (user == null)
            {
                AuthenticationManager.Logout(HttpContext);
                return(RedirectToAction("Index", "Login"));
            }
            var nameChanged = user.UserName != userModel.Name;

            if (nameChanged && await userManager.FindByNameAsync(userModel.Name) != null)
            {
                return(RedirectToAction("Manage", new { Message = ManageMessageId.Error }));
            }
            user.UserName  = userModel.Name;
            user.GroupName = userModel.GroupName;
            user.FirstName = userModel.FirstName;
            user.LastName  = userModel.LastName;
            user.Email     = userModel.Email;
            user.LastEdit  = DateTime.Now;
            if (!string.IsNullOrEmpty(userModel.Password))
            {
                await userManager.RemovePasswordAsync(user.Id);

                await userManager.AddPasswordAsync(user.Id, userModel.Password);
            }
            await userManager.UpdateAsync(user);

            if (nameChanged)
            {
                AuthenticationManager.Logout(HttpContext);
                return(RedirectToAction("Index", "Login"));
            }
            return(RedirectToAction("Manage"));
        }
Exemplo n.º 31
0
        public async Task <bool> ResetPasswordAsync(string username, string password)
        {
            var user = await _userManager.FindByNameAsync(username);

            await _userManager.RemovePasswordAsync(user);

            var result = await _userManager.AddPasswordAsync(user, password);

            foreach (var error in result.Errors)
            {
                await _bus.RaiseEvent(new DomainNotification(result.ToString(), error.Description));
            }

            return(result.Succeeded);
        }
Exemplo n.º 32
0
        public async Task<WikiDownUser> Save(IPrincipal principal, UserManager<WikiDownUser> userManager)
        {
            var user = await userManager.FindByNameAsync(this.UserName);

            var roles = this.GetRoles(principal, user);

            if (user != null)
            {
                if (user.UserName == principal.Identity.Name)
                {
                    var userAccessLevel = ArticleAccessHelper.GetAccessLevel(user.Roles);
                    if (userAccessLevel < ArticleAccessLevel.Admin)
                    {
                        throw new HttpResponseException(HttpStatusCode.BadRequest);
                    }
                }

                user.SetRoles(roles);
                user.SetDisplayName(this.DisplayName);
                user.SetEmail(this.Email);

                if (!string.IsNullOrWhiteSpace(this.Password))
                {
                    await userManager.RemovePasswordAsync(user.Id);
                    await userManager.AddPasswordAsync(user.Id, this.Password);
                }

                await userManager.UpdateAsync(user);

                WikiDownUserCacheHelper.Clear(user.UserName);
            }
            else
            {
                user = new WikiDownUser(this.UserName) { Roles = roles };
                user.SetDisplayName(this.DisplayName);
                user.SetEmail(this.Email);

                await userManager.CreateAsync(user, this.Password);
            }

            return user;
        }
Exemplo n.º 33
0
        public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordModel model)
        {
              
            if (ModelState.IsValid)
            {
                
                // Fetch userID by email
                DBservices dbs = new DBservices();
                dbs = dbs.ReadFromDataBase(27, model.EmailAddress);
                string userId = dbs.dt.Rows[0].ItemArray[0].ToString();
                string userName = dbs.dt.Rows[0].ItemArray[1].ToString();
                string userFname = dbs.dt.Rows[0].ItemArray[2].ToString();
                
                // Generate an 8th digit long password
                var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
                var stringChars = new char[8];
                var random = new Random();
                for (int i = 0; i < stringChars.Length; i++)
                {
                    stringChars[i] = chars[random.Next(chars.Length)];
                }
                var randomPassword = new String(stringChars);
                UserManager<IdentityUser> UserManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>());
                IdentityResult resultRem = await UserManager.RemovePasswordAsync(userId);
                IdentityResult resultAdd = await UserManager.AddPasswordAsync(userId, randomPassword);

                //Send a notification to the user

                MailMessage mail = new MailMessage();
                StreamReader reader = new StreamReader(HttpContext.Current.Server.MapPath("~/Models/mailTemplates/forgotPasswordTemplate.html"));
                string readFile = reader.ReadToEnd();
                string StrContent = readFile;
                
                StrContent = StrContent.Replace("[FirstName]", userFname);
                StrContent = StrContent.Replace("[UserName]", userName);
                StrContent = StrContent.Replace("[Password]", randomPassword);
                
                mail.IsBodyHtml = true;
                mail.To.Add(model.EmailAddress);
                mail.Subject = "רוכבים לעבודה, איפוס סיסמא";                
                mail.Body = StrContent.ToString();
                mail.IsBodyHtml = true;
                SmtpClient smtp = new SmtpClient();
                smtp.Send(mail);

            }

            return Ok();

        }
 public async Task<JsonData> Reset(UserViewModel model)
 {
     try
     {
         var db = new DataContext();
         var userMan = new UserManager<MyUser>(new UserStore<MyUser>(db));
         userMan.UserValidator = new UserValidator<MyUser>(userMan)
         {
             AllowOnlyAlphanumericUserNames =
                 false
         };
         var user = await userMan.FindByEmailAsync(model.Email);
         if (user == null) throw new Exception("please check the email address");
         //todo: generate a unique password and email it to the user
         var newPassword = user.FullName.Substring(2, 3) + user.PasswordHash.Substring(0, 5);
         var result = await userMan.RemovePasswordAsync(user.Id);
         if (!result.Succeeded) throw new Exception(string.Join(", ", result.Errors));
         var result2 = await userMan.AddPasswordAsync(user.Id, newPassword);
         if (!result2.Succeeded) throw new Exception(string.Join(", ", result2.Errors));
         //todo: Email the new password to the user
         return DataHelpers.ReturnJsonData(null, true, "A new password has been emailed to your email address");
     }
     catch (Exception e)
     {
         return DataHelpers.ExceptionProcessor(e);
     }
 }