Example #1
0
        public async Task ShouldReturnEmployee()
        {
            var employeeId = Guid.NewGuid();
            var companyId  = Guid.NewGuid();
            var tenantId   = Guid.NewGuid();

            var expected = new Employee()
            {
                Id        = employeeId,
                CompanyId = companyId,
                TenantId  = tenantId,
            };
            var employees = new List <Employee>()
            {
                expected,
                new Employee()
                {
                    Id = Guid.NewGuid(),
                }
            };

            _mock.Mock <IInventContext>()
            .Setup(context => context.Employees)
            .ReturnsAsDbSet(employees);

            var actual = await _provider.GetByIdAsync(employeeId);

            ContentAssert.AreEqual(expected, actual);
        }
        public async Task ShouldUpdateSecurityUser()
        {
            var usertId      = Guid.NewGuid();
            var securityUser = new SecurityUser();

            var expected = new UserSettingsDTO();

            var userSettingsDTO = new UserSettingsDTO();

            _mock.Mock <ISecurityUserProvider>()
            .Setup(provider => provider.GetByUserIdAsync(usertId))
            .ReturnsAsync(securityUser);

            _mock.Mock <IMapper>()
            .Setup(mapper => mapper.Map(userSettingsDTO, securityUser))
            .Returns(securityUser);

            _mock.Mock <IMapper>()
            .Setup(mapper => mapper.Map <UserSettingsDTO>(securityUser))
            .Returns(expected);

            var actual = await _service.UpdateAsync(userSettingsDTO, usertId);

            _mock.Mock <IInventContext>()
            .Verify(context => context.Update(securityUser));

            _mock.Mock <IInventContext>()
            .Verify(context => context.SaveChangesAsync(default(CancellationToken)));

            ContentAssert.AreEqual(expected, actual);
        }
Example #3
0
        public async Task ForgotPasswordShouldReturnBadRequestWhenUserIsNotFound()
        {
            const string email           = "[email protected]";
            const string validationToken = "validation token";

            var request = new ForgotPasswordRequest
            {
                Email           = email,
                ValidationToken = validationToken
            };

            var response = SendGridHelper.GetEmptyResponse(System.Net.HttpStatusCode.Accepted);

            _mock.Mock <IUserManager>()
            .Setup(manager => manager.FindByEmailAsync(email))
            .ReturnsAsync(null as User);

            _mock.Mock <ICaptchaValidationService>()
            .Setup(provider => provider.IsValidAsync(validationToken))
            .ReturnsAsync(true);

            var controller = _mock.Create <AuthController>();
            var actual     = await controller.ForgotPassword(request);

            var expected = new BadRequestObjectResult("USER_NOT_FOUND");

            ContentAssert.AreEqual(expected, actual);
        }
        public async Task ShouldGetTenantSettings()
        {
            var tenantId       = Guid.NewGuid();
            var tenantSettings = new TenantSettings()
            {
                TenantId = tenantId,
            };

            var expected = new TenantSettingsDTO();

            var tenantSettingsList = new List <TenantSettings>()
            {
                tenantSettings,
                new TenantSettings()
                {
                    TenantId = Guid.NewGuid(),
                }
            };

            _mock.Mock <IInventContext>()
            .Setup(context => context.TenantSettings)
            .ReturnsAsDbSet(tenantSettingsList);

            var actual = await _service.GetByTenantIdAsync(tenantId);

            ContentAssert.AreEqual(expected, actual);
        }
        public async Task ShouldReturnTenant()
        {
            var tenantId = Guid.NewGuid();

            var expected = new Tenant()
            {
                Id = tenantId,
            };
            var tenants = new List <Tenant>()
            {
                expected,
                new Tenant()
                {
                    Id = Guid.NewGuid(),
                }
            };

            _mock.Mock <IInventContext>()
            .Setup(context => context.Tenants)
            .ReturnsAsDbSet(tenants);

            var actual = await _provider.GetByIdAsync(tenantId);

            ContentAssert.AreEqual(expected, actual);
        }
        public async Task ReturnsValidWhenModelIsValid()
        {
            const string companyName     = "company name";
            const string companyPhone    = "companyPhone";
            const string firstName       = "First Name";
            const string email           = "[email protected]";
            const string lastName        = "Last Name";
            const string password        = "******";
            const string validationToken = "validation token";

            var request = new CompanyRegisterRequest
            {
                CompanyName     = companyName,
                CompanyPhone    = companyPhone,
                FirstName       = firstName,
                Email           = email,
                LastName        = lastName,
                Password        = password,
                ValidationToken = validationToken,
                ToSAccepted     = true,
            };

            _mock.Mock <ICompanyNameIsTakenProvider>()
            .Setup(context => context.IsTaken(companyName))
            .ReturnsAsync(false);

            _mock.Mock <IEmailIsTakenProvider>()
            .Setup(context => context.IsTaken(email))
            .ReturnsAsync(false);

            var validator = _mock.Create <CompanyRegisterRequestValidator>();
            var actual    = await validator.ValidateAsync(request);

            ContentAssert.AreEqual(new ValidationResult(), actual);
        }
