protected override IdentityUserLogin <string> CreateUserLogin(UnravelTravelUser user, UserLoginInfo login) => new IdentityUserLogin <string> { UserId = user.Id, ProviderKey = login.ProviderKey, LoginProvider = login.LoginProvider, ProviderDisplayName = login.ProviderDisplayName, };
protected override IdentityUserClaim <string> CreateUserClaim(UnravelTravelUser user, Claim claim) { var identityUserClaim = new IdentityUserClaim <string> { UserId = user.Id }; identityUserClaim.InitializeFromClaim(claim); return(identityUserClaim); }
public async Task AssignShoppingCartsUserIdThrowsNullReferenceExceptionIfNoShoppingCartForThisUser() { var user = new UnravelTravelUser { Id = this.secondTestUserId, UserName = SecondTestUsername, }; await this.DbContext.SaveChangesAsync(); var exception = await Assert.ThrowsAsync <NullReferenceException>(() => this.ShoppingCartsServiceMock.AssignShoppingCartsUserId(user)); Assert.Equal(string.Format(ServicesDataConstants.NullReferenceShoppingCartForUser, user.Id, user.UserName), exception.Message); }
// TODO: this is stupid but db does not store userId for each shopping cart find out why! public async Task AssignShoppingCartsUserId(UnravelTravelUser user) { var shoppingCart = await this.shoppingCartsRepository.All() .FirstOrDefaultAsync(sc => sc.User.Id == user.Id); if (shoppingCart == null) { throw new NullReferenceException(string.Format(ServicesDataConstants.NullReferenceShoppingCartForUser, user.Id, user.UserName)); } shoppingCart.UserId = user.Id; this.shoppingCartsRepository.Update(shoppingCart); await this.shoppingCartActivitiesRepository.SaveChangesAsync(); }
protected override IdentityUserToken <string> CreateUserToken( UnravelTravelUser user, string loginProvider, string name, string value) { var token = new IdentityUserToken <string> { UserId = user.Id, LoginProvider = loginProvider, Name = name, Value = value, }; return(token); }
private async Task LoadSharedKeyAndQrCodeUriAsync(UnravelTravelUser user) { // Load the authenticator key & QR code URI to display on the form var unformattedKey = await this.userManager.GetAuthenticatorKeyAsync(user); if (string.IsNullOrEmpty(unformattedKey)) { await this.userManager.ResetAuthenticatorKeyAsync(user); unformattedKey = await this.userManager.GetAuthenticatorKeyAsync(user); } this.SharedKey = this.FormatKey(unformattedKey); var email = await this.userManager.GetEmailAsync(user); this.AuthenticatorUri = this.GenerateQrCodeUri(email, unformattedKey); }
private static async Task SeedUserInRoles(UserManager <UnravelTravelUser> userManager, IShoppingCartsService shoppingCartsService) { if (!userManager.Users.Any()) { var user = new UnravelTravelUser { UserName = GlobalConstants.AdministratorUsername, Email = GlobalConstants.AdministratorEmail, FullName = GlobalConstants.AdministratorFullName, ShoppingCart = new ShoppingCart(), }; var result = await userManager.CreateAsync(user, GlobalConstants.AdministratorPassword); if (result.Succeeded) { await userManager.AddToRoleAsync(user, GlobalConstants.AdministratorRoleName); await shoppingCartsService.AssignShoppingCartsUserId(user); } } }
protected override IdentityUserRole <string> CreateUserRole(UnravelTravelUser user, ApplicationRole role) { return(new IdentityUserRole <string> { RoleId = role.Id, UserId = user.Id }); }
public async Task <ReservationDetailsViewModel> BookAsync(int restaurantId, string userIdentifier, ReservationCreateInputModel reservationCreateInputModel) { // If identifier is email the user is guest var isGuest = Regex.IsMatch(userIdentifier, ServicesDataConstants.EmailRegex); UnravelTravelUser user = null; if (!isGuest) { user = await this.usersRepository.All().FirstOrDefaultAsync(u => u.UserName == userIdentifier); if (user == null) { throw new NullReferenceException(string.Format(ServicesDataConstants.NullReferenceUsername, userIdentifier)); } } var restaurant = await this.restaurantsRepository.All().FirstOrDefaultAsync(r => r.Id == restaurantId); if (restaurant == null) { throw new NullReferenceException(string.Format(ServicesDataConstants.NullReferenceRestaurantId, restaurantId)); } Reservation reservation = null; if (!isGuest) { reservation = await this.reservationsRepository.All() .FirstOrDefaultAsync(r => r.User == user && r.Restaurant == restaurant && r.Date == reservationCreateInputModel.Date); if (reservation != null) { reservation.PeopleCount += reservationCreateInputModel.PeopleCount; this.reservationsRepository.Update(reservation); } } if (reservation == null) { // var utcReservationDate = reservationCreateInputModel.Date.GetUtcDate( // restaurant.Destination.Name, // restaurant.Destination.Country.Name); var utcReservationDate = reservationCreateInputModel.Date.CalculateUtcDateTime(restaurant.Destination.UtcRawOffset); reservation = new Reservation { UserId = user == null ? null : user.Id, Restaurant = restaurant, Date = utcReservationDate, // Save UTC date to Db PeopleCount = reservationCreateInputModel.PeopleCount, }; this.reservationsRepository.Add(reservation); await this.reservationsRepository.SaveChangesAsync(); } var reservationDetailsViewModel = AutoMap.Mapper.Map <ReservationDetailsViewModel>(reservation); var emailContent = await this.GenerateEmailContent(reservationDetailsViewModel); await this.emailSender.SendEmailAsync( user != null?user.Email : userIdentifier, ServicesDataConstants.BookingEmailSubject, emailContent); return(reservationDetailsViewModel); }
public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? this.Url.Content("~/"); // Get the information about the user from the external login provider var info = await this.signInManager.GetExternalLoginInfoAsync(); if (info == null) { this.ErrorMessage = "Error loading external login information during confirmation."; return(this.RedirectToPage("./Login", new { ReturnUrl = returnUrl })); } if (this.ModelState.IsValid) { var nameWithoutWhiteSpaces = info.Principal.Identity.Name.RemoveWhiteSpaces(); var user = new UnravelTravelUser { UserName = nameWithoutWhiteSpaces, Email = this.Input.Email, ShoppingCart = new ShoppingCart(), }; // For validating unique email IdentityResult result = null; IdentityError[] customErrors = null; try { result = await this.userManager.CreateAsync(user); } catch (DbUpdateException ex) { result = new IdentityResult(); if (ex.InnerException.Message.Contains("IX_AspNetUsers_Email")) { var exceptionMessage = $"User with email {user.Email} already exists. Please login and navigate to Account External Logins Add another service."; customErrors = new[] { new IdentityError { Code = string.Empty, Description = exceptionMessage }, }; } } if (result.Succeeded) { result = await this.userManager.AddLoginAsync(user, info); if (result.Succeeded) { await this.userManager.AddToRoleAsync(user, GlobalConstants.UserRoleName); await this.shoppingCartsService.AssignShoppingCartsUserId(user); await this.signInManager.SignInAsync(user, isPersistent : false); this.logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); await this.StoreGuestShoppingCartIfAny(info.Principal.Identity.Name.RemoveWhiteSpaces()); return(this.LocalRedirect(returnUrl)); } } foreach (var error in result.Errors.Concat(customErrors)) { this.ModelState.AddModelError(string.Empty, error.Description); } } this.LoginProvider = info.LoginProvider; this.ReturnUrl = returnUrl; return(this.Page()); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? this.Url.Content("~/"); if (this.ModelState.IsValid) { var user = new UnravelTravelUser { UserName = this.Input.UserName, FullName = this.Input.FullName, Email = this.Input.Email, ShoppingCart = new ShoppingCart(), }; // For validating unique email IdentityResult result = null; IdentityError[] customErrors = null; try { result = await this.userManager.CreateAsync(user, this.Input.Password); } catch (DbUpdateException ex) { result = new IdentityResult(); if (ex.InnerException.Message.Contains("IX_AspNetUsers_Email")) { var exceptionMessage = $"User with email {user.Email} already exists."; customErrors = new[] { new IdentityError { Code = string.Empty, Description = exceptionMessage }, }; } } if (result.Succeeded) { this.logger.LogInformation("User created a new account with password."); await this.userManager.AddToRoleAsync(user, GlobalConstants.UserRoleName); await this.shoppingCartsService.AssignShoppingCartsUserId(user); var code = await this.userManager.GenerateEmailConfirmationTokenAsync(user); var callbackUrl = this.Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { userId = user.Id, code = code }, protocol: this.Request.Scheme); var emailContent = callbackUrl.GetConfirmationEmailContent(); await this.emailSender.SendEmailAsync( this.Input.Email, "Confirm your email", emailContent); await this.signInManager.SignInAsync(user, isPersistent : false); var shoppingCartActivities = this.HttpContext.Session .GetObjectFromJson <ShoppingCartActivityViewModel[]>(WebConstants.ShoppingCartSessionKey) ?? new List <ShoppingCartActivityViewModel>().ToArray(); if (shoppingCartActivities != null) { foreach (var activity in shoppingCartActivities) { await this.shoppingCartsService.AddActivityToShoppingCartAsync(activity.ActivityId, this.Input.UserName, activity.Quantity); } this.HttpContext.Session.Remove(WebConstants.ShoppingCartSessionKey); } return(this.LocalRedirect(returnUrl)); } foreach (var error in result.Errors.Concat(customErrors)) { this.ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(this.Page()); }