예제 #1
0
        public async Task <ActionResult> Register(CustomRegisterUser registerUser)
        {
            var user = new MyIdentityUser
            {
                UserName       = registerUser.Name,
                Email          = registerUser.Email,
                EmailConfirmed = true
            };

            var result = await _userManager.CreateAsync(user, registerUser.Password);


            if (result.Succeeded)
            {
                await _userManager.AddToRoleAsync(user, Roles.BASIC);

                await _userManager.AddClaimAsync(user, new Claim(Claims.Sample, ClaimsValues.READ));

                await _userManager.AddClaimAsync(user, new Claim(Claims.Sample, ClaimsValues.WRITE));

                return(Ok(createToken(user.UserName)));
            }
            else
            {
                var error = new BadRequestError();
                foreach (var item in result.Errors)
                {
                    error.AddMessage(item.Description);
                }
                var json = ErrorFormat.SerializeError(ModelState, error);
                return(BadRequest(json));
            }
        }
예제 #2
0
        public async Task <ActionResult> ResetAcessTokenPassword(ResetTokenPasswordModel model, [FromServices] IMemoryCache cache)
        {
            string jsonError = ErrorFormat.SerializeError(new BadRequestError("Invalid reset credentiais"));
            var    user      = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(BadRequest(jsonError));
            }

            var lockoutEndDate = await _userManager.GetLockoutEndDateAsync(user);

            if (lockoutEndDate > DateTimeOffset.Now)
            {
                return(BadRequest(ErrorFormat.SerializeError(new BadRequestError("Too many attempts to reset. Wait a few minutes and try again"))));
            }

            var token = cache.Get(model.Code) as string;

            if (token == null)
            {
                var time = DateTimeOffset.Now.AddSeconds(30);
                await _userManager.SetLockoutEndDateAsync(user, time);

                var error = new BadRequestError();
                return(BadRequest(jsonError));
            }
            //await _userManager.ResetPasswordAsync(user, token, model.Password);
            return(Ok(new ResetAcessTokenPasswordModel(token)));
        }
예제 #3
0
        public async Task <IHttpActionResult> Register(UserCreateModel model)
        {
            if (await validationService.CheckExistingUsernameAsync(RequestContext.Principal, model.Username))
            {
                return(Content(HttpStatusCode.Conflict,
                               new
                {
                    Message = "Operation is impossible",
                    Errors = new List <string> {
                        "User with this name already exists"
                    }
                }));
            }

            IdentityResult result = await userService.CreateAsync(model);

            if (result.Errors.Count() > 0)
            {
                var badRequestError = new BadRequestError();
                badRequestError.AddErrors(result.Errors);

                return(Content(HttpStatusCode.BadRequest,
                               new {
                    Message = "Bad Request",
                    ModelErrors = new Dictionary <string, BadRequestError>()
                    {
                        { "", badRequestError }
                    },
                    Errors = new List <string>()
                }));
            }

            return(StatusCode(HttpStatusCode.NoContent));
        }