Example #7
0
        public async Task ShouldReturnAllEmployeesOfAdminsCompany()
        {
            var userId     = Guid.NewGuid();
            var employeeId = Guid.NewGuid();
            var expected   = new Company()
            {
                Employees = new List <Employee>()
                {
                    new Employee()
                    {
                        Id           = employeeId,
                        SecurityUser = new SecurityUser()
                        {
                            UserId = userId,
                        },
                    },
                },
            };

            var companies = new List <Company>()
            {
                expected
            };

            _mock.Mock <IInventContext>()
            .Setup(context => context.Companies)
            .ReturnsAsDbSet(companies);

            var actual = await _provider.GetAsync(userId);

            ContentAssert.AreEqual(expected, actual);
        }
        public async Task ShouldReturnUserSettingsDTOOnGetAction()
        {
            Guid userId         = Guid.NewGuid();
            Guid securityUserId = Guid.NewGuid();

            var securityUser = new SecurityUser
            {
                Id = securityUserId
            };

            var expected = new UserSettingsDTO();

            var controller = _mock.Create <UserSettingsController>();

            _mock.Mock <IUserManager>()
            .Setup(manager => manager.GetUserId(controller.User))
            .Returns(userId);

            _mock.Mock <ISecurityUserProvider>()
            .Setup(provider => provider.GetByUserIdAsync(userId))
            .ReturnsAsync(securityUser);

            _mock.Mock <IMapper>()
            .Setup(mapper => mapper.Map <UserSettingsDTO>(securityUser))
            .Returns(expected);

            var actual = await controller.Get();

            ContentAssert.AreEqual(expected, actual);
        }
        public async Task ReturnsActivationRequestParams()
        {
            var userId      = new Guid("{FF9C001A-075B-4ACB-B31F-07E818A56A99}");
            var credentials = new OtpActivationRequestParams
            {
                UserId = userId
            };

            var secretKey    = "secret key";
            var securityUser = new SecurityUser
            {
                TwoFactorAuthenticationSecretKey = secretKey
            };

            _mock.Mock <ISecurityUserProvider>()
            .Setup(provider => provider.GetByUserIdAsync(userId))
            .ReturnsAsync(securityUser);

            var service = _mock.Create <OtpDeactivationService>();
            await service.DeactivateAsync(credentials);

            var expected = new SecurityUser
            {
                TwoFactorAuthenticationSecretKey = null
            };

            ContentAssert.AreEqual(expected, securityUser);

            _mock.Mock <IInventContext>()
            .Verify(context => context.Update(securityUser), Times.Once);

            _mock.Mock <IInventContext>()
            .Verify(context => context.SaveChangesAsync(default(CancellationToken)), Times.Once);
        }
Example #10
0
        public void ReturnsUser()
        {
            const string companyName      = "company name";
            const string email            = "[email protected]";
            const string firstName        = "First Name";
            const string lastName         = "Last Name";
            const string password         = "******";
            var          concurrencyStamp = new Guid("{F031AC41-810E-4A26-B4CE-4DD7E29434DF}");

            var request = new CompanyRegisterRequest
            {
                CompanyName = companyName,
                Email       = email,
                FirstName   = firstName,
                LastName    = lastName,
                Password    = password
            };

            _mock.Mock <INewGuidProvider>()
            .Setup(provider => provider.Get())
            .Returns(concurrencyStamp);

            var converter = _mock.Create <CompanyRegisterRequestToUserConverter>();
            var actual    = converter.Convert(request);

            var company = new Company
            {
                Name = companyName
            };

            var tenant = new Tenant
            {
                IsActive = true,
                Name     = request.CompanyName,
                Company  = company,
            };

            var expected = new User
            {
                UserName     = email,
                Email        = email,
                SecurityUser = new SecurityUser
                {
                    IsActive             = true,
                    IsInvited            = true,
                    IsInvitationAccepted = true,
                    Tenant   = tenant,
                    Employee = new Employee
                    {
                        Company   = company,
                        FirstName = firstName,
                        LastName  = lastName,
                        Tenant    = tenant,
                    }
                },
                ConcurrencyStamp = concurrencyStamp.ToString()
            };

            ContentAssert.AreEqual(expected, actual);
        }
