Exemplo n.º 1
0
        public async Task CreateAsyncReturnsCorrect()
        {
            var id   = Guid.NewGuid().ToString();
            var user = new CarpetUser
            {
                Id          = id,
                FirstName   = "Иван",
                LastName    = "Иванов",
                PhoneNumber = "0888777444",
                Email       = "*****@*****.**",
                UserName    = "******",
            };
            var roleAdminId = Guid.NewGuid().ToString();
            var role        = new CarpetRole {
                Id = roleAdminId, Name = GlobalConstants.AdministratorRoleName
            };
            var roleOperatorId = Guid.NewGuid().ToString();
            var roleOperator   = new CarpetRole {
                Id = roleOperatorId, Name = GlobalConstants.OperatorRoleName
            };

            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "CreateAsyncReturnsCorrect")
                          .Options;
            var dbContext = new ApplicationDbContext(options);

            dbContext.Users.Add(user);
            dbContext.Roles.Add(role);
            dbContext.Roles.Add(roleOperator);
            await dbContext.SaveChangesAsync();

            var repository = new EfDeletableEntityRepository <Employee>(dbContext);
            var service    = new EmployeesService(repository, dbContext);

            var userFrom = dbContext.Users.First();

            var employeeId = Guid.NewGuid().ToString();

            var employee = new EmployeeCreateInputModel
            {
                Id          = id,
                FirstName   = "Иван",
                LastName    = "Иванов",
                PhoneNumber = "0888777444",
                Salary      = 1000m,
                RoleName    = GlobalConstants.OperatorRoleName,
            };

            var employeeFromDbFirst = await service.CreateAsync(employee, string.Empty);

            await service.DeleteByIdAsync(employeeFromDbFirst.Id);

            var employeeFromDb = await service.CreateAsync(employee, string.Empty);

            Assert.NotEqual(employeeFromDb.Id, employeeFromDbFirst.Id);
            Assert.Equal(employeeFromDb.PhoneNumber, employeeFromDbFirst.PhoneNumber);
            Assert.Equal(employeeFromDb.PhoneNumber, employeeFromDbFirst.PhoneNumber);
            Assert.Equal(employee.PhoneNumber, employeeFromDb.PhoneNumber);
        }
Exemplo n.º 2
0
 protected override IdentityUserLogin <string> CreateUserLogin(CarpetUser user, UserLoginInfo login) =>
 new IdentityUserLogin <string>
 {
     UserId              = user.Id,
     ProviderKey         = login.ProviderKey,
     LoginProvider       = login.LoginProvider,
     ProviderDisplayName = login.ProviderDisplayName,
 };
Exemplo n.º 3
0
        public async Task DeleteByIdAsyncWithWrongIdReturnsError()
        {
            var id   = Guid.NewGuid().ToString();
            var user = new CarpetUser
            {
                Id          = id,
                FirstName   = "Иван",
                LastName    = "Иванов",
                PhoneNumber = "0888777444",
                Email       = "*****@*****.**",
                UserName    = "******",
            };
            var roleAdminId = Guid.NewGuid().ToString();
            var role        = new CarpetRole {
                Id = roleAdminId, Name = GlobalConstants.AdministratorRoleName
            };
            var roleOperatorId = Guid.NewGuid().ToString();
            var roleOperator   = new CarpetRole {
                Id = roleOperatorId, Name = GlobalConstants.OperatorRoleName
            };

            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "DeleteByIdAsyncWithWrongIdReturnsError")
                          .Options;
            var dbContext = new ApplicationDbContext(options);

            dbContext.Users.Add(user);
            dbContext.Roles.Add(role);
            dbContext.Roles.Add(roleOperator);
            await dbContext.SaveChangesAsync();

            var repository = new EfDeletableEntityRepository <Employee>(dbContext);
            var service    = new EmployeesService(repository, dbContext);

            var wrongId = Guid.NewGuid().ToString();

            var employee = new EmployeeCreateInputModel
            {
                Id          = id,
                FirstName   = "Иван",
                LastName    = "Иванов",
                PhoneNumber = "0888777444",
                Salary      = 1000m,
                RoleName    = GlobalConstants.OperatorRoleName,
            };

            var employeeDelete = new EmployeeDeleteInputModel
            {
                Id = wrongId,
            };

            var result = await service.CreateAsync(employee, string.Empty);

            var exception = await Assert.ThrowsAsync <NullReferenceException>(() => service.DeleteByIdAsync(employeeDelete.Id));

            Assert.Equal(string.Format(string.Format(EmployeeConstants.NullReferenceId, wrongId)), exception.Message);
        }
