Ejemplo n.º 1
0
        public void AltranController_Authenticate_NonExistingEmails_ReturnsBadRequestObjectResult()
        {
            //Arrange
            var mapper = ArrangeProvider.GetMapper();

            var email = ArrangeProvider._EMAIL_;

            var token = new AuthenticationTokenDto
            {
                Email = ArrangeProvider._EMAIL_,
                Role  = Role.Admin,
                Token = "Token"
            };

            var mockClientService = new Mock <IClientsService>();

            mockClientService.Setup(x => x.Authenticate(email)).Returns(token);

            var mockPolicyService = new Mock <IPoliciesService>();

            var controller = new AltranController(mockClientService.Object, mockPolicyService.Object);

            // Act
            var actionResult = controller.Authenticate(ArrangeProvider._EMAIL2_);

            //Assert
            Assert.IsInstanceOfType(actionResult.Result, typeof(BadRequestObjectResult));
        }
Ejemplo n.º 2
0
        public AuthenticationTokenDto SignIn(string login, string password)
        {
            AuthenticationTokenDto tokenDto = null;

            password = Encryptor.MD5Hash(password);
            User user = userRepository.GetItemsList().FirstOrDefault(u => u.Login.Equals(login) && u.Password.Equals(password));

            if (user != null)
            {
                if (user.AuthenticationToken == null)
                {
                    user.AuthenticationToken = new AuthenticationToken()
                    {
                        Login = user.Login,
                        Token = Guid.NewGuid().ToString()
                    };
                    userRepository.Update(user);
                    userRepository.Save();
                }

                tokenDto        = Mapper.Map <AuthenticationToken, AuthenticationTokenDto>(user.AuthenticationToken);
                tokenDto.UserId = user.Id;
            }

            return(tokenDto);
        }
Ejemplo n.º 3
0
        public void AltranController_Authenticate_ExistingEmails_ReturnsAuthenticationToken()
        {
            //Arrange
            var mapper = ArrangeProvider.GetMapper();

            var email = ArrangeProvider._EMAIL_;

            var token = new AuthenticationTokenDto
            {
                Email = ArrangeProvider._EMAIL_,
                Role  = Role.Admin,
                Token = "Token"
            };

            var mockClientService = new Mock <IClientsService>();

            mockClientService.Setup(x => x.Authenticate(email)).Returns(token);

            var mockPolicyService = new Mock <IPoliciesService>();

            var controller = new AltranController(mockClientService.Object, mockPolicyService.Object);

            // Act
            var actionResult = controller.Authenticate(email);

            //Assert
            var result = actionResult.Result as OkObjectResult;

            Assert.IsNotNull(result);
            Assert.AreEqual(token.Email, ((result.Value) as AuthenticationTokenDto).Email);
            Assert.AreEqual(token.Role, ((result.Value) as AuthenticationTokenDto).Role);
            Assert.AreEqual(token.Token, ((result.Value) as AuthenticationTokenDto).Token);
        }