Example #11
0
        public void ReturnsJwtSecurityToken()
        {
            const string issuer          = "http://cloudinventory.ru/";
            var          expires         = new DateTime(2018, 5, 3);
            var          jwtTokenOptions = new JwtTokenOptions
            {
                Issuer = issuer
            };
            var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret key"));
            var signingCredentials   = new SigningCredentials(symmetricSecurityKey, SecurityAlgorithms.HmacSha256);
            var claims = new List <Claim>();

            _mock.Mock <IOptions <JwtTokenOptions> >()
            .Setup(options => options.Value)
            .Returns(jwtTokenOptions);

            _mock.Mock <ISymmetricSecurityKeyProvider>()
            .Setup(provider => provider.GetKey())
            .Returns(symmetricSecurityKey);

            var service = _mock.Create <JwtSecurityTokenProvider>();
            var actual  = service.Create(claims, expires, signingCredentials);

            var expected = new JwtSecurityToken(issuer, issuer, claims, expires: expires,
                                                signingCredentials: signingCredentials);

            ContentAssert.AreEqual(expected, actual);
        }
Example #12
0
        public async Task ShouldReturnSecurityUserByUserId()
        {
            var userId = Guid.NewGuid();

            var expected = new SecurityUser()
            {
                UserId = userId,
            };
            var securityUsers = new List <SecurityUser>()
            {
                expected,
                new SecurityUser()
                {
                    UserId = Guid.NewGuid(),
                }
            };

            _mock.Mock <IInventContext>()
            .Setup(context => context.SecurityUsers)
            .ReturnsAsDbSet(securityUsers);

            var actual = await _provider.GetByUserIdAsync(userId);

            ContentAssert.AreEqual(expected, actual);
        }
Example #13
0
        public void ShouldReturnUserId()
        {
            const string token = "token";

            var parameters = new TokenValidationParameters
            {
                ValidateIssuer           = true,
                ValidateAudience         = true,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
            };

            var claim  = new Claim(ProjectClaims.OtpAuthTokenClaimName, "");
            var claim2 = new Claim(ClaimTypes.NameIdentifier, "5582f0f2-e904-4240-86cf-e0f865783aa5");

            var claimsIdentity = new ClaimsIdentity(new Claim[] { claim, claim2 }, "");

            var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);

            _mock.Mock <ITokenValidationParametersProvider>()
            .Setup(provider => provider.GetParameters())
            .Returns(parameters);

            _mock.Mock <IJwtSecurityTokenValidator>()
            .Setup(provider => provider.Validate(token, parameters))
            .Returns(claimsPrincipal);

            var expected = new Guid("5582f0f2-e904-4240-86cf-e0f865783aa5");

            var controller = _mock.Create <UserIdFromOtpTokenProvider>();

            var actual = controller.Get(token);

            ContentAssert.AreEqual(actual, expected);
        }
        public async Task ShouldDeleteUserPicture()
        {
            var claimsPrincipal = new ClaimsPrincipal();

            var controllerContext = new ControllerContext
            {
                HttpContext = new DefaultHttpContext
                {
                    User = claimsPrincipal
                }
            };
            var userId = Guid.NewGuid();

            var expected = new UserSettingsDTO();

            var controller = _mock.Create <UserPictureController>();

            controller.ControllerContext = controllerContext;

            _mock.Mock <IUserManager>()
            .Setup(manager => manager.GetUserId(controller.User))
            .Returns(userId);

            _mock.Mock <IUserPictureService>()
            .Setup(service => service.DeleteUserPictureAsync(userId))
            .ReturnsAsync(expected);

            var actual = await controller.DeleteUserPicture();

            ContentAssert.AreEqual(expected, actual);
        }
