Ejemplo n.º 1
0
        public void TestViewUser()
        {
            var          r   = _ac.ViewUser(testUser.Id) as ViewResult;
            CarShareUser csu = (CarShareUser)r.Model;

            Assert.AreEqual("testUserName", csu.UserName);
        }
Ejemplo n.º 2
0
        public void TestEditUserDetails()
        {
            var          r   = _ac.EditUserDetails(testUser.Id) as ViewResult;
            CarShareUser csu = (CarShareUser)r.Model;

            Assert.AreEqual("testUserName", csu.UserName);
        }
Ejemplo n.º 3
0
        private async Task LoadAsync(CarShareUser user)
        {
            var email = await _userManager.GetEmailAsync(user);

            Email = email;

            Input = new InputModel
            {
                NewEmail = email,
            };

            IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user);
        }
Ejemplo n.º 4
0
        private async Task LoadAsync(CarShareUser user)
        {
            var userName = await _userManager.GetUserNameAsync(user);

            var phoneNumber = await _userManager.GetPhoneNumberAsync(user);

            Username = userName;

            Input = new InputModel
            {
                PhoneNumber = phoneNumber
            };
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new CarShareUser {
                    UserName = Input.Email, Email = Input.Email, Address = Input.Address
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { area = "Identity", userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Ejemplo n.º 6
0
        private async Task LoadSharedKeyAndQrCodeUriAsync(CarShareUser user)
        {
            // Load the authenticator key & QR code URI to display on the form
            var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);

            if (string.IsNullOrEmpty(unformattedKey))
            {
                await _userManager.ResetAuthenticatorKeyAsync(user);

                unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user);
            }

            SharedKey = FormatKey(unformattedKey);

            var email = await _userManager.GetEmailAsync(user);

            AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey);
        }
Ejemplo n.º 7
0
        public IActionResult EditUserDetails(CarShareUser model)
        {
            var user = _db.Users.SingleOrDefault(c => c.Id == model.Id);

            if (model.Email != null)
            {
                user.Email = model.Email;
            }
            if (model.Address != null)
            {
                user.Address = model.Address;
            }
            user.UserStatus = model.UserStatus;

            _db.Users.Update(user);
            _db.SaveChanges();
            return(RedirectToAction("UserManagement", "Admin"));
        }
Ejemplo n.º 8
0
        public void Initialize()
        {
            var optionsBuilder = new DbContextOptionsBuilder <ApplicationDbContext>();

            optionsBuilder.UseInMemoryDatabase <ApplicationDbContext>("AdminControllerTestDb");
            _dbContext = new ApplicationDbContext(optionsBuilder.Options);
            _ac        = new AdminController(_dbContext);

            // adding test user
            testUser = new CarShareUser()
            {
                UserName       = "******",
                Email          = "testUserEmail",
                EmailConfirmed = true
            };
            _dbContext.Users.Add(testUser);

            // adding test image
            testImage = new Image()
            {
                Title = "testTitle",
                Data  = Encoding.ASCII.GetBytes(new string('a', 100))
            };
            _dbContext.Images.Add(testImage);
            _dbContext.SaveChanges();

            // adding test car
            Image dbImage = _dbContext.Images.FirstOrDefault();

            testCar = new Car()
            {
                Registration = "testRegistration",
                Description  = "testDescription",
                Status       = CarStatus.Available,
                NumSeats     = 2,
                ImageId      = dbImage.Id,
                Image        = dbImage
            };
            _dbContext.Cars.Add(testCar);

            _dbContext.SaveChanges();
        }
Ejemplo n.º 9
0
        public void TestEditUserDetailsPost()
        {
            // mocking model
            CarShareUser modelUser = new CarShareUser()
            {
                Id         = testUser.Id,
                Email      = "newTestEmail",
                Address    = "newTestAddress",
                UserStatus = UserStatus.AwaitingHire
            };

            var r = _ac.EditUserDetails(modelUser) as ViewResult;

            // pulling edited user from db
            CarShareUser editedUser = _dbContext.Users.Where(u => u.Id == testUser.Id).FirstOrDefault();

            // asserting all required changes have been made correctly
            Assert.AreEqual(modelUser.Id, editedUser.Id);
            Assert.AreEqual(modelUser.Email, editedUser.Email);
            Assert.AreEqual(modelUser.Address, editedUser.Address);
            Assert.AreEqual(modelUser.UserStatus, editedUser.UserStatus);
        }
        private async Task CreateAdmin(IServiceProvider serviceProvider)
        {
            var roleManager = serviceProvider.GetRequiredService <RoleManager <IdentityRole> >();
            var userManager = serviceProvider.GetRequiredService <UserManager <CarShareUser> >();

            string[] roles = { "User", "Admin" };

            // setting up roles
            foreach (string role in roles)
            {
                if (await roleManager.RoleExistsAsync(role) == false)
                {
                    await roleManager.CreateAsync(new IdentityRole(role));
                }
            }

            // setting up admin
            if (await userManager.FindByEmailAsync("*****@*****.**") == null)
            {
                var powerUser = new CarShareUser
                {
                    UserName       = "******",
                    Email          = "*****@*****.**",
                    EmailConfirmed = true
                };
                string powerUserPassword = "******";

                var powerUserCreate = await userManager.CreateAsync(powerUser, powerUserPassword);
            }

            // assigning admin user to admin role
            var admin = await userManager.FindByEmailAsync("*****@*****.**");

            if (await userManager.IsInRoleAsync(admin, "Admin") == false)
            {
                await userManager.AddToRoleAsync(admin, "Admin");
            }
        }
Ejemplo n.º 11
0
        public async Task <IActionResult> OnPostConfirmationAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            // Get the information about the user from the external login provider
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                ErrorMessage = "Error loading external login information during confirmation.";
                return(RedirectToPage("./Login", new { ReturnUrl = returnUrl }));
            }

            if (ModelState.IsValid)
            {
                var user = new CarShareUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user);

                if (result.Succeeded)
                {
                    result = await _userManager.AddLoginAsync(user, info);

                    if (result.Succeeded)
                    {
                        _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider);

                        // If account confirmation is required, we need to show the link if we don't have a real email sender
                        if (_userManager.Options.SignIn.RequireConfirmedAccount)
                        {
                            return(RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }));
                        }

                        await _signInManager.SignInAsync(user, isPersistent : false);

                        var userId = await _userManager.GetUserIdAsync(user);

                        var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                        code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                        var callbackUrl = Url.Page(
                            "/Account/ConfirmEmail",
                            pageHandler: null,
                            values: new { area = "Identity", userId = userId, code = code },
                            protocol: Request.Scheme);

                        await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                          $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                        return(LocalRedirect(returnUrl));
                    }
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            LoginProvider = info.LoginProvider;
            ReturnUrl     = returnUrl;
            return(Page());
        }