예제 #4
0
 private IActionResult PrepareFailureResult(ErrorBase error)
 {
     return(error switch
     {
         BadRequestError _ => BadRequest(error),
         AuthorizationError _ => Unauthorized(error),
         DataNotFoundError _ => NotFound(error),
         _ => StatusCode(StatusCodes.Status500InternalServerError)
     });
예제 #5
0
        public void ConstructorBuildsErrorDictionary()
        {
            var modelState = new ModelStateDictionary();

            modelState.AddModelError("Prop", "Some Error");

            var subject = new BadRequestError(modelState);

            Assert.That(subject.PropertyErrors, Contains.Key("Prop"));
            Assert.That(subject.PropertyErrors["Prop"].First(), Is.EqualTo("Some Error"));
        }
예제 #6
0
        public IActionResult BadRequestTest3()
        {
            var innermostTestEx = new ApplicationException("Innermost Test Exception");

            var innertestEx = new ApplicationException("Inner Test Exception", innermostTestEx);

            var testEx = new ApplicationException("Test Exception - Exception Only", innertestEx);

            var badRequestError = new BadRequestError(testEx);

            return(BadRequest(badRequestError));
        }
예제 #7
0
        public IActionResult BadRequestTest2()
        {
            var innermostTestEx = new ApplicationException("Innermost Test Exception");

            var innertestEx = new ApplicationException("Inner Test Exception", innermostTestEx);

            var testEx = new ApplicationException("Test Exception", innertestEx);

            var badRequestError = new BadRequestError($"{_hits} - {AppInfo.ApplicationName} - {AppInfo.EnvironmentName} - Bad Reuqest Test 2 - Message & Exception - {DateTime.Now}", testEx);

            return(BadRequest(badRequestError));
        }
예제 #8
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ModelState.IsValid)
            {
                return;
            }
            log.LogWarning("Bad request: {@ModelState}", context.ModelState);
            var response = new BadRequestError(context.ModelState)
            {
                CorrelationId = correlationCtx?.CorrelationContext?.CorrelationId
            };

            context.Result = new BadRequestObjectResult(response);
        }
        /// <summary>
        /// Tries to format the Error from the Server to a <see cref="BadRequestError"/>
        /// to be displayed to the User
        /// </summary>
        /// <param name="obj">
        /// The error Object returned from the server
        /// </param>
        private void ThrowExceptionMessage(object obj)
        {
            var data      = obj.ToString();
            var processed = false;

            BadRequestError badError = null;

            try
            {
                badError  = Newtonsoft.Json.JsonConvert.DeserializeObject <BadRequestError>(data);
                processed = true;
            }
            catch { }

            if (processed)
            {
                throw new Exception(badError.GetErrorMessage());
            }
        }
예제 #10
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            // When you have specifics configurations (see inside this method)
            services.AddCustomIdentityConfiguration(Configuration);

            services.AddDistributedRedisCache(options =>
            {
                options.Configuration =
                    Configuration.GetConnectionString("ConexaoRedis");
                options.InstanceName = "APICotacoes-";
            });

            services.AddMemoryCache();

            services.Configure <ApiBehaviorOptions>(options =>
            {
                options.InvalidModelStateResponseFactory = context =>
                {
                    var errors   = context.ModelState.Values.SelectMany(e => e.Errors);
                    var apiError = new BadRequestError();

                    foreach (var error in errors)
                    {
                        apiError.AddMessage(error.ErrorMessage);
                    }

                    string json = JsonConvert.SerializeObject(apiError, Formatting.Indented);
                    var result  = new BadRequestObjectResult(json);
                    result.ContentTypes.Clear();
                    return(result);
                };
            });


            services.AddAspNetUserConfiguration();

            services.AddSwaggerConfiguration();

            services.AddDependencyInjectionConfiguration(Configuration);
        }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await next(context);
            }
            catch (Exception ex)
            {
                var    statusCode = GetHttpStatusCodeFromExceptionType(ex);
                object result;

                if (ex is CoreException)
                {
                    logger.LogInformation(ex, ex.Message);

                    result = new BadRequestError(ex as CoreException);
                }
                else
                {
                    var internalServerError = new InternalServerError(ex);

                    if (ex is AggregateException)
                    {
                        foreach (var inner in (ex as AggregateException).InnerExceptions)
                        {
                            logger.LogError(inner, $"An aggregate internal error occurred [LogId:{internalServerError.LogId}].", internalServerError.LogId);
                        }
                    }
                    else
                    {
                        logger.LogError(ex, $"An internal error occurred [LogId:{internalServerError.LogId}].", internalServerError.LogId);
                    }

                    result = internalServerError;
                }

                context.Response.ContentType = "application/json";
                context.Response.StatusCode  = (int)statusCode;

                await context.Response.WriteAsync(JsonConvert.SerializeObject(result, new GeneralJsonSerializerSettings()));
            }
        }
