public UserAuthenticationResultDTO Login(string username, string password, bool rememberMe)
        {
            var user = new UserAuthenticationDTO()
            {
                Id       = 1,
                Name     = "Osman",
                Surname  = "KURT",
                Email    = "*****@*****.**",
                UserName = "******",
                RoleId   = 1
            };

            var token = new CompanyUserToken(user, _appSettings, rememberMe).Create();

            return(new UserAuthenticationResultDTO()
            {
                Id = user.Id,
                Name = user.Name,
                Surname = user.Surname,
                Email = user.Email,
                UserName = user.UserName,
                Token = token,
                CreationDate = DateTime.Now
            });
        }
Esempio n. 2
0
        public async Task <UserAuthenticationDTO> CreateAsync(UserAuthenticationDTO authMethod)
        {
            var sqlParams = new
            {
                Id             = Guid.NewGuid(),
                UserId         = authMethod.UserId.RawValue,
                CredentialType = (int)authMethod.CredentialType,
                authMethod.Secret,
                authMethod.DisplayName,
                CreationTime = DateTime.UtcNow
            };
            string sql = @";
                INSERT INTO dbo.UserAuthenticationMethods(Id, UserId, CredentialType, Secret, DisplayName, CreationTime, IsRevoked)
                VALUES(@Id, @UserId, @CredentialType, @Secret, @DisplayName, @CreationTime, 0);

                SELECT Id,
                       UserId,
                       CredentialType,
                       Secret,
                       DisplayName,
                       CreationTime,
                       IsRevoked,
                       RevokeTime
                FROM dbo.UserAuthenticationMethods 
                WHERE Id = @Id;
            ";

            return(await _db.QuerySingle(async (db) =>
            {
                return await db.FetchAsync <UserAuthenticationDTO>(sql, sqlParams);
            }));
        }
Esempio n. 3
0
        // Register

        public async Task <RegisterResult> RegisterAsync(string newCustomerName, string username, string email, string password)
        {
            var customer     = new CustomerDTO(null, newCustomerName);
            var user         = new UserDTO(null, null, username, username, email);
            var passwordHash = BCrypt.Net.BCrypt.HashPassword(password);
            var authMethod   = new UserAuthenticationDTO(null, null, CredentialType.PasswordHash, passwordHash, "Password", DateTime.UtcNow);

            try
            {
                await _persistence.RequireTransactionAsync(async() =>
                {
                    customer          = await _persistence.Customers.CreateAsync(customer);
                    user.CustomerId   = customer.Id;
                    user              = await _persistence.Users.CreateAsync(user);
                    authMethod.UserId = user.Id;
                    authMethod        = await _persistence.UserAuthentications.CreateAsync(authMethod);
                });
            }
            catch (Exception exc)
            {
                //TODO reduce breadth of exception statement
                return(RegisterResult.GetFailed("Username is already in use"));
            }

            // add in option of an email activation step and use options to provide redirect url

            await SignInAsync(user);

            return(RegisterResult.GetSuccess());
        }
Esempio n. 4
0
        public async Task Get_User_Token()
        {
            //Given
            UserAuthenticationDTO user = new UserAuthenticationDTO()
            {
                username = "******",
                password = "******",
            };

            var userRepositoryMock = new Mock <IUserRepository>();

            userRepositoryMock.Setup(x => x.Validate(user.username, user.password)).ReturnsAsync(true);
            userRepositoryMock.Setup(x => x.GetByUsername(It.IsAny <string>())).ReturnsAsync(new User
            {
                username   = "******",
                password   = "******",
                userStatus = 1
            });
            //When
            UserController userController = new UserController(userRepositoryMock.Object);
            var            result         = await userController.ValidateUser(user) as ObjectResult;

            var resultToken = result.Value;

            //Then
            Assert.AreEqual((int)HttpStatusCode.OK, result.StatusCode);
            Assert.IsFalse(string.IsNullOrEmpty((string)resultToken));
        }
Esempio n. 5
0
        public async Task <bool> Authenticate(UserAuthenticationDTO userDto)
        {
            var user = await _context.Users.FirstOrDefaultAsync(u => u.Email == userDto.Email);

            if (user == null)
            {
                return(false);
            }
            if (user.PasswordHash != userDto.Password)
            {
                return(false);
            }

            return(true);
        }
