Пример #1
0
        public async Task <JwtDto> SignInAsync(SignIn command)
        {
            if (!EmailRegex.IsMatch(command.Email))
            {
                var exception = new InvalidCredentialsException(command.Email);
                await _messageBroker.PublishAsync(new SignInRejected(command.Email, exception.Message, exception.Code));

                throw exception;
            }

            var user = await _userRepository.GetAsync(command.Email);

            if (user is null || !_passwordService.IsValid(user.Password, command.Password))
            {
                var exception = new InvalidCredentialsException(command.Email);
                await _messageBroker.PublishAsync(new SignInRejected(command.Email, exception.Message, exception.Code));

                throw exception;
            }

            var token = _jwtProvider.Create(user.Id, user.Role);
            await _messageBroker.PublishAsync(new SignedIn(user.Id, user.Role));

            return(token);
        }
Пример #2
0
        public Token RequestToken(IAuthenticationRequest tokenRequest)
        {
            // Check that we're accessing a valid organization from the CrmDiscoveryService Web service.
            if (String.IsNullOrEmpty(tokenRequest.OrganizationName))
            {
                OrganizationDetail orgInfo = GetOrganizationDetail();
                tokenRequest.OrganizationName = orgInfo.OrganizationName;
            }

            // Retrieve a CrmTicket from the CrmDiscoveryService Web service.
            RetrieveCrmTicketResponse crmTicketResponse = GetCrmTicketResponse(tokenRequest);

            if (crmTicketResponse == null)
            {
                // user not found, try default credentials
                IAuthenticationRequest defaultTicketRequest = GetDefaultTicketRequest();
                crmTicketResponse = GetCrmTicketResponse(defaultTicketRequest);
            }

            // user not found at all, throw exception
            if (crmTicketResponse == null)
            {
                InvalidCredentialsException ex = new InvalidCredentialsException();
                ex.Data.Add("Username", tokenRequest.DomainName + @"\" + tokenRequest.Username);
                throw ex;
            }

            CrmAuthenticationToken crmToken = GetCrmAuthenticationToken(tokenRequest, crmTicketResponse);

            return(new Token(crmToken, crmTicketResponse.OrganizationDetail.CrmServiceUrl));
        }
Пример #3
0
        public async Task <JwtDto> SignInAsync(SignIn command)
        {
            if (!EmailRegex.IsMatch(command.Email))
            {
                _logger.LogWarning($"Invalid email address: {command.Email}.");
                var exception = new InvalidCredentialsException(command.Email);
                await _messageBroker.PublishAsync(new SignInRejected(command.Email, exception.Message, exception.Code));

                throw exception;
            }

            var user = await _userRepository.GetAsync(command.Email);

            if (user is null || !_passwordService.IsValid(user.Password, command.Password))
            {
                var exception = new InvalidCredentialsException(command.Email);
                await _messageBroker.PublishAsync(new SignInRejected(command.Email, exception.Message, exception.Code));

                throw exception;
            }

            var token = _jwtProvider.Create(user.Id, user.Role);
            await _messageBroker.PublishAsync(new SignedIn(user.Id, user.Role));

            _logger.LogInformation($"User with id: {user.Id} has been authenticated.");

            return(token);
        }
Пример #4
0
        public async Task signup_endpoint_should_return_error_when_password_is_incorrect()
        {
            var id            = new AggregateId();
            var email         = "*****@*****.**";
            var fullname      = "fullname";
            var password      = "******";
            var wrongPassword = "******";
            var role          = Role.User;
            var securityStamp = new Guid().ToString();

            // Add user
            var user = new User(id, email, fullname, "test.nl/image", _passwordService.Hash(password), role,
                                securityStamp, 0, DateTime.MinValue, DateTime.UtcNow, new string[] { });
            await _mongoDbFixture.InsertAsync(user.AsDocument());

            var request = new SignIn(email, wrongPassword);

            var response = await Act(request);

            response.Should().NotBeNull();
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);

            var content = await response.Content.ReadAsStringAsync();

            var exception = new InvalidCredentialsException(email);

            content.Should().Contain(exception.Code);
        }
        public void InvalidCredentialsExceptionConstructorTest()
        {
            string msg = "TestValue"; // TODO: Initialize to an appropriate value
            InvalidCredentialsException target = new InvalidCredentialsException(msg);

            Assert.IsNotNull(target);
            Assert.AreEqual(msg, target.Message);
        }