예제 #12
0
        public async Task <ActionResult> ResetPassword(ResetPasswordModel model, [FromServices] IMemoryCache cache)
        {
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                return(BadRequest(ErrorFormat.SerializeError(new BadRequestError("Invalid reset credentiais"))));
            }

            var result = await _userManager.ResetPasswordAsync(user, model.Token, model.Password);

            if (!result.Succeeded)
            {
                var error = new BadRequestError();
                foreach (var item in result.Errors)
                {
                    error.AddMessage(item.Description);
                }
                var json = ErrorFormat.SerializeError(ModelState, error);
                return(BadRequest(json));
            }

            return(Ok("Ok"));
        }
예제 #13
0
 public static IActionResult BadRequestCustom(this Controller controller, BadRequestError error)
 {
     return(controller.BadRequest(error.ToString()));
 }
 public ExceptionFromServicesException(HttpStatusCode httpStatusCode, BadRequestError badRequestError) : this(httpStatusCode)
 {
     BadRequestError = badRequestError;
 }
예제 #15
0
 public BadRequestException(string message, BadRequestError err)
     : base(message)
 {
     ErrorDetails = err;
 }
예제 #16
0
 /// <summary>
 /// Creates a new <see cref="BadRequestException"/>.
 /// </summary>
 /// <param name="request">The original request.</param>
 /// <param name="response">The response.</param>
 /// <param name="error">The error.</param>
 /// <exception cref="ArgumentNullException"><paramref name="request"/> or <paramref name="response"/> is <c>null</c>.</exception>
 public BadRequestException(IWebApiRequest request, IWebApiResponse <ErrorObject> response, BadRequestError error) :
     base(request, response, response?.Content.Message ?? string.Empty)
 {
     this.BadRequestError = error;
 }
예제 #17
0
 public BadRequestException(BadRequestError err)
 {
     ErrorDetails = err;
 }
예제 #18
0
        public async Task <String> DoCall()
        {
            this.checkFilter();
            int retries = isIdempotent ? 1 : 0;

            for (int attempt = 0; attempt <= retries; attempt++)
            {
                using (var client = new HttpClient())
                {
                    HttpResponseMessage response = null;
                    try
                    {
                        if (bodyParams.Count > 0)
                        {
                            // POST
                            var formUrlEncodedContent = new FormUrlEncodedContent(bodyParams);
                            response = await client.PostAsync(url, formUrlEncodedContent);
                        }
                        else
                        {
                            // GET
                            response = await client.GetAsync(url);
                        }
                    }
                    catch (Exception e)
                    {
                        if (attempt < retries)
                        {
                            // retry
                            continue;
                        }
                        else
                        {
                            throw e;
                        }
                    }

                    if (response.IsSuccessStatusCode)
                    {
                        // OK
                        var content = await response.Content.ReadAsStringAsync();

                        return(content);
                    }
                    else if (((int)response.StatusCode) == 404)
                    {
                        // not found
                        throw new ResourceNotFoundException();
                    }
                    else if (((int)response.StatusCode) == 400)
                    {
                        // business error (bad request)
                        string txt = await response.Content.ReadAsStringAsync();

                        BadRequestError err = BadRequestError.FromJson(txt);
                        throw new BadRequestException("Bad request", err);
                    }
                    else if (((int)response.StatusCode) == 500 && attempt < retries)
                    {
                        // technical error, retry
                        continue;
                    }
                    else
                    {
                        throw new TechnicalException("HTTP Error from REST API: " + response.StatusCode);
                    }
                }
            }

            // unreachable
            return(null);
        }
 public AddContactPayload(BadRequestError error)
     : base(new[] { error })
 {
 }
예제 #20
0
 public AddUserPayload(BadRequestError error)
     : base(new[] { error })
 {
 }
예제 #21
0
        public IActionResult BadRequestTest1()
        {
            var badRequestError = new BadRequestError($"{_hits} - {AppInfo.ApplicationName} - {AppInfo.EnvironmentName} - Bad Reuqest Test 1 - Message Only - {DateTime.Now}");

            return(BadRequest(badRequestError));
        }