Esempio n. 6
0
        public void WhenTheClientPutsARequestForALogin()
        {
            UserAuthenticationDTO userAuth = new UserAuthenticationDTO
            {
                username = _users.First().username,
                password = _users.First().password
            };

            var user   = JsonConvert.SerializeObject(userAuth);
            var uri    = "http://localhost:8080/users/login";
            var result = _client.PostAsync(uri, new StringContent(user, Encoding.UTF8, "application/json")).Result;
            var token  = result.Content.ReadAsStringAsync().Result;

            ScenarioContext.Current["statusCode"] = result.StatusCode;
            ScenarioContext.Current["token"]      = token;
        }
Esempio n. 7
0
        public void GivenIAmAnAuthorizedUser()
        {
            UserAuthenticationDTO userAuth = new UserAuthenticationDTO
            {
                username = "******",
                password = "******"
            };

            var user = JsonConvert.SerializeObject(userAuth);

            var uri = "http://localhost:8080/users/login";

            var token = _client.PostAsync(uri, new StringContent(user, Encoding.UTF8, "application/json")).Result.Content.ReadAsStringAsync().Result;

            _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token.ToString());
        }
Esempio n. 8
0
        public async Task UpdateAsync(UserAuthenticationDTO userAuth)
        {
            var sqlParams = new
            {
                Id = Guid.NewGuid(),
                userAuth.DisplayName,
                userAuth.IsRevoked,
                userAuth.RevokeTime
            };
            string sql = @";
                UPDATE dbo.UserAuthenticationMethods
                SET DisplayName = @DisplayName,
                    IsRevoked = @IsRevoked,
                    RevokeTime = @RevokeTime    
                WHERE Id = @Id;
            ";

            await _db.Execute(async (db) =>
            {
                await db.ExecuteAsync(sql, sqlParams);
            });
        }
Esempio n. 9
0
        public async Task <IActionResult> AuthenticateUser(UserAuthenticationDTO userDto)
        {
            bool isAuthenticated = await _usersRepository.Authenticate(userDto);

            if (!isAuthenticated)
            {
                return(BadRequest("Wrong credentials"));
            }

            var user = await _usersRepository.GetByEmail(userDto.Email);

            var claims = new List <Claim>()
            {
                new Claim("Id", user.Id.ToString()),
                new Claim(ClaimTypes.Email, user.Email),
                new Claim(ClaimTypes.Name, user.FirstName),
                new Claim(ClaimTypes.Surname, user.LastName),
            };

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var authProps      = new AuthenticationProperties()
            {
            };

            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
                                          new ClaimsPrincipal(claimsIdentity),
                                          authProps);

            var cookieOptions = new CookieOptions()
            {
                Expires = DateTimeOffset.Now.AddDays(1)
            };

            Response.Cookies.Append("Email", user.Email, cookieOptions);
            Response.Cookies.Append("Id", user.Id.ToString(), cookieOptions);

            return(Ok());
        }
Esempio n. 10
0
        public async Task <IActionResult> ValidateUser([FromBody] UserAuthenticationDTO userAuthentication)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid input"));
            }

            User user = await _userRepository.GetByUsername(userAuthentication.username);

            if (user.userStatus == 0)
            {
                return(BadRequest("User not allowed"));
            }

            if (await _userRepository.Validate(userAuthentication.username, userAuthentication.password))
            {
                var tokenHandler    = new JwtSecurityTokenHandler();
                var key             = Encoding.ASCII.GetBytes("VERY SECRET, MUCH HIDDEN");
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Subject = new ClaimsIdentity(new Claim[]
                    {
                        new Claim(ClaimTypes.Name, userAuthentication.username)
                    }),
                    Expires            = DateTime.UtcNow.AddHours(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };

                var token      = tokenHandler.CreateToken(tokenDescriptor);
                var tokenValue = tokenHandler.WriteToken(token);

                return(Ok(tokenValue));
            }

            return(BadRequest("Wrong password or username"));
        }
Esempio n. 11
0
 public CompanyUserToken(UserAuthenticationDTO user, Appsettings appSettings, bool rememberMe) : base(user, appSettings, rememberMe)
 {
     _claims.Add(new Claim(ApplicationConstants.ClaimId, _user.Id.ToString()));
 }