Example #15
0
        public async Task ReturnsValidWhenModelWithIdIsValid()
        {
            const string email           = "[email protected]";
            var          claimsPrincipal = _mock.Mock <ClaimsPrincipal>().Object;
            var          httpContext     = _mock.Mock <HttpContext>().Object;

            var request = new EmployeeDTO
            {
                Id          = Guid.NewGuid(),
                DateOfBirth = DateTime.Now,
                Email       = email,
                FirstName   = "FirstName",
                LastName    = "LastName",
                Gender      = Gender.Female,
                Phone       = "Phone",
            };

            _mock.Mock <HttpContext>()
            .SetupGet(context => context.User)
            .Returns(claimsPrincipal);

            _mock.Mock <IHttpContextAccessor>()
            .SetupGet(accessor => accessor.HttpContext)
            .Returns(httpContext);

            _mock.Mock <IEmailIsTakenProvider>()
            .Setup(provider => provider.IsTaken(email))
            .ReturnsAsync(false);

            var actual = await _validator.ValidateAsync(request);

            ContentAssert.AreEqual(new ValidationResult(), actual);
        }
        public async Task ShouldReturnDashboardSummaryResponse()
        {
            var claimsPrincipal = new ClaimsPrincipal();

            var controllerContext = new ControllerContext
            {
                HttpContext = new DefaultHttpContext
                {
                    User = claimsPrincipal
                }
            };

            var expected = new DashboardSummaryResponse();

            var controller = _mock.Create <DashboardController>();

            controller.ControllerContext = controllerContext;

            _mock.Mock <IDashboardService>()
            .Setup(service => service.GetSummaryAsync(controller.User))
            .ReturnsAsync(expected);

            var actual = await controller.GetSummary();

            ContentAssert.AreEqual(expected, actual);
        }
        public void ReturnsJwtSecurityTokenClaims()
        {
            const bool hasLongTimeToLive = true;
            var        jtiGuid           = new Guid("{9A02969F-BA20-43E6-8E9F-70CD525C1942}");
            var        userId            = new Guid("{EC2995E1-ADF0-4A7B-8A6F-A59F76FD176B}");

            var roles = new List <string> {
                UserRoles.Employee.Name,
                UserRoles.CompanyAdministrator.Name,
            };

            _mock.Mock <INewGuidProvider>()
            .Setup(guidProvider => guidProvider.Get())
            .Returns(jtiGuid);

            var provider = _mock.Create <JwtTokenClaimsProvider>();
            var actual   = provider.GetClaims(userId, hasLongTimeToLive, roles);

            var expected = new List <Claim>
            {
                new Claim(JwtRegisteredClaimNames.Jti, jtiGuid.ToString()),
                new Claim(ClaimTypes.NameIdentifier, userId.ToString()),
                new Claim(ProjectClaims.JwtTokenHasLongTimeToLiveClaimName, hasLongTimeToLive.ToString()),
                new Claim(ClaimTypes.Role, UserRoles.Employee.Name),
                new Claim(ClaimTypes.Role, UserRoles.CompanyAdministrator.Name)
            };

            ContentAssert.AreEqual(expected, actual);
        }
Example #18
0
        public void ReturnsTokenValidationParameters()
        {
            const string issuer = "http://cloudinventory.ru/";

            var symmetricSecurityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("secret key"));

            var jwtTokenOptions = new JwtTokenOptions
            {
                Issuer = issuer
            };

            _mock.Mock <IOptions <JwtTokenOptions> >()
            .Setup(options => options.Value)
            .Returns(jwtTokenOptions);

            _mock.Mock <ISymmetricSecurityKeyProvider>()
            .Setup(provider => provider.GetKey())
            .Returns(symmetricSecurityKey);

            var service = _mock.Create <TokenValidationParametersProvider>();
            var actual  = service.GetParameters();

            var expected = new TokenValidationParameters
            {
                ValidateIssuer           = true,
                ValidateAudience         = true,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer      = issuer,
                ValidAudience    = issuer,
                IssuerSigningKey = symmetricSecurityKey
            };

            ContentAssert.AreEqual(expected, actual);
        }
