PTMagic/Monitor/_Internal/BasePageModelSecure.cs

79 lines
2.2 KiB
C#
Raw Normal View History

2018-05-22 10:11:50 +02:00
using System;
using Microsoft.AspNetCore.Http;
using Core.Main;
using Core.Helper;
namespace Monitor._Internal
{
public class BasePageModelSecure : BasePageModel
{
2021-02-17 18:41:30 +01:00
// The string to redirect to if it fails security
protected string _redirectUrl;
public BasePageModelSecure(string redirect = null)
{
// Configure redirect URL
_redirectUrl = !String.IsNullOrEmpty(redirect) ? redirect : "Login";
}
/// <summary>
/// Must be called from inheritting pages to check security
/// </summary>
public void Init()
{
2021-02-17 18:41:30 +01:00
// Initialise base class
2018-05-22 10:11:50 +02:00
base.PreInit();
2021-02-17 18:41:30 +01:00
// Security check
if (!IsLoggedIn(this.HttpContext))
{
HttpContext.Response.Redirect(PTMagicConfiguration.GeneralSettings.Monitor.RootUrl + _redirectUrl);
}
}
/// <summary>
/// Check to see a user if logged in interactively
/// </summary>
/// <returns>Boolean - User logged in or not</returns>
protected Boolean IsLoggedIn(HttpContext context)
{
bool isLoggedIn = false;
if (PTMagicConfiguration.GeneralSettings.Monitor.IsPasswordProtected)
{
2021-02-17 18:41:30 +01:00
// Do we have a session active?
if (!String.IsNullOrEmpty(context.Session.GetString("LoggedIn" + PTMagicConfiguration.GeneralSettings.Monitor.Port.ToString())))
{
2021-02-17 18:41:30 +01:00
isLoggedIn = true;
}
else
{
// Do we have a auto login cookie?
if (Request.Cookies.ContainsKey("PTMRememberMeKey"))
{
2021-02-17 18:41:30 +01:00
string rememberMeKey = Request.Cookies["PTMRememberMeKey"];
if (!rememberMeKey.Equals(""))
{
2021-02-17 18:41:30 +01:00
string encryptedPassword = EncryptionHelper.Decrypt(Request.Cookies["PTMRememberMeKey"]);
if (encryptedPassword.Equals(PTMagicConfiguration.SecureSettings.MonitorPassword))
{
context.Session.SetString("LoggedIn" + PTMagicConfiguration.GeneralSettings.Monitor.Port.ToString(), DateTime.UtcNow.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'"));
isLoggedIn = true;
}
2018-05-22 10:11:50 +02:00
}
}
}
}
2021-02-17 18:41:30 +01:00
else
{
// No password required
isLoggedIn = true;
}
return isLoggedIn;
2018-05-22 10:11:50 +02:00
}
2021-02-17 18:41:30 +01:00
2018-05-22 10:11:50 +02:00
}
2021-02-17 18:41:30 +01:00
2018-05-22 10:11:50 +02:00
}