2020-02-25 16:08:03 +00:00
|
|
|
using System.Linq;
|
2018-05-01 11:17:59 +00:00
|
|
|
using System.Net.Http;
|
|
|
|
using System.Security.Cryptography;
|
|
|
|
using System.Text;
|
|
|
|
using Jackett.Common.Models.Config;
|
|
|
|
using Jackett.Common.Services.Interfaces;
|
|
|
|
|
2018-05-01 11:41:34 +00:00
|
|
|
namespace Jackett.Server.Services
|
2018-05-01 11:17:59 +00:00
|
|
|
{
|
2021-11-16 13:06:07 +00:00
|
|
|
internal class SecurityService : ISecurityService
|
2018-05-01 11:17:59 +00:00
|
|
|
{
|
|
|
|
private const string COOKIENAME = "JACKETT";
|
2020-02-10 22:16:19 +00:00
|
|
|
private readonly ServerConfig _serverConfig;
|
2018-05-01 11:17:59 +00:00
|
|
|
|
2021-11-16 13:06:07 +00:00
|
|
|
public SecurityService(ServerConfig sc) => _serverConfig = sc;
|
2018-05-01 11:17:59 +00:00
|
|
|
|
|
|
|
public string HashPassword(string input)
|
|
|
|
{
|
|
|
|
if (input == null)
|
|
|
|
return null;
|
|
|
|
// Append key as salt
|
|
|
|
input += _serverConfig.APIKey;
|
|
|
|
|
2020-02-10 22:16:19 +00:00
|
|
|
var UE = new UnicodeEncoding();
|
2018-05-01 11:17:59 +00:00
|
|
|
byte[] hashValue;
|
2020-02-10 22:16:19 +00:00
|
|
|
var message = UE.GetBytes(input);
|
2018-05-01 11:17:59 +00:00
|
|
|
|
2020-02-10 22:16:19 +00:00
|
|
|
var hashString = new SHA512Managed();
|
|
|
|
var hex = "";
|
2018-05-01 11:17:59 +00:00
|
|
|
|
|
|
|
hashValue = hashString.ComputeHash(message);
|
2020-02-10 22:16:19 +00:00
|
|
|
foreach (var x in hashValue)
|
2018-05-01 11:17:59 +00:00
|
|
|
{
|
2020-02-10 22:16:19 +00:00
|
|
|
hex += string.Format("{0:x2}", x);
|
2018-05-01 11:17:59 +00:00
|
|
|
}
|
|
|
|
return hex;
|
|
|
|
}
|
|
|
|
|
2020-02-25 16:08:03 +00:00
|
|
|
public void Login(HttpResponseMessage response) => response.Headers.Add("Set-Cookie", COOKIENAME + "=" + _serverConfig.AdminPassword + "; path=/");
|
2018-05-01 11:17:59 +00:00
|
|
|
|
2020-02-25 16:08:03 +00:00
|
|
|
public void Logout(HttpResponseMessage response) => response.Headers.Add("Set-Cookie", COOKIENAME + "=; path=/");
|
2018-05-01 11:17:59 +00:00
|
|
|
|
|
|
|
public bool CheckAuthorised(HttpRequestMessage request)
|
|
|
|
{
|
|
|
|
if (string.IsNullOrEmpty(_serverConfig.AdminPassword))
|
|
|
|
return true;
|
|
|
|
|
|
|
|
try
|
|
|
|
{
|
2018-05-01 11:41:34 +00:00
|
|
|
var cookie = request.Headers.GetValues(COOKIENAME).FirstOrDefault();
|
2018-05-01 11:17:59 +00:00
|
|
|
if (cookie != null)
|
|
|
|
{
|
2018-05-01 11:41:34 +00:00
|
|
|
return cookie == _serverConfig.AdminPassword;
|
2018-05-01 11:17:59 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
catch { }
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|