private static void SeedAdministrator(IUserService userService) { Task.Run(async() => { string adminName = RoleType.Administrator.ToString(); UserEf adminUser = await userService.FindByNameAsync(adminName); if (adminUser is null) { adminUser = new UserEf() { UserName = adminName, Email = "*****@*****.**", EmailConfirmed = true, FirstName = "Mp3MusicZone", LastName = adminName, Birthdate = new DateTime(1990, 4, 16), Genre = GenreType.Male, }; await userService.CreateAsync(adminUser, "Test12"); await userService.AddToRoleAsync(adminUser, adminName); } }) .GetAwaiter() .GetResult(); }
public async Task <IActionResult> EditProfile(EditProfileViewModel model) { UserEf user = await this.userService.GetUserAsync(User); if (user is null) { return(RedirectToAction(nameof(HomeController.Index), "Home") .WithErrorMessage($"Unable to load user with ID '{this.userService.GetUserId(User)}'.")); } user.FirstName = model.FirstName; user.LastName = model.LastName; user.Genre = model.Genre; user.Birthdate = model.Birthdate; IdentityResult updateUserResult = await this.userService.UpdateAsync(user); if (!updateUserResult.Succeeded) { string errors = this.GetErrorsDescription(updateUserResult); return(View(model) .WithErrorMessage(errors)); } return(RedirectToAction(nameof(Profile)) .WithSuccessMessage("Your profile has been successfully updated.")); }
private async Task SendEmailConfirmationToken(UserEf user) { string code = await this.userService.GenerateEmailConfirmationTokenAsync(user); string callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme); await emailSender.SendEmailConfirmationAsync(user.Email, callbackUrl); }
private FilteredUser ConvertFrom_Entity_To_FilteredUser(UserEf entity, FilteredUser model) { var instance = model ?? new FilteredUser(); instance.Id = entity.Id; instance.Email = entity.Email; instance.FullName = $"{entity.Name} {entity.LastName}"; return(instance); }
private static UserAccount ConvertFrom_Entity_To_Model(UserEf entity, UserAccount model) { var instance = model ?? new UserAccount(); instance.Email = entity.Email; instance.FullName = $"{entity.Name} {entity.LastName}"; instance.Image = entity.ImagePath.ToImage(); return(instance); }
private static InvitationEmail ConvertFrom_UserEf_To_InvitationEmail(UserEf entity, InvitationEmail model) { var instance = model ?? new InvitationEmail(); instance.Email = entity.Email; instance.UserName = entity.Name; instance.Password = entity.Password; instance.Residential = entity.Residential?.Name; return(instance); }
public async Task <IActionResult> Register( RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; UserEf user = await this.userService.FindByEmailAsync(model.Email); if (user != null) { return(View(model) .WithErrorMessage($"E-mail address '{model.Email}' is already taken.")); } user = new UserEf() { UserName = model.Username, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, Genre = model.Genre, Birthdate = model.Birthdate }; IdentityResult createUserResult = await this.userService.CreateAsync(user, model.Password); IdentityResult addRoleResult = await this.userService.AddToRoleAsync( user, RoleType.RegularUser.ToString()); if (createUserResult.Succeeded && addRoleResult.Succeeded) { logger.LogInformation("User created a new account with password."); await this.SendEmailConfirmationToken(user); //await signInManager.SignInAsync(user, isPersistent: false); if (returnUrl is null) { return(View() .WithSuccessMessage($"The registration is successfull. Please, verify your e-mail address {model.Email} before proceeding.")); } return(this.RedirectToLocal(returnUrl)); } string errors = this.GetErrorsDescription(createUserResult); // If we got this far, something failed, redisplay form return(View(model) .WithErrorMessage(errors)); }
private static User ConvertFrom_Entity_To_Model(UserEf entity, User model) { var instance = model ?? new User(); instance.Id = entity.Id; instance.Name = entity.Name; instance.Email = entity.Email; instance.LastName = entity.LastName; instance.RoleNames = string.Join(", ", entity.UserRoles.Select(x => x.Role.Name).ToArray()); return(instance); }
private async Task SendForgotPasswordToken(UserEf user) { string code = await this.userService.GeneratePasswordResetTokenAsync(user); string callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme); callbackUrl += $"&email={user.Email}"; await emailSender.SendEmailAsync(user.Email, "Reset Password", $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>"); }
private UserLogin ConvertFrom_Entity_To_Model(UserEf entity, UserLogin model) { var instance = model ?? new UserLogin(); instance.Id = entity.Id; instance.Name = entity.Name; instance.Email = entity.Email; instance.LastName = entity.LastName; instance.Image = entity.ImagePath.ToImage(); instance.RoleIds = entity?.UserRoles.Select(x => x.RoleId).ToList(); return(instance); }
public async Task <IActionResult> ResendEmailConfirmation(string email) { UserEf user = await this.userService.FindByEmailAsync(email); if (user == null) { return(RedirectToAction(nameof(HomeController.Index), "Home") .WithErrorMessage($"Unable to find user with email {email}.")); } await this.SendEmailConfirmationToken(user); return(RedirectToAction(nameof(this.Login)) .WithSuccessMessage($"A verification link has been sent to email address {email}. Please verify your email.")); }
public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model) { UserEf user = await this.userService.FindByEmailAsync(model.Email); if (user == null || !(await this.userService.IsEmailConfirmedAsync(user))) { return(View() .WithErrorMessage($"Invalid Email address.")); } await SendForgotPasswordToken(user); return(View() .WithSuccessMessage("Please check your email to reset your password.")); }
private static UserToUpdate ConvertFrom_Entity_To_UserToUpdate(UserEf entity, UserToUpdate model) { var instance = model ?? new UserToUpdate(); instance.Id = entity.Id; instance.Name = entity.Name; instance.Email = entity.Email; instance.Password = entity.Password; instance.LastName = entity.LastName; instance.CellPhone = entity.CellPhone; instance.LandPhone = entity.LandPhone; instance.Roles = entity?.UserRoles.Select(x => x.RoleId).ToList(); return(instance); }
public async Task SendInvitationAsync(UserEf user) { var invitation = Mapper.Map <InvitationEmail>(user); invitation.Url = EmailConfiguration.Url; var residentialId = user.ResidentialId.Value; const string subjet = "Bienvenido a Smart Residential"; var htmlEmail = await CreateHtmlEmailAsync(residentialId, subjet); htmlEmail.Title = invitation.Residential; htmlEmail.Content = invitation.ToHtmlContent(ContentRootPath); Send(htmlEmail, user.Email); }
public async Task <IActionResult> ChangePassword() { UserEf user = await this.userService.GetUserAsync(User); if (user is null) { return(RedirectToAction(nameof(HomeController.Index), "Home") .WithErrorMessage($"Unable to load user with ID '{this.userService.GetUserId(User)}'.")); } ChangePasswordViewModel model = new ChangePasswordViewModel { StatusMessage = StatusMessage }; return(View(model)); }
private static UserLogin ConvertFrom_Entity_To_Model(UserEf entity, UserLogin model) { var instance = model ?? new UserLogin(); instance.Id = entity.Id; instance.Name = entity.Name; instance.Email = entity.Email; instance.LastName = entity.LastName; instance.CellPhone = entity.CellPhone; instance.LandPhone = entity.LandPhone; instance.ResidentialId = entity.ResidentialId; instance.Residential = entity.Residential?.Name; instance.RoleIds = entity.UserRoles.Select(x => x.Role.Id).ToList(); instance.Roles = entity.UserRoles.Select(x => x.Role?.Name).ToList(); return(instance); }
private static UserEf ConvertFrom_UserToAdd_To_Entity(UserToAdd model, UserEf entity) { var instance = entity ?? new UserEf(); instance.Name = model.Name.RemoveSpace(); instance.Email = model.Email.RemoveSpace(); instance.Password = model.Password.RemoveSpace(); instance.LastName = model.LastName.RemoveSpace(); instance.CellPhone = model.CellPhone.RemoveSpace(); instance.LandPhone = model.LandPhone.RemoveSpace(); instance.ResidentialId = model.ResidentialId; instance.UserRoles = model.Roles.Select(roleId => new UserRoleEf { RoleId = roleId }).ToList(); return(instance); }
public async Task Should_GetUserAsync_ResturnsALoginUserModelById() { //Arrange const int userId = 1; const string password = "******"; const string email = "*****@*****.**"; var userEntity = new UserEf { Id = userId, Email = email, Password = password }; var userModel = new UserLogin { Id = userId, Email = email }; _repositoryMock.Setup(x => x.GetUserAsync(userId)) .ReturnsAsync(userEntity); _mapperMock.Setup(x => x.Map <UserLogin>(userEntity)) .Returns(userModel); _manager = new UserLoginManager(_mapperMock.Object, _repositoryMock.Object); //Act var model = await _manager.GetUserAsync(userId); //Assert _repositoryMock.Verify(x => x.GetUserAsync(userId), Times.Once); _mapperMock.Verify(x => x.Map <UserLogin>(userEntity), Times.Once); Assert.NotNull(model.Email); Assert.Equal(userId, model.Id); Assert.Equal(email, model.Email); }
public async Task <IActionResult> EditProfile() { UserEf user = await this.userService.GetUserAsync(User); if (user is null) { return(RedirectToAction(nameof(HomeController.Index), "Home") .WithErrorMessage($"Unable to load user with ID '{this.userService.GetUserId(User)}'.")); } EditProfileViewModel model = new EditProfileViewModel() { FirstName = user.FirstName, LastName = user.LastName, Birthdate = user.Birthdate, Genre = user.Genre }; return(View(model)); }
public async Task <IActionResult> UploadProfilePicture(IFormFile file) { UserEf user = await this.userService.GetUserAsync(User); if (user is null) { return(RedirectToAction(nameof(HomeController.Index), "Home") .WithErrorMessage($"Unable to load user with ID '{this.userService.GetUserId(User)}'.")); } string messageType = string.Empty; string messageText = string.Empty; if (!file.IsImage() || file.Length > ProfileImageMaxLength) { messageType = ErrorsMessageType; messageText = $"Your submission should be a image file and no more than 5 MBs in size!"; } else { user.ProfileImage = file.ToByteArray(); IdentityResult result = await this.userService.UpdateAsync(user); if (result.Succeeded) { messageType = SuccessMessageType; messageText = "Profile Picture uploaded successfully."; } else { messageType = ErrorsMessageType; messageText = "We're sorry, something went wrong. Please try again later."; } } return(RedirectToAction(nameof(Profile)) .WithMessage(messageType, messageText)); }
public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; UserEf user = await this.userService.FindByNameAsync(model.Username); if (user != null) { bool isEmailConfirmed = await this.userService .IsEmailConfirmedAsync(user); if (!isEmailConfirmed) { return(View(model) .WithErrorMessage($"Please, confirm your email address, to activate your account. If you cannot find your confirmation email <a href=\"/account/resendemailconfirmation?email={user.Email}\">click here to resend it.</a>")); } } // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await this.signInService .PasswordSignInAsync( model.Username, model.Password, model.RememberMe, lockoutOnFailure : false); if (result.Succeeded) { logger.LogInformation("User logged in."); return(this.RedirectToLocal(returnUrl)); } // If we got this far, something failed, redisplay form return(View(model) .WithErrorMessage("Invalid login attempt.")); }
public async Task <IActionResult> ConfirmEmail(string userId, string code) { if (User.Identity.IsAuthenticated) { return(RedirectToAction(nameof(HomeController.Index), "Home") .WithErrorMessage("User already logged in.")); } if (userId == null || code == null) { return(RedirectToAction(nameof(HomeController.Index), "Home")); } UserEf user = await this.userService.FindByIdAsync(userId); if (user == null) { throw new ApplicationException($"Unable to load user with ID '{userId}'."); } if (user.EmailConfirmed) { return(RedirectToAction(nameof(HomeController.Index), "Home") .WithErrorMessage($"Email address {user.Email} is already confirmed.")); } IdentityResult result = await this.userService.ConfirmEmailAsync(user, code); if (!result.Succeeded) { return(RedirectToAction(nameof(this.Login)) .WithErrorMessage("Oops! Something went wrong. Please try again.")); } return(RedirectToAction(nameof(this.Login)) .WithSuccessMessage("Thank you for verifying your email. You can now log in.")); }
public async Task ExecuteAsync(OnStartupNullObject command) { string adminName = "Administrator"; UserEf adminUser = this.userService.FindByNameAsync(adminName).Result; if (adminUser is null) { adminUser = new UserEf() { UserName = adminName, Email = "*****@*****.**", EmailConfirmed = true, FirstName = "Mp3MusicZone", LastName = adminName, Birthdate = new DateTime(1990, 4, 16), Genre = GenreType.Male, }; await userService.CreateAsync(adminUser, "Test12"); await userService.AddToRoleAsync(adminUser, adminName); } }
public async Task <IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return(View(model)); } UserEf user = await this.userService.GetUserAsync(User); if (user is null) { return(RedirectToAction(nameof(HomeController.Index), "Home") .WithErrorMessage($"Unable to load user with ID '{this.userService.GetUserId(User)}'.")); } IdentityResult changePasswordResult = await this.userService .ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (!changePasswordResult.Succeeded) { string errors = this.GetErrorsDescription(changePasswordResult); return(View(model) .WithErrorMessage(errors)); } await signInService.SignInAsync(user, isPersistent : false); logger.LogInformation("User changed their password successfully."); StatusMessage = "Your password has been changed."; //this.TempData.AddSuccessMessage("Your password has been successfully changed."); return(RedirectToAction(nameof(Profile)) .WithSuccessMessage("Your password has been successfully changed.")); }
public async Task <IActionResult> ResetPassword(ResetPasswordViewModel model) { UserEf user = await this.userService.FindByEmailAsync(model.Email); if (user == null) { return(this.RedirectToAction(nameof(HomeController.Index), "Home") .WithErrorMessage("A valid email must be supplied for password reset.")); } IdentityResult result = await this.userService .ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return(RedirectToAction(nameof(Login)) .WithSuccessMessage("Your password has been reset successfully.")); } string errors = this.GetErrorsDescription(result); return(View() .WithErrorMessage(errors)); }