kreta/KretaWeb/Areas/Adminisztracio/Controllers/LoginController.cs
2024-03-13 00:33:46 +01:00

287 lines
11 KiB
C#

using System;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Kreta.BusinessLogic.Classes;
using Kreta.BusinessLogic.Helpers;
using Kreta.BusinessLogic.Helpers.SystemSettings;
using Kreta.BusinessLogic.Utils;
using Kreta.Core;
using Kreta.Core.FeatureToggle;
using Kreta.Enums.ManualEnums;
using Kreta.Framework;
using Kreta.Framework.Security;
using Kreta.Resources;
using Kreta.Web.Areas.Adminisztracio.Models;
using Kreta.Web.Classes;
using Kreta.Web.Configuration;
using Kreta.Web.Controllers.Logic;
using Kreta.Web.Helpers;
using Kreta.Web.Helpers.ReCaptcha;
using Kreta.Web.Models.EditorTemplates;
using Kreta.Web.Security;
namespace Kreta.Web.Areas.Adminisztracio.Controllers
{
[AllowAnonymous]
public class LoginController : Controller
{
private IIdpConfiguration IdpConfiguration { get; }
private IFeatureContext FeatureContext { get; }
public LoginController(IIdpConfiguration idpConfiguration, IFeatureContext featureContext)
{
IdpConfiguration = idpConfiguration ?? throw new ArgumentNullException(nameof(idpConfiguration));
FeatureContext = featureContext ?? throw new ArgumentNullException(nameof(featureContext));
}
public ActionResult Index()
{
if (IdpConfiguration.LoginEnabled)
{
return RedirectToAction("Index", "Home", new { Area = string.Empty });
}
var model = BuildModel();
var mainVersion = KretaVersion.Instance.MainVersion;
var assemblyCreationDate = KretaVersion.Instance.AssemblyCreationDateTime.ToShortDateString();
var commitNumber = KretaVersion.Instance.CommitNumber;
var nextUpdateDateTimeText = new AdminHelper(ConnectionTypeExtensions.GetOrganizationConnectionType()).GetKovTelepitesDatum().ToString("yyyy.MM.dd. HH:mm");
ViewBag.Version = $"{CommonResource.Version}: {mainVersion} ({assemblyCreationDate}) <br/> {commitNumber}";
ViewBag.NextUpdateDateTimeText = nextUpdateDateTimeText;
LogOut();
return View(model);
}
public ActionResult LostPasswordPopUp()
{
var popUpModel = new PopUpModel(new LostPasswordModel(), "LostPasswordPopUp");
popUpModel = popUpModel.AddCancelBtn(popUpModel, "KretaWindowHelper.destroyAllWindow");
popUpModel = popUpModel.AddOkBtn(popUpModel, "LoginHelper.requestNewPassword");
return PartialView(Constants.General.PopupView, popUpModel);
}
public ActionResult PasswordReset(LostPasswordModel model)
{
var result = Content(ErrorResource.AzUjJelszotElkuldtukAMegadottEmailCimre);
return result;
}
private const string ErrorCodeAccountError = "AccountError";
public ActionResult LoginCheck(LoginModel model)
{
if (IdpConfiguration.LoginEnabled)
{
return HttpNotFound();
}
LogOut();
LoginInfo loginInfo = null;
bool isAccountOk;
if (!new IntezmenyHelper(ConnectionTypeExtensions.GetOrganizationConnectionType()).IsSuccessAuthorizedDate())
{
return LoginResult(success: false, AdminisztracioResource.TelepitesMiattBelepesNemLehetseges, ErrorCodeAccountError, string.Empty);
}
if (string.IsNullOrWhiteSpace(model.UserName))
{
return LoginResult(success: false, ErrorResource.AFelhasznalonevMegadasaKotelezo, ErrorCodeAccountError, string.Empty);
}
//recaptcha validation
if (model.ReCaptchaIsEnabled)
{
var captcha = ReCaptchaValidator.Validate(model.ReCaptcha);
if (!captcha.Success)
{
return LoginResult(success: false, ErrorResource.ABelepeshezACaptchaKozetelezo, ErrorCodeAccountError, string.Empty);
}
}
//NOTE: Account lekérdezése
try
{
using (var loginManager = new LoginManager())
{
loginInfo = loginManager.CheckLogin(model.UserName.Trim(), model.Password, GetClientIP());
isAccountOk = loginInfo != null;
if (isAccountOk && !loginInfo.IsDeniedArchivIntezmenyUser)
{
throw new ArchivBelepesException("-");
}
}
}
catch (SecurityException)
{
isAccountOk = false;
}
catch (DataIntegrityException)
{
isAccountOk = false;
}
catch (NextTanevBelepesException)
{
return LoginResult(success: false, ErrorResource.KovTanevBelepesError, ErrorCodeAccountError, string.Empty);
}
catch (ArchivBelepesException)
{
return LoginResult(success: false, ErrorResource.ArchivBelepesError, ErrorCodeAccountError, string.Empty);
}
catch (Exception ex)
{
SDAServer.Instance.Logger.ExceptionThrown(ex);
return LoginResult(success: false, ErrorResource.IsmeretlenHibaTortent, ErrorCodeAccountError, string.Empty);
}
//NOTE: Ha nem jók a bejelentkezési adatok
if (!isAccountOk || loginInfo.PasswordState == PasswordState.INVALID)
{
return LoginResult(success: false, ErrorResource.HibasFelhasznalonevVagyJelszo, ErrorCodeAccountError, string.Empty, loginInfo?.MeghiusultBelepes);
}
if (loginInfo.IsDeniedSzirIntezmenyUser)
{
return LoginResult(success: false, ErrorResource.HibasFelhasznalonevVagyJelszo, ErrorCodeAccountError, string.Empty, loginInfo.MeghiusultBelepes);
}
//NOTE: Végleges login
var isLoginSuccess = Login(loginInfo, out var loginMessageString);
if (HttpContext.Request.Headers.AllKeys.Contains(nameof(KliensTipusEnum.Mobile), StringComparer.Ordinal))
{
ClaimData.KliensTipusa = KliensTipusEnum.Mobile;
}
// Dashboard popup üzenetekhez:
var popupCookie = new HttpCookie("DisplayedPopups")
{
HttpOnly = true,
SameSite = SameSiteMode.None,
Secure = true
};
HttpContext.Response.Cookies.Add(popupCookie);
return LoginResult(isLoginSuccess, isLoginSuccess ? ErrorResource.SikeresBejelentkezes : loginMessageString, isLoginSuccess ? "Ok" : ErrorCodeAccountError, string.Empty, loginInfo.MeghiusultBelepes);
}
public void LogOut()
{
MasterLayoutLogic.LogOut();
}
public ActionResult ChangeLanguage(int id)
{
ClaimData.LCID = id;
return RedirectToAction("Index");
}
private LoginModel BuildModel()
{
var connectionType = ConnectionTypeExtensions.GetOrganizationConnectionType();
var dsDashboard = CommonUtils.GetLoginDashboardUzenet(connectionType);
var csokkentettGondviseloEnable = new SystemSettingsHelper(connectionType).GetSystemSettingValue<bool>(Enums.RendszerBeallitasTipusEnum.Csokkentett_gondviselok_kezelese);
var ds = new IntezmenyHelper(connectionType).GetOrganizationNameAndCode();
var model = new LoginModel
{
IntezmenyNeve = ds.Tables[0].Rows[0][0].ToString(),
IntezmenyOMkod = ds.Tables[0].Rows[0][1].ToString(),
LejartLicence = string.Equals(ds.Tables[0].Rows[0][2].ToString(), "T", StringComparison.OrdinalIgnoreCase),
NextUpdateHeader = dsDashboard.Tables[0].Rows[0]["C_CIM"].ToString(),
NextUpdateMessage = dsDashboard.Tables[0].Rows[0]["C_TARTALOM"].ToString(),
CsokkentettGondviseloEnable = csokkentettGondviseloEnable,
IsSzirIntezmeny = ds.Tables[0].Rows[0].Field<bool>("IsSzirIntezmeny_BOOL"),
IsArchivIntezmeny = ds.Tables[0].Rows[0].Field<bool>("IsArchivIntezmeny_BOOL"),
IdpLogoutUrl = IdpConfiguration.LogoutUrl,
ReCaptchaIsEnabled = false
};
return model;
}
private JsonResult LoginResult(bool success, string errorMessage, string errorCode, string warningMessage, int? failedLoginCounter = 0)
{
var result = Json(new LoginResultModel { Success = success, ErrorMessage = errorMessage, ErrorCode = errorCode, WarningMessage = warningMessage, FailedLoginCounter = failedLoginCounter });
return result;
}
private bool Login(LoginInfo loginInfo, out string loginMessageString)
{
loginMessageString = string.Empty;
try
{
using (var loginManager = new LoginManager())
{
loginInfo = loginManager.Login(loginInfo);
}
}
catch (SecurityException)
{
if (ApplicationData.KretaDebug)
{
throw;
}
loginMessageString = ErrorResource.HibasFelhasznalonevVagyJelszo;
return false;
}
catch (DataIntegrityException)
{
if (ApplicationData.KretaDebug)
{
throw;
}
loginMessageString = ErrorResource.NemLetezikAFelhasznalohozJelszo;
return false;
}
catch (Exception ex)
{
if (ApplicationData.KretaDebug)
{
throw;
}
SDAServer.Instance.Logger.ExceptionThrown(ex);
loginMessageString = ErrorResource.IsmeretlenHibaTortent;
return false;
}
//NOTE: Ha nem sikerült bejelentkeznie
if (loginInfo == null)
{
loginMessageString = ErrorResource.HibasFelhasznalonevVagyJelszo;
return false;
}
return true;
}
private string GetClientIP()
{
var clientIp = HttpContext.Request.UserHostAddress.Trim();
try
{
var xForwardedFor = HttpContext.Request.Headers["X-Forwarded-For"];
if (!string.IsNullOrWhiteSpace(xForwardedFor))
{
clientIp = xForwardedFor;
}
return clientIp;
}
catch
{
return clientIp;
}
}
}
}