Example #19
0
        public void OtpSignInSouldShouldReturnOkResultWhenAllIsCorrect()
        {
            const string token           = "token";
            const string validationToken = "validation token";
            const int    code            = 123;
            var          userId          = new Guid("5582f0f2-e904-4240-86cf-e0f865783aa5");

            var user = new User()
            {
                Id = userId
            };

            var request = new OtpSignInRequest
            {
                Code            = code,
                ValidationToken = validationToken,
                Token           = token
            };

            var parameters = new TokenValidationParameters
            {
                ValidateIssuer           = true,
                ValidateAudience         = true,
                ValidateLifetime         = true,
                ValidateIssuerSigningKey = true,
            };


            var expected = new SignInResponse();

            _mock.Mock <ICaptchaValidationService>()
            .Setup(provider => provider.IsValidAsync(validationToken))
            .ReturnsAsync(true);

            _mock.Mock <ITokenValidationParametersProvider>()
            .Setup(provider => provider.GetParameters())
            .Returns(parameters);

            _mock.Mock <IUserIdFromOtpTokenProvider>()
            .Setup(provider => provider.Get(token))
            .Returns(userId);

            _mock.Mock <IUserManager>()
            .Setup(provider => provider.FindByIdAsync(userId))
            .ReturnsAsync(user);

            _mock.Mock <IOtpSignInValidationService>()
            .Setup(provider => provider.Validate(user.Id, code))
            .ReturnsAsync(true);

            _mock.Mock <ISignInResponseProvider> ()
            .Setup(provider => provider.Get(user, false))
            .Returns(expected);

            var controller = _mock.Create <AuthController>();
            var actual     = controller.OtpSignIn(request);

            ContentAssert.AreEqual(actual.Result, expected);
        }
        public void ShouldReturnSignInResponseByUser()
        {
            const string email      = "[email protected]";
            Guid         userId     = Guid.NewGuid();
            const string token      = "token";
            const bool   rememberMe = true;

            var roles = new List <UserRole>()
            {
                new UserRole()
                {
                    Role = new Role()
                    {
                        Name = UserRoles.Employee.Name,
                    }
                },
                new UserRole()
                {
                    Role = new Role()
                    {
                        Name = UserRoles.CompanyAdministrator.Name,
                    }
                },
            };

            var rolesFalt = roles.Select(r => r.Role.Name).ToList();

            var user = new User()
            {
                Id    = userId,
                Email = email,
                Roles = roles,
            };

            var userDTO = new UserDTO
            {
                Email = email,
                Roles = rolesFalt,
            };

            var expected = new SignInResponse
            {
                Token = token,
                User  = userDTO
            };

            _mock.Mock <ICreateJwtTokenAsStringService>()
            .Setup(service => service.Create(userId, rememberMe, rolesFalt))
            .Returns(token);

            _mock.Mock <IMapper>()
            .Setup(mapper => mapper.Map <UserDTO>(user))
            .Returns(userDTO);

            var actual = _provider.Get(user, rememberMe);

            ContentAssert.AreEqual(expected, actual);
        }
Example #21
0
        public async Task HasOnlyAdminUsersShouldReturnFalse()
        {
            var tenantId = Guid.NewGuid();

            var employees = new List <Employee>
            {
                new Employee
                {
                    TenantId     = tenantId,
                    SecurityUser = new SecurityUser()
                    {
                        User = new User()
                        {
                            Roles = new List <UserRole>()
                            {
                                new UserRole()
                                {
                                    RoleId = UserRoles.Employee.RoleId
                                },
                                new UserRole()
                                {
                                    RoleId = UserRoles.CompanyAdministrator.RoleId
                                },
                            },
                        }
                    }
                },
                new Employee
                {
                    TenantId     = tenantId,
                    SecurityUser = new SecurityUser()
                    {
                        User = new User()
                        {
                            Roles = new List <UserRole>()
                            {
                                new UserRole()
                                {
                                    RoleId = UserRoles.Employee.RoleId
                                },
                            },
                        }
                    }
                },
            };

            var expected = false;

            _mock.Mock <IInventContext>()
            .Setup(context => context.Employees)
            .ReturnsAsDbSet(employees);

            var actual = await _service.HasOnlyAdminUsers(tenantId);

            ContentAssert.AreEqual(expected, actual);
        }
        public async Task ShouldReturnUserDTOOnMeAction()
        {
            const string email  = "[email protected]";
            Guid         userId = Guid.NewGuid();

            var roles = new List <UserRole>()
            {
                new UserRole()
                {
                    Role = new Role()
                    {
                        Name = UserRoles.Employee.Name,
                    }
                },
                new UserRole()
                {
                    Role = new Role()
                    {
                        Name = UserRoles.CompanyAdministrator.Name,
                    }
                },
            };

            var user = new User()
            {
                Id    = userId,
                Email = email,
                Roles = roles,
            };

            var expected = new UserDTO
            {
                Email = email,
                Roles = roles.Select(r => r.Role.Name).ToList(),
            };

            var controller = _mock.Create <UserController>();

            _mock.Mock <IUserManager>()
            .Setup(manager => manager.GetUserId(controller.User))
            .Returns(userId);

            _mock.Mock <IUserManager>()
            .Setup(provider => provider.FindByIdAsync(userId))
            .ReturnsAsync(user);

            _mock.Mock <IMapper>()
            .Setup(mapper => mapper.Map <UserDTO>(user))
            .Returns(expected);

            var actual = await controller.Me();

            ContentAssert.AreEqual(expected, actual);
        }
