public static void HandleBadRequest(this Controller controller, ApiBadRequestException apiBadRequestException) { if (apiBadRequestException.BadRequestData.ModelState != null) { foreach (var modelStateItem in apiBadRequestException.BadRequestData.ModelState) { foreach (var message in modelStateItem.Value) { controller.ModelState.AddModelError(modelStateItem.Key, message); } } } if (string.Equals(apiBadRequestException.BadRequestData.Error, "invalid_grant")) { controller.ModelState.AddModelError(string.Empty, apiBadRequestException.BadRequestData.ErrorDescription); } }
private static Task HandleExceptionAsync(HttpContext context, Exception ex) { var code = ex switch { ApiNotFoundException _ => HttpStatusCode.NotFound, ApiUnauthorizedException _ => HttpStatusCode.Unauthorized, ApiBadRequestException _ => HttpStatusCode.BadRequest, ApiTunerNotAvailableException _ => HttpStatusCode.ServiceUnavailable, _ => HttpStatusCode.InternalServerError }; var result = JsonConvert.SerializeObject(new { error = ex.Message }); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)code; return(context.Response.WriteAsync(result)); } }
/// <summary> /// Logs in a user by creating a new token for them if the credentials are valid. /// </summary> /// <param name="account">The user supplied credentials</param> /// <returns>The newly created token.</returns> /// <exception cref="ArgumentNullException"><paramref name="account"/> is <c>null</c>.</exception> /// <exception cref="ApiBadRequestException"><paramref name="account"/> was not found in the database.</exception> public string LoginUser(Account account) { if (account == null) { _logger.LogError("Tried to login with account NULL"); throw new ArgumentNullException(); } try { using (var dbConnection = new MySqlConnection(_sqlConnectionString)) { dbConnection.Open(); var selectCommand = new MySqlCommand( $"SELECT 1 FROM {_sqlTableName} WHERE BENUTZERNAME=@username AND PASSWORT=@password", dbConnection); //selectCommand.Prepare(); selectCommand.Parameters.AddWithValue("@username", account.Username); selectCommand.Parameters.AddWithValue("@password", account.Password); var reader = selectCommand.ExecuteReader(); if (!reader.HasRows) { var ex = new ApiBadRequestException("Username or password invalid."); _logger.LogTrace(ex, ex.Message); throw ex; } var newToken = GenerateBase64Token(); _tokenDictionary.Add(newToken, new AuthTokenInformation(account.Username)); dbConnection.Close(); return(newToken); } } catch (MySqlException mySqlException) { _logger.LogError(mySqlException, "Failed to fill dataset from MySQL database for login."); throw; } }
public async void HttpPost_ResetPassword_ModelIsValid_PasswordResetThrowsApiBadRequestExceptionWithModelErrors_ReturnsViewWithModel_AndErrorAddedToModelState() { // Arrange Dictionary <string, ICollection <string> > modelState = new Dictionary <string, ICollection <string> > { { "A Key", new List <string> { "Something wen't wrong" } } }; ApiBadRequestException badRequestException = new ApiBadRequestException(HttpStatusCode.BadRequest, new ApiBadRequest { ModelState = modelState }); IUnauthenticatedUser unauthenticatedUserClient = A.Fake <IUnauthenticatedUser>(); A.CallTo(() => unauthenticatedUserClient.ResetPasswordAsync(A <PasswordResetData> ._, A <string> ._)) .Throws(badRequestException); A.CallTo(() => apiClient.User) .Returns(unauthenticatedUserClient); AccountController controller = AccountController(); ResetPasswordModel passwordResetModel = new ResetPasswordModel(); // Act ActionResult result = await controller.ResetPassword(A.Dummy <Guid>(), A.Dummy <string>(), passwordResetModel); // Assert Assert.IsType <ViewResult>(result); Assert.Equal(passwordResetModel, ((ViewResult)result).Model); Assert.Single(controller.ModelState.Values); Assert.Single(controller.ModelState.Values.Single().Errors); Assert.Contains("Something wen't wrong", controller.ModelState.Values.Single().Errors.Single().ErrorMessage); }
public async void HttpPost_ResetPassword_ModelIsValid_PasswordResetThrowsApiBadRequestExceptionWithModelErrors_ReturnsViewWithModel_AndErrorAddedToModelState() { // Arrange Dictionary<string, ICollection<string>> modelState = new Dictionary<string, ICollection<string>> { { "A Key", new List<string> { "Something wen't wrong" } } }; ApiBadRequestException badRequestException = new ApiBadRequestException(HttpStatusCode.BadRequest, new ApiBadRequest { ModelState = modelState }); IUnauthenticatedUser unauthenticatedUserClient = A.Fake<IUnauthenticatedUser>(); A.CallTo(() => unauthenticatedUserClient.ResetPasswordAsync(A<PasswordResetData>._)) .Throws(badRequestException); A.CallTo(() => apiClient.User) .Returns(unauthenticatedUserClient); AccountController controller = AccountController(); ResetPasswordModel passwordResetModel = new ResetPasswordModel(); // Act ActionResult result = await controller.ResetPassword(A.Dummy<Guid>(), A.Dummy<string>(), passwordResetModel); // Assert Assert.IsType<ViewResult>(result); Assert.Equal(passwordResetModel, ((ViewResult)result).Model); Assert.Single(controller.ModelState.Values); Assert.Single(controller.ModelState.Values.Single().Errors); Assert.Contains("Something wen't wrong", controller.ModelState.Values.Single().Errors.Single().ErrorMessage); }