Пример #6
0
 public ExceptionResponse Map(Exception ex)
 {
     return(ex switch
     {
         EmailAlreadyInUseException emailAlreadyInUseException => new ExceptionResponse("email_in_use", ex.Message, HttpStatusCode.BadRequest),
         InvalidCredentialsException invalidCredentialsException => new ExceptionResponse("invalid_credentials", ex.Message, HttpStatusCode.BadRequest),
         InvalidEmailException invalidEmailException => new ExceptionResponse("invalid_email", ex.Message, HttpStatusCode.BadRequest),
         ResourceNotFoundException resourceNotFoundException => new ExceptionResponse("not_found", ex.Message, HttpStatusCode.NotFound),
         NameAlreadyExistException nameAlreadyExistException => new ExceptionResponse("name_in_use", ex.Message, HttpStatusCode.BadRequest),
         _ => null
     });
 public object Map(Exception exception, object message)
 {
     return(exception switch
     {
         EmailInUseException ex => new SignedUpRejected(ex.Email, ex.Message, ex.Code),
         InvalidCredentialsException ex => new SignInRejected(ex.Email, ex.Message, ex.Code),
         InvalidEmailException ex => message switch
         {
             SignIn command => new SignInRejected(command.Email, ex.Message, ex.Code),
             SignedUpRejected command => new SignedUpRejected(command.Email, ex.Message, ex.Code),
             _ => null
         },
Пример #8
0
        public override async Task OnExceptionAsync(ExceptionContext context)
        {
            var errorMessage = context.Exception.Message;

            var(statusCode, errorCode) = (HttpStatusCode.InternalServerError, ErrorCodes.ServerError);

            (statusCode, errorCode) = context.Exception switch
            {
                ServerException _ => (HttpStatusCode.InternalServerError, GetErrorCode(context.Exception)),
                CrudException _ => (HttpStatusCode.InternalServerError, GetErrorCode(context.Exception)),
                ResetPasswordException _ => (HttpStatusCode.InternalServerError, GetErrorCode(context.Exception)),
                TokenException _ => (HttpStatusCode.InternalServerError, GetErrorCode(context.Exception)),
                ProfileUpdateException _ => (HttpStatusCode.InternalServerError, GetErrorCode(context.Exception)),
                ChangePasswordException _ => (HttpStatusCode.InternalServerError, GetErrorCode(context.Exception)),
                UploadFileException _ => (HttpStatusCode.InternalServerError, GetErrorCode(context.Exception)),
                DeleteFileException _ => (HttpStatusCode.InternalServerError, GetErrorCode(context.Exception)),
                AdminActionException _ => (HttpStatusCode.InternalServerError, GetErrorCode(context.Exception)),
                HubConnectionException _ => (HttpStatusCode.InternalServerError, GetErrorCode(context.Exception)),

                AuthException _ => (HttpStatusCode.Unauthorized, GetErrorCode(context.Exception)),
                InvalidCredentialsException _ => (HttpStatusCode.Unauthorized, GetErrorCode(context.Exception)),
                AccountNotConfirmedException _ => (HttpStatusCode.Unauthorized, GetErrorCode(context.Exception)),

                EntityNotFoundException _ => (HttpStatusCode.NotFound, GetErrorCode(context.Exception)),

                ServiceException _ => (HttpStatusCode.ServiceUnavailable, GetErrorCode(context.Exception)),

                NoPermissionsException _ => (HttpStatusCode.Forbidden, GetErrorCode(context.Exception)),
                AccountBlockedException _ => (HttpStatusCode.Forbidden, GetErrorCode(context.Exception)),

                DuplicateException _ => (HttpStatusCode.Conflict, GetErrorCode(context.Exception)),

                OldPasswordInvalidException _ => (HttpStatusCode.BadRequest, GetErrorCode(context.Exception)),

                _ => (HttpStatusCode.InternalServerError, ErrorCodes.ServerError)
            };

            var jsonResponse = (new BaseResponse(Error.Build(errorCode, errorMessage, statusCode: statusCode))).ToJSON();

            context.HttpContext.Response.ContentType   = "application/json";
            context.HttpContext.Response.StatusCode    = (int)statusCode;
            context.HttpContext.Response.ContentLength = Encoding.UTF8.GetBytes(jsonResponse).Length;

            context.HttpContext.Response.AddApplicationError(errorMessage);

            await context.HttpContext.Response.WriteAsync(jsonResponse);

            var logger = context.HttpContext.RequestServices.GetService <INLogger>();
            logger.Error(errorMessage, context.Exception);

            await base.OnExceptionAsync(context);
        }
        public IEnumerator Authenticate(string username, string password)
        {
            LastError = null;

            if (Authenticated)
            {
                LastError = new RDataAuthenticationException("Failed to Authenticate - already authenticated. Call Revoke() to Revoke the previous authentication");
                yield break;
            }
            // Send authentication request
            var localAuthRequest = new AuthenticateLocalRequest(username, password);

            yield return(StartCoroutine(_httpClient.Send <AuthenticateLocalRequest, AuthenticateLocalRequest.AuthenticateLocalResponse>(localAuthRequest)));

            if (localAuthRequest.HasError && localAuthRequest.Error is RData.Http.Exceptions.UnauthorizedException)
            {
                LastError = new InvalidCredentialsException(localAuthRequest.Error);
                yield break;
            }

            if (localAuthRequest.HasError)
            {
                LastError = new RDataAuthenticationException(localAuthRequest.Error);
                yield break;
            }

            if (!localAuthRequest.HasResponse)
            {
                LastError = new RDataAuthenticationException("Failed to authenticate, http request failed but has no error");
                yield break;
            }

            // Process the authentication response - build new AuthenticationInfo object
            _authenticationInfo = new AuthenticationInfo();

            _authenticationInfo.accessToken           = localAuthRequest.Response.accessToken;
            _authenticationInfo.refreshToken          = localAuthRequest.Response.refreshToken;
            _authenticationInfo.user                  = localAuthRequest.Response.user;
            _authenticationInfo.refreshTokenExpiresAt = localAuthRequest.Response.refreshTokenExpiresAt;
            _authenticationInfo.accessTokenExpiresAt  = localAuthRequest.Response.accessTokenExpiresAt;

            // Save into player prefs
            SaveToPlayerPrefs();
        }
Пример #10
0
        public async Task signup_endpoint_should_return_error_when_user_does_not_exist()
        {
            var email    = "*****@*****.**";
            var password = "******";


            var request = new SignIn(email, password);

            var response = await Act(request);

            response.Should().NotBeNull();
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);

            var content = await response.Content.ReadAsStringAsync();

            var exception = new InvalidCredentialsException(email);

            content.Should().Contain(exception.Code);
        }
        private static Task HandleExceptionAsync(HttpContext context, System.Exception exception)
        {
            var serializedError = string.Empty;

            var code = exception switch
            {
                NotFoundException _ => HttpStatusCode.NotFound,
                InvalidCredentialsException _ => HttpStatusCode.Unauthorized,
                ConflictException _ => HttpStatusCode.Conflict,
                _ => throw exception,
            };

            if (string.IsNullOrEmpty(serializedError))
            {
                serializedError = JsonConvert.SerializeObject(new { error = exception.Message });
            }

            context.Response.ContentType = "application/json";
            context.Response.StatusCode  = (int)code;
            return(context.Response.WriteAsync(serializedError));
        }
Пример #12
0
 public string[] GetCredentials(InvalidCredentialsException e)
 //throws CanceledOperationException
 {
     Console.WriteLine(e.Message);
     return(PromptForCredentials());
 }
Пример #13
0
 public String[] GetCredentials(InvalidCredentialsException e)
 {
     Console.WriteLine(e.Message);
     return(PromptForCredentials());
 }
        public void InvalidCredentialsExceptionConstructorTest1()
        {
            InvalidCredentialsException target = new InvalidCredentialsException();

            Assert.IsNotNull(target);
        }