Example #23
0
        public void ShouldBuildUri()
        {
            var expected = "http://cloudinventory.ru/some-relative-url?userId=userId1&code=code1";

            var actual = _clientUriService.BuildUri("some-relative-url", new NameValueCollection()
            {
                { "userId", "userId1" },
                { "code", "code1" },
            });

            ContentAssert.AreEqual(expected, actual);
        }
Example #24
0
        public async Task GetEventLocations_ShouldSuccess()
        {
            var          eventId      = new Guid("EECB7DF6-A46A-4AE1-970F-2041F62525E8");
            const string locationName = "Skolas iela 1, Riga, Latvia";
            const double latitude     = 22;
            const double longitude    = 33;
            var          eventStart   = new DateTime(1999, 12, 1);
            var          eventEnd     = new DateTime(1999, 12, 2);

            var locations = new List <Location>
            {
                new Location
                {
                    Name       = locationName,
                    Longitude  = longitude,
                    Latitude   = latitude,
                    EventStart = eventStart,
                    EventEnd   = eventEnd
                }
            };

            var @event = new Event
            {
                Id = eventId
            };

            _eventRepositoryMock.Setup(er => er.Get(eventId)).ReturnsAsync(@event);

            _locationRepositoryMock.Setup(lr => lr.GetEventLocations(eventId))
            .ReturnsAsync(locations);

            GetEventLocationsResponse actual = await _locationService.GetEventLocations(eventId);

            var expected = new GetEventLocationsResponse
            {
                EventId   = eventId,
                Locations = new List <LocationDto>
                {
                    new LocationDto
                    {
                        EventStart = eventStart,
                        EventEnd   = eventEnd,
                        Longitude  = longitude,
                        Latitude   = latitude,
                        Name       = locationName
                    }
                }
            };

            ContentAssert.AreEqual(expected, actual);
        }
        public void ReturnsActivationRequestParams()
        {
            var otp       = "123456";
            var password  = "******";
            var secretKey = "secret key123456";
            var otpToken  = "otp token";
            var userId    = new Guid("{289D2B80-8FFA-43FC-996A-871CC5145308}");

            var credentials = new OtpActivationRequest
            {
                Otp      = otp,
                Password = password,
                OtpToken = otpToken
            };

            var claimsPrincipal = new Mock <ClaimsPrincipal>().Object;

            _mock.Mock <ITokenClaimsPrincipalFactory>()
            .Setup(instance => instance.Create(otpToken))
            .Returns(claimsPrincipal);

            _mock.Mock <IUserIdClaimValueProvider>()
            .Setup(instance => instance.GetValue())
            .Returns(userId);
            _mock.Mock <IOtpSecretKeyClaimValueProvider>()
            .Setup(instance => instance.GetValue())
            .Returns(secretKey);

            _mock.Mock <IFactory <ClaimsPrincipal, IUserIdClaimValueProvider> >()
            .Setup(factory => factory.Create(claimsPrincipal))
            .Returns(_mock.Mock <IUserIdClaimValueProvider>().Object);

            _mock.Mock <IFactory <ClaimsPrincipal, IOtpSecretKeyClaimValueProvider> >()
            .Setup(factory => factory.Create(claimsPrincipal))
            .Returns(_mock.Mock <IOtpSecretKeyClaimValueProvider>().Object);

            var provider = _mock.Create <OtpActivationRequestParamProvider>();
            var actual   = provider.Get(credentials);

            var secretKeyData = secretKey.FromBase32(config: Base32Config.Rfc);
            var expected      = new OtpActivationRequestParams
            {
                Otp       = otp,
                Password  = password,
                SecretKey = secretKeyData,
                UserId    = userId
            };

            ContentAssert.AreEqual(expected, actual);
        }