Ejemplo n.º 4
0
        public async Task SignIn(string login, string password)
        {
            string jsonRequest = serializer.Serialize(new { login = login, password = password });
            string requestUri  = Properties.Resources.UrlToServer + "Account/SignIn";

            try
            {
                var responseMessage = await client.PostAsync(requestUri, new StringContent(jsonRequest, Encoding.UTF8, "application/json"));

                if (responseMessage.IsSuccessStatusCode)
                {
                    string jsonResult = await responseMessage.Content.ReadAsStringAsync();

                    AuthenticationToken = serializer.Deserialize <AuthenticationTokenDto>(jsonResult);
                }
            }
            catch (HttpRequestException ex)
            {
                if (!NetworkInterface.GetIsNetworkAvailable())
                {
                    throw new NoInternetConnectionException("No internet connection, please try again later.");
                }
                throw ex;
            }
        }
        /// <summary>
        ///
        /// CreateToken
        ///
        /// Creates a new Authentiaction Token and saves it in the Database and return it to the user
        ///
        /// </summary>
        /// <para>
        /// @author: Ahmed Sadiq, Brian Fann, Rachel Dang
        /// @updated: 4/26/18
        /// </para>
        /// <param name="loginDto"></param>
        /// <returns>
        /// Response with the AuthenticationTokenDto
        /// </returns>
        public ResponseDto <AuthenticationTokenDto> CreateToken(string username)
        {
            var tokenHandler        = new JwtSecurityTokenHandler();
            var authenticationToken = new AuthenticationToken();
            var salt = new SaltGenerator().GenerateSalt(128);

            // Creating the Header of the Token
            var key = new SymmetricSecurityKey(Encoding.Default.GetBytes(salt));
            var signingCredentials = new SigningCredentials(key, "HS256");

            authenticationToken.Salt = salt;

            // Assigning the Username to the Token
            authenticationToken.Username = username;

            // Time Stamping the Token
            var issuedOn = DateTime.UtcNow;

            authenticationToken.ExpiresOn = issuedOn.AddMinutes(15);

            // Create claims identity with "Read" permisison claims
            var claimsIdentity = CreateClaimsIdentity(username).Data;

            // Creating the Body of the token
            var tokenDescription = new SecurityTokenDescriptor
            {
                Subject            = claimsIdentity,
                Audience           = AuthenticationTokenConstants.AUDIENCE,
                IssuedAt           = issuedOn,
                Expires            = authenticationToken.ExpiresOn,
                Issuer             = AuthenticationTokenConstants.ISSUER,
                SigningCredentials = signingCredentials,
            };

            // Changing the Token to a String Form
            var token       = tokenHandler.CreateToken(tokenDescription);
            var tokenString = tokenHandler.WriteToken(token);

            authenticationToken.TokenString = tokenString;

            // Storing the Token to the Database
            using (var authenticationGateway = new AuthenticationGateway())
            {
                authenticationGateway.StoreAuthenticationToken(authenticationToken);
            }

            // Assigning the Token to a Dto to return it back to the User
            var authenticationTokenDto = new AuthenticationTokenDto(authenticationToken.Username,
                                                                    authenticationToken.ExpiresOn, authenticationToken.TokenString);

            // Returning the Token to the Controler
            return(new ResponseDto <AuthenticationTokenDto>
            {
                Data = authenticationTokenDto
            });
        }
        /// <summary>
        ///
        /// RevokeToken
        ///
        /// Ends the duration of the token before its Experation time
        ///
        /// </summary>
        /// <param name="authenticationTokenDto"></param>
        /// <returns>
        /// Response with the message of session ending successfully
        /// </returns>
        public ResponseDto <AuthenticationTokenDto> RevokeToken(AuthenticationTokenDto authenticationTokenDto)
        {
            var authenticationTokenPreLogicValidationStrategy =
                new AuthenticationTokenPreLogicValidationStrategy(authenticationTokenDto);

            // Checking if the Dto has all the information it needs
            var validateAuthenticationTokenDtoResult = authenticationTokenPreLogicValidationStrategy.ExcuteStrategy();

            if (validateAuthenticationTokenDtoResult.Error != null)
            {
                return(new ResponseDto <AuthenticationTokenDto>
                {
                    Data = authenticationTokenDto,
                    Error = validateAuthenticationTokenDtoResult.Error
                });
            }

            // Changing the Experiation time on the Token
            authenticationTokenDto.ExpiresOn = DateTime.UtcNow; // Set this to the past

            // Creating the Model to save in the DB
            var incomingAuthenticationToken = new AuthenticationToken(authenticationTokenDto.Username, authenticationTokenDto.ExpiresOn, authenticationTokenDto.TokenString);

            // Validating the Model after creation
            var authenticationTokenPostLogicValidationStrategy =
                new AuthenticationTokenPostLogicValidationStrategy(incomingAuthenticationToken);
            var validateAutenticationTokenResult = authenticationTokenPostLogicValidationStrategy.ExcuteStrategy();

            if (!validateAutenticationTokenResult)
            {
                return(new ResponseDto <AuthenticationTokenDto>
                {
                    Data = authenticationTokenDto,
                    Error = GeneralErrorMessages.GENERAL_ERROR
                });
            }

            // Updating the Token on the Database
            using (var authenticationGateway = new AuthenticationGateway())
            {
                authenticationGateway.StoreAuthenticationToken(incomingAuthenticationToken);
            }

            // Returning a message that everything went fine
            return(new ResponseDto <AuthenticationTokenDto>
            {
                Data = authenticationTokenDto,
            });
        }
Ejemplo n.º 7
0
        public object BeforeCall(string operationName, object[] inputs)
        {
            AuthenticationTokenDto authToken = HttpContext.Current.GetToken();

            if (authToken == null)
            {
                throw new WebFaultException <string>("Unauthorized", HttpStatusCode.Unauthorized);
            }

            User user = unitOfWork.UserRepository.GetItemsList().FirstOrDefault(us => us.Login == authToken.Login);

            if (user == null)
            {
                throw new WebFaultException <string>("Unauthorized", HttpStatusCode.Unauthorized);
            }
            else
            {
                if (!user.AuthenticationToken.Token.Equals(authToken.Token))
                {
                    throw new WebFaultException <string>("Unauthorized", HttpStatusCode.Unauthorized);
                }

                if (roles != null)
                {
                    bool isInRole = false;
                    foreach (var role in roles)
                    {
                        if (role == (RankDto)user.Rank)
                        {
                            isInRole = true;
                            break;
                        }
                    }

                    if (!isInRole)
                    {
                        throw new FaultException("This user is not a member of these roles");
                    }
                }
            }

            return(null);
        }
Ejemplo n.º 8
0
        public IHttpActionResult LogoutUserUser(HttpRequestMessage request)
        {
            try
            {
                AuthenticationTokenManager tokenManager = new AuthenticationTokenManager();
                TokenService tokenService = new TokenService();


                var tokenString = tokenService.ExtractToken(request);
                if (string.IsNullOrEmpty(tokenString))
                {
                    return(BadRequest(GeneralErrorMessages.GENERAL_ERROR));
                }

                var username = tokenService.GetTokenUsername(tokenString);
                if (string.IsNullOrEmpty(username))
                {
                    return(BadRequest(GeneralErrorMessages.GENERAL_ERROR));
                }

                AuthenticationTokenDto tokenDto = new AuthenticationTokenDto(username, tokenString);

                var revokeTokenResponse = tokenManager.RevokeToken(tokenDto);

                if (revokeTokenResponse.Error != null)
                {
                    return(BadRequest(GeneralErrorMessages.GENERAL_ERROR));
                }

                return(Ok());
            }
            catch (Exception)
            {
                return(InternalServerError());
            }
        }