using System; using System.Net; using System.Net.Http; using System.Runtime.Caching; using System.Web.Http; using Kreta.BusinessLogic.Helpers; using Kreta.BusinessLogic.Security; using Kreta.Core; using Kreta.Core.KIR.Domain.Model; using Kreta.Core.KIR.Factory.Interface; using Kreta.Resources; using Kreta.Web.Areas.KirImportExport.Models.KirImport; using Kreta.Web.Security; namespace Kreta.Web.Areas.KirImportExport.ApiControllers { [ApiRoleClaimsAuthorize(true)] [ApiRolePackageAuthorize(KretaClaimPackages.Adminisztrator.ClaimValue)] public class KirAuthenticationApiController : ApiController { private const int KirLoginCacheExpirationInMinutes = 5; private IAuthenticationServiceFactory AuthenticationServiceFactory { get; } private string KirAuthHeaderModelCacheKey => $"{ClaimData.FelhasznaloNev}_{ClaimData.FelhasznaloId}_{ClaimData.IntezmenyAzonosito}_KirLogin"; private string KirTokenCacheKey => $"{ClaimData.FelhasznaloNev}_{ClaimData.FelhasznaloId}_{ClaimData.IntezmenyAzonosito}_KirToken"; public KirAuthenticationApiController(IAuthenticationServiceFactory authenticationServiceFactory) { AuthenticationServiceFactory = authenticationServiceFactory ?? throw new ArgumentNullException(nameof(authenticationServiceFactory)); } [HttpPost] [ApiValidateAjaxAntiForgeryToken] public HttpResponseMessage Login(KirLoginModel kirLoginModel) { try { AuthHeaderModel authHeaderModel = new KirAuthenticationHelper(AuthenticationServiceFactory).Authenticate(kirLoginModel); if (!(Cache.Get(KirAuthHeaderModelCacheKey) is AuthHeaderModel)) { Cache.Add(KirAuthHeaderModelCacheKey, authHeaderModel, new CacheItemPolicy { SlidingExpiration = TimeSpan.FromMinutes(KirLoginCacheExpirationInMinutes) }); } if (string.IsNullOrWhiteSpace(Cache.Get(KirTokenCacheKey) as string)) { Cache.Add(KirTokenCacheKey, authHeaderModel.KirToken, new CacheItemPolicy { AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(KirLoginCacheExpirationInMinutes)) }); } return new HttpResponseMessage(HttpStatusCode.OK); } catch (Exception) { return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ErrorResource.NemSikerultABejelentkezesHibasFelhasznalonevVagyJelszo); } } [HttpPost] [ApiValidateAjaxAntiForgeryToken] public HttpResponseMessage KirLoginCheck() { return Cache.Get(KirAuthHeaderModelCacheKey) is AuthHeaderModel ? new HttpResponseMessage(HttpStatusCode.OK) : new HttpResponseMessage(HttpStatusCode.BadRequest); } } }