Beispiel #1
0
        public void AuthenticateCommand_PresentWrongPassword_ThrowsException()
        {
            // ---- Arrange ----

            const string email         = "*****@*****.**";
            const string name          = "Test user";
            const string wrongPassword = "******";
            const string password      = "******";
            var          passwordHash  = AuthUtils.GetMd5Hash(password);

            var testUser = new UserIdentityModel(
                Guid.NewGuid(),
                email,
                "Test user",
                name,
                passwordHash,
                Instant.MinValue);

            _authRepositoryMock.Setup(r => r.GetUserIdentity(email))
            .ReturnsAsync(() => testUser);

            var command = new AuthenticateUserCommand(email, wrongPassword);
            var handler = new AuthenticateUserCommandHandler(_repositoryProviderMock.Object, _configuration);

            // ---- Act & Assert ----

            Assert.ThrowsAsync <WrongPasswordException>(
                async() => await handler.Handle(command, CancellationToken.None));

            _authRepositoryMock.Verify(r => r.GetUserIdentity(email), Times.Once);
        }
Beispiel #2
0
        public void GetMd5HashMethod__CheckGeneration_ValidMd5Hash()
        {
            const string examplePassword = @"EuYw7?{UsBVwQuCz";
            const string generatedMd5    = @"3977efafcd79547c092d22bc3b0bf70f";

            var md5 = AuthUtils.GetMd5Hash(examplePassword);

            StringAssert.AreEqualIgnoringCase(generatedMd5, md5);
            StringAssert.AreEqualIgnoringCase(md5, AuthUtils.GetMd5Hash(examplePassword));
        }
Beispiel #3
0
        public void AuthenticateCommand_AuthUser_SuccessAuth()
        {
            // ---- Arrange ----

            const string email        = "*****@*****.**";
            const string name         = "Test user";
            const string password     = "******";
            var          passwordHash = AuthUtils.GetMd5Hash(password);

            var clock    = new FakeClock(SystemClock.Instance.GetCurrentInstant());
            var testUser = new UserIdentityModel(
                Guid.NewGuid(),
                email,
                name,
                "user",
                passwordHash,
                clock.GetCurrentInstant());

            _authRepositoryMock.Setup(r => r.GetUserIdentity(email))
            .ReturnsAsync(() => testUser);

            var command = new AuthenticateUserCommand(email, password);
            var handler = new AuthenticateUserCommandHandler(_repositoryProviderMock.Object, _configuration)
            {
                Clock = clock
            };

            AuthAccessModel result = null;

            var lifetime = DurationUtils.FromString(
                _configuration[$"{AuthUtils.Jwt.ConfigKeys.Section}:{AuthUtils.Jwt.ConfigKeys.LifetimeKey}"]);

            // ---- Act ----

            Assert.DoesNotThrowAsync(async() => {
                result = await handler.Handle(command, CancellationToken.None);
            });

            clock.Advance(lifetime); // for check expires token instant

            // ---- Assert ----

            Assert.IsNotNull(result);
            Assert.AreEqual(testUser.Id, result.Id);
            Assert.AreEqual(testUser.Email, result.Email);
            Assert.AreEqual(clock.GetCurrentInstant(), result.ExpiresAt);
            Assert.AreEqual(clock.GetCurrentInstant(), result.ExpiresAt);
            Assert.AreEqual("user", testUser.Role);
            Assert.IsNotEmpty(result.Token);

            _authRepositoryMock.Verify(r => r.GetUserIdentity(email), Times.Once);
        }
        /// <exception cref="InvalidEmailFormatException"></exception>
        /// <exception cref="UserAlreadyExistsException"></exception>
        /// <exception cref="InvalidNameFormatException"></exception>
        /// <exception cref="WeakPasswordException"></exception>
        public async Task <UserModel> Handle(RegisterUserCommand request, CancellationToken cancellationToken)
        {
            // Check is email valid
            if (!AuthUtils.ValidateEmail(request.Email))
            {
                throw new InvalidEmailFormatException(request.Email);
            }

            // Check is user already exists
            var isExists = await _usersRepository.IsUserIdentityExists(request.Email);

            if (isExists)
            {
                throw new UserAlreadyExistsException(request.Email);
            }

            // Check name
            if (!AuthUtils.ValidateName(request.Name))
            {
                throw new InvalidNameFormatException(request.Name);
            }

            // Check password stronger
            if (!AuthUtils.CheckPasswordComplexity(request.Password))
            {
                throw new WeakPasswordException();
            }

            // Generate password hash
            var passwordHash = AuthUtils.GetMd5Hash(request.Password);

            // User registration instant
            var registrationInstant = Clock.GetCurrentInstant();

            var user = new UserIdentityModel(
                Guid.NewGuid(),
                request.Email,
                request.Name,
                "user",
                passwordHash,
                registrationInstant
                );

            // Register user
            var registrationResult = await _usersRepository.RegisterUser(user);

            return(registrationResult);
        }
Beispiel #5
0
        public Guid LoginUser(LoginRequest request)
        {
            var password = AuthUtils.GetMd5Hash(request.Password);

            var userEntity = _context.Users
                             .SingleOrDefault(x => x.Email == request.Email);

            if (userEntity == null || userEntity.Password != password || !userEntity.ConfirmEmail)
            {
                return(Guid.Empty);
            }

            var id = userEntity.UserId;

            return(id);
        }
Beispiel #6
0
        public Guid AddUser(RegistrationRequest request)
        {
            var userEntity = _context.Users
                             .SingleOrDefault(x => x.Email == request.Email);

            if (userEntity != null)
            {
                return(Guid.Empty);
            }

            var index = 1;

            if (_context.Users.Count() != 0)
            {
                index = _context.Users
                        .OrderByDescending(x => x.Index)
                        .ToList()
                        .First()
                        .Index + 1;
            }

            var cart = new CartEntity()
            {
                CartId = Guid.NewGuid()
            };

            var user = new UserEntity()
            {
                UserId      = Guid.NewGuid(),
                Index       = index,
                FullName    = request.FullName,
                CompanyName = request.CompanyName,
                Email       = request.Email,
                Cart        = cart,
                Password    = AuthUtils.GetMd5Hash(request.Password),
                Role        = UserRolesEnum.Customer
            };

            _context.Users.Add(user);
            _context.SaveChanges();

            var id = user.UserId;

            return(id);
        }
Beispiel #7
0
        public void AddAdminUser()
        {
            const string fullName = "Egor Vdovenko";
            const string email    = "*****@*****.**";
            const string password = "******";

            var context = new EfDbContext();

            var index = 1;

            if (context.Users.Count() != 0)
            {
                index = context.Users
                        .OrderByDescending(x => x.Index)
                        .ToList()
                        .First()
                        .Index + 1;
            }

            var cart = new CartEntity()
            {
                CartId = Guid.NewGuid()
            };

            var admin = new UserEntity()
            {
                UserId       = Guid.NewGuid(),
                Index        = index,
                FullName     = fullName,
                CompanyName  = "",
                Email        = email,
                Cart         = cart,
                ConfirmEmail = true,
                Password     = AuthUtils.GetMd5Hash(password),
                Role         = UserRolesEnum.Administrator
            };

            context.Users.Add(admin);
            context.SaveChanges();
        }
Beispiel #8
0
        private bool ValidatePassword(string providedPassword, UserIdentityModel identity)
        {
            var hash = AuthUtils.GetMd5Hash(providedPassword);

            return(StringComparer.OrdinalIgnoreCase.Compare(hash, identity.PasswordHash) == 0);
        }