kreta/Kreta.WebApi/Ellenorzo/Kreta.Ellenorzo.WebApi/VN/Common/Logic/FelhasznaloLogic.cs
2024-03-13 00:33:46 +01:00

99 lines
3.4 KiB
C#

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Web;
using Kreta.Ellenorzo.Domain.VN.Common;
using Kreta.Ellenorzo.Enums;
namespace Kreta.Ellenorzo.WebApi.VN.Logic
{
internal static class FelhasznaloLogic
{
public static MobileUser GetFelhasznalo()
{
return HttpContext.Current.Items.Contains("MobileUser")
? (MobileUser)HttpContext.Current.Items["MobileUser"]
: new MobileUser(GetInstituteCode(), GetStudentId(), GetUserName(), GetTutelaryId(), GetRoles(), GetSchoolYearId(), GetApiSecurity(), GetUserIdpUniqueId(), GetStudentIdpUniqueId(), GetInstituteUniqueId());
}
private static string GetInstituteCode()
{
return GetClaims("kreta:institute_code").Single();
}
private static Guid GetInstituteUniqueId()
{
return new Guid(GetClaims("kreta:institute_unique_id").Single());
}
private static ApiSecurity GetApiSecurity()
{
if (bool.Parse(ConfigurationManager.AppSettings["IsApiSecurityEnabled"]))
{
var header = ((HttpRequestMessage)HttpContext.Current.Items["MS_HttpRequestMessage"]).Headers;
return new ApiSecurity(header.Authorization.Parameter, header.First(x => x.Key == "s").Value.First());
}
else
{
return null;
}
}
private static int GetInstituteUserId()
{
var claim = GetClaims("kreta:institute_user_id").Single();
return int.Parse(claim);
}
private static int GetSchoolYearId()
{
var claim = GetClaims("kreta:school_year_id").Single();
return int.Parse(claim);
}
private static int? GetTutelaryId()
=> HasRole(FelhasznaloSzerepkor.Gondviselo) ? GetInstituteUserId() : (int?)null;
private static int GetStudentId()
=> HasRole(FelhasznaloSzerepkor.Gondviselo) ? int.Parse(GetClaims("kreta:student_id").Single()) : GetInstituteUserId();
private static Guid GetUserIdpUniqueId()
{
return new Guid(GetClaims("kreta:institute_user_idp_unique_id").Single());
}
private static Guid GetStudentIdpUniqueId()
=> HasRole(FelhasznaloSzerepkor.Gondviselo) ? new Guid(GetClaims("kreta:student_idp_unique_id").Single()) : GetUserIdpUniqueId();
private static string GetUserName()
{
return GetClaims("kreta:user_name").Single();
}
private static IEnumerable<FelhasznaloSzerepkor> GetRoles()
{
var result = new List<FelhasznaloSzerepkor>();
var roles = GetClaims(ClaimTypes.Role);
foreach (var role in roles)
{
if (Enum.TryParse(role, out FelhasznaloSzerepkor enumValue))
{
result.Add(enumValue);
}
}
return result;
}
private static IEnumerable<string> GetClaims(string type)
{
return ClaimsPrincipal.Current.Claims.Where(x => x.Type == type).Select(x => x.Value);
}
private static bool HasRole(FelhasznaloSzerepkor felhasznaloSzerepkor) => GetRoles().Count(x => x == felhasznaloSzerepkor) == 1;
}
}