Example #26
0
        public async Task CetEventCategories_ShouldSuccess()
        {
            //ARRANGE
            const string catDesc    = "cat desc";
            const string catName    = "cat name";
            var          categoryId = new Guid("7BC0C011-7FA3-4AA4-B260-257465831D65");
            var          eventId    = new Guid("DDB2B2AB-D122-40FA-B117-7DB88F48FA23");

            var @event = new Event
            {
                Id = eventId
            };

            var categories = new List <Category>
            {
                new Category
                {
                    Description = catDesc,
                    Name        = catName,
                    Id          = categoryId
                }
            };

            _eventRepositoryMock.Setup(er => er.Get(eventId))
            .ReturnsAsync(@event);


            _categoryRepositoryMock.Setup(cr => cr.GetEventCategories(eventId))
            .ReturnsAsync(categories);

            //ACT
            GetEventCategoriesResponse actual = await _categoryService.GetEventCategories(eventId);

            //ASSERT
            var expected = new GetEventCategoriesResponse
            {
                EventId    = eventId,
                Categories = new List <CategoryDto>
                {
                    new CategoryDto
                    {
                        Description = catDesc,
                        Name        = catName,
                        Id          = categoryId
                    }
                }
            };

            ContentAssert.AreEqual(expected, actual);
        }
        public async Task ShouldUpdateEmployeeAndReturnOneWithId()
        {
            var expected = new EmployeeDTO()
            {
                Id = Guid.NewGuid(),
            };

            _mock.Mock <IEmployeesService>()
            .Setup(service => service.UpdateAsync(expected))
            .ReturnsAsync(expected);

            var actual = await _controller.Update(expected);

            ContentAssert.AreEqual(expected, actual);
        }
Example #28
0
        public async Task ReturnsActivationRequestParams()
        {
            var otp       = "123456";
            var password  = "******";
            var secretKey = new byte[] { 1 };
            var userId    = new Guid("{289D2B80-8FFA-43FC-996A-871CC5145308}");
            var user      = new User
            {
                Id = userId
            };
            var credentials = new OtpDeactivationRequest
            {
                Otp      = otp,
                Password = password
            };

            var claimsPrincipal = _mock.Mock <ClaimsPrincipal>().Object;
            var httpContext     = _mock.Mock <HttpContext>().Object;

            _mock.Mock <IOtpSecretKeyProvider>()
            .Setup(instance => instance.ReadAsync(userId))
            .ReturnsAsync(secretKey);

            _mock.Mock <HttpContext>()
            .SetupGet(context => context.User)
            .Returns(claimsPrincipal);

            _mock.Mock <IHttpContextAccessor>()
            .SetupGet(accessor => accessor.HttpContext)
            .Returns(httpContext);

            _mock.Mock <ICurrentUserProvider>()
            .Setup(instance => instance.GetUserAsync(claimsPrincipal))
            .ReturnsAsync(user);

            var provider = _mock.Create <OtpDeactivationRequestParamProvider>();
            var actual   = await provider.GetAsync(credentials);

            var expected = new OtpActivationRequestParams
            {
                Otp       = otp,
                Password  = password,
                SecretKey = secretKey,
                UserId    = userId
            };

            ContentAssert.AreEqual(expected, actual);
        }
        public void ReturnsSigningCredentials()
        {
            const string secretKey = "secret key";
            var          key       = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

            _mock.Mock <ISymmetricSecurityKeyProvider>()
            .Setup(keyProvider => keyProvider.GetKey())
            .Returns(key);

            var provider = _mock.Create <SigningCredentialsProvider>();
            var actual   = provider.Get();

            var expected = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            ContentAssert.AreEqual(expected, actual);
        }
        public async Task GetReturnsSuccessResponse()
        {
            var expected = new OtpGetLinkResponse();
            var request  = new OtpLinkRequest();

            _mock.Mock <IOtpLinkRequestProvider>()
            .Setup(instance => instance.GetAsync())
            .ReturnsAsync(request);
            _mock.Mock <IOtpResponseProvider>()
            .Setup(instance => instance.Get(request))
            .Returns(expected);

            var controller = _mock.Create <AuthOtpController>();
            var actual     = await controller.Get();

            ContentAssert.AreEqual(expected, actual);
        }