using BuddyFinance.Common.Encryption; using BuddyFinance.Integration.Models; using BuddyFinance.Integration.Models.Enums; using System; using System.Diagnostics.Contracts; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace BuddyFinance.WebApi.Filters { public class AuthenticateAttribute : AuthorizationFilterAttribute { public override void OnAuthorization(HttpActionContext actionContext) { if (SkipAuthorization(actionContext)) return; BaseResult result = new BaseResult(); var token = System.Web.HttpContext.Current.Request.Headers["X-Auth-Token"]; if (string.IsNullOrWhiteSpace(token)) { result = new BaseResult((int)ResponseCodes.Unauthorized, "Unauthorized"); } else { try { var authCode_ = token.Decrypt(); var split = authCode_.Split('|'); DateTime issueDate = DateTime.Parse(split[1]); TimeSpan validTimespan = TimeSpan.Parse(split[2]); var isValid = DateTime.Now < issueDate.Add(validTimespan); result.ErrorCode = isValid ? (int)ResponseCodes.Success : (int)ResponseCodes.Unauthorized; result.ErrorMessage = isValid ? "Success" : "Unauthorized. Invalid access token"; } catch (System.Exception ex) { result.ErrorCode = (int)ResponseCodes.Unauthorized; result.ErrorMessage = ex.Message + ". Unauthorized"; } } if (result.ErrorCode != (int)ResponseCodes.Success) { var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK) { Content = new ObjectContent>(result, new JsonMediaTypeFormatter()) }; actionContext.Response = response; //new HttpUnauthorizedResult(); } } private static bool SkipAuthorization(HttpActionContext actionContext) { Contract.Assert(actionContext != null); return actionContext.ActionDescriptor.GetCustomAttributes().Any() || actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes().Any(); } } }