Exemplo n.º 1
0
        public HttpResponseMessage Create(TaskCreateApiModel apiModel)
        {
            var                  response              = new HttpResponseMessage();
            ResponseFormat       responseData          = new ResponseFormat();
            AuthorizationService _authorizationService = new AuthorizationService().SetPerm((int)EnumPermissions.TASK_CREATE);
            //read jwt

            IEnumerable <string> headerValues;

            if (Request.Headers.TryGetValues("Authorization", out headerValues))
            {
                string jwt = headerValues.FirstOrDefault();
                //validate jwt
                var payload = JwtTokenManager.ValidateJwtToken(jwt);

                if (payload.ContainsKey("error"))
                {
                    if ((string)payload["error"] == ErrorMessages.TOKEN_EXPIRED)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_EXPIRED;
                    }
                    if ((string)payload["error"] == ErrorMessages.TOKEN_INVALID)
                    {
                        response.StatusCode  = HttpStatusCode.Unauthorized;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.TOKEN_INVALID;
                    }
                }
                else
                {
                    var userId = payload["id"];

                    var isAuthorized = _authorizationService.Authorize(Convert.ToInt32(userId));
                    if (isAuthorized)
                    {
                        var isCreated = _taskTemplateService.CreateTask(apiModel, Convert.ToInt32(userId));;
                        if (isCreated)
                        {
                            response.StatusCode  = HttpStatusCode.OK;
                            responseData         = ResponseFormat.Success;
                            responseData.message = SuccessMessages.TASK_CREATED;
                        }
                    }
                    else
                    {
                        response.StatusCode  = HttpStatusCode.Forbidden;
                        responseData         = ResponseFormat.Fail;
                        responseData.message = ErrorMessages.UNAUTHORIZED;
                    }
                }
            }
            else
            {
                response.StatusCode  = HttpStatusCode.Unauthorized;
                responseData         = ResponseFormat.Fail;
                responseData.message = ErrorMessages.UNAUTHORIZED;
            }
            var json = JsonConvert.SerializeObject(responseData);

            response.Content = new StringContent(json, Encoding.UTF8, "application/json");
            return(response);
        }