Exemplo n.º 4
0
        protected override IdentityUserClaim <string> CreateUserClaim(CarpetUser user, Claim claim)
        {
            var identityUserClaim = new IdentityUserClaim <string> {
                UserId = user.Id
            };

            identityUserClaim.InitializeFromClaim(claim);
            return(identityUserClaim);
        }
Exemplo n.º 5
0
        public async Task GetByUsernameAsyncReturnsCorrect()
        {
            var id   = Guid.NewGuid().ToString();
            var user = new CarpetUser
            {
                Id          = id,
                FirstName   = "Иван",
                LastName    = "Иванов",
                PhoneNumber = "0888777444",
                Email       = "*****@*****.**",
                UserName    = "******",
            };
            var roleAdminId = Guid.NewGuid().ToString();
            var role        = new CarpetRole {
                Id = roleAdminId, Name = GlobalConstants.AdministratorRoleName
            };
            var roleOperatorId = Guid.NewGuid().ToString();
            var roleOperator   = new CarpetRole {
                Id = roleOperatorId, Name = GlobalConstants.OperatorRoleName
            };

            var options = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseInMemoryDatabase(databaseName: "GetByUsernameAsyncReturnsCorrect")
                          .Options;
            var dbContext = new ApplicationDbContext(options);

            dbContext.Users.Add(user);
            dbContext.Roles.Add(role);
            dbContext.Roles.Add(roleOperator);
            await dbContext.SaveChangesAsync();

            var repository = new EfDeletableEntityRepository <Employee>(dbContext);
            var service    = new EmployeesService(repository, dbContext);

            var employee = new EmployeeCreateInputModel
            {
                Id          = id,
                FirstName   = "Иван",
                LastName    = "Иванов",
                PhoneNumber = "0888777444",
                Salary      = 1000m,
                RoleName    = GlobalConstants.OperatorRoleName,
            };

            var result = await service.CreateAsync(employee, string.Empty);

            var username = await dbContext.Employees.FirstOrDefaultAsync(x => x.Id == result.Id);

            var actual = await service.GetIdByUserNameAsync(username.User.UserName);

            var employees = await service.GetAllAsync <EmployeeIndexViewModel>().ToListAsync();

            Assert.Equal(result.Id, actual);
            Assert.Single(employees);
        }
Exemplo n.º 6
0
        protected override IdentityUserToken <string> CreateUserToken(
            CarpetUser user,
            string loginProvider,
            string name,
            string value)
        {
            var token = new IdentityUserToken <string>
            {
                UserId        = user.Id,
                LoginProvider = loginProvider,
                Name          = name,
                Value         = value,
            };

            return(token);
        }
Exemplo n.º 7
0
        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 user = new CarpetUser {
                    UserName = this.Input.Email, Email = this.Input.Email
                };
                var result = await this.userManager.CreateAsync(user);

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

                    if (result.Succeeded)
                    {
                        await this.signInManager.SignInAsync(user, isPersistent : false);

                        this.logger.LogInformation(
                            "User created an account using {Name} provider.",
                            info.LoginProvider);
                        return(this.LocalRedirect(returnUrl));
                    }
                }

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

            this.LoginProvider = info.LoginProvider;
            this.ReturnUrl     = returnUrl;
            return(this.Page());
        }
Exemplo n.º 8
0
        private async Task LoadSharedKeyAndQrCodeUriAsync(CarpetUser 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);
        }
Exemplo n.º 9
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            var isRoot = !this.userManager.Users.Any();

            returnUrl = returnUrl ?? this.Url.Content("~/");
            if (this.ModelState.IsValid)
            {
                var user = new CarpetUser
                {
                    UserName    = this.Input.Email,
                    Email       = this.Input.Email,
                    FirstName   = this.Input.FirstName,
                    LastName    = this.Input.LastName,
                    PhoneNumber = this.Input.PhoneNumber,
                };

                var customer = new Customer
                {
                    FirstName     = user.FirstName,
                    LastName      = user.LastName,
                    User          = user,
                    PhoneNumber   = user.PhoneNumber,
                    PickUpAddress = "Sofia",
                };

                user.Customers.Add(customer);

                var result = await this.userManager.CreateAsync(user, this.Input.Password);

                if (result.Succeeded)
                {
                    if (isRoot)
                    {
                        await this.userManager.AddToRoleAsync(user, GlobalConstants.AdministratorRoleName);
                    }

                    this.logger.LogInformation("User created a new account with password.");

                    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);

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

                    await this.signInManager.SignInAsync(user, isPersistent : false);

                    return(this.LocalRedirect(returnUrl));
                }

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

            // If we got this far, something failed, redisplay form
            return(this.Page());
        }
Exemplo n.º 10
0
 protected override IdentityUserRole <string> CreateUserRole(CarpetUser user, CarpetRole role)
 {
     return(new IdentityUserRole <string> {
         RoleId = role.Id, UserId = user.Id
     });
 }