EnVisageOnline/Main/Source/EnVisage/Code/Attributes/PrevuAuthorizeAttribute.cs

148 lines
5.9 KiB
C#

using Microsoft.AspNet.Identity;
using Microsoft.IdentityModel.Claims;
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EnVisage.Code.Attributes;
using System.Threading;
using EnVisage.Code.BLL;
using System.Text;
using System.Data.Entity.Validation;
using System.Web.Routing;
namespace EnVisage.Code.Attributes
{
public class PrevuAuthorizeAttribute : AuthorizeAttribute
{
protected static readonly Logger Logger = LogManager.GetCurrentClassLogger();
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
{
return false;
}
Guid UserId = Guid.Empty;
IClaimsPrincipal principal = null;
try
{
principal = Thread.CurrentPrincipal as IClaimsPrincipal;
UserId = Guid.Parse(httpContext.User.Identity.GetID());
}
catch (Exception d)
{
LogException(d);
return false;
}
if (isAuthorized && UserId != Guid.Empty)
return true;
if (principal == null)
{
WriteLog("User name from principal is null. in AuthorizeCore()");
return false;
}
var identity = (IClaimsIdentity) principal.Identity;
if (identity.Name == null)
WriteLog("User name from identity is null. in AuthorizeCore()");
if (identity.Name != null)
{
WriteLog("User name from adfs." + identity.Name);
string username = identity.Name;
string[] splprm = { "\\" };
string[] names = username.Split(splprm, StringSplitOptions.None);
if (names.Length >= 2)
username = names[1];
var user = (new EnVisageEntities()).AspNetUsers.Where(x => x.UserName == username).FirstOrDefault();
if (user != null)
{
if (user.Type == (int) Code.UserType.Active)
{
identity.Claims.Add(new Microsoft.IdentityModel.Claims.Claim(Microsoft.IdentityModel.Claims.ClaimTypes.NameIdentifier, user.Id));
return true;
}
}
}
return false;
}
protected override void HandleUnauthorizedRequest(System.Web.Mvc.AuthorizationContext filterContext)
{
if (HttpContext.Current.User.Identity.isSSO())
{
filterContext.Result = new RedirectToRouteResult(new
RouteValueDictionary(new { controller = "Account", action = "SSOFailureNoLocalAccount" }));
}
else
{
base.HandleUnauthorizedRequest(filterContext);
}
}
private void WriteLog(string message)
{
bool writelog = false;
string debug= (new SystemSettingsManager(null)).GetSystemSettingsValue((int) SystemSettingType.WriteDebugMessagesForSSO,false);
if (!string.IsNullOrEmpty(debug))
writelog = debug.Trim().ToLower().Equals("true");
if (!writelog)
return;
Logger.Log(NLog.LogLevel.Debug, message);
}
public void LogException(Exception ex)
{
var sb = new StringBuilder();
sb.AppendLine(string.Format("{0}: {1}", ex.GetType(), ex.Message));
sb.AppendLine(ex.StackTrace);
var innerCount = 0;
var innerEx = ex;
while (innerEx.InnerException != null && innerCount++ < Constants.MAX_INNER_EXCEPTION_LOG_LEVEL)
{
if (innerEx.Message != innerEx.InnerException.Message)
sb.AppendLine("Inner Exception Message: " + innerEx.InnerException.Message);
innerEx = innerEx.InnerException;
}
var dbEntityValidationException = ex as DbEntityValidationException;
if (dbEntityValidationException != null)
{
foreach (var validationErrors in dbEntityValidationException.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
sb.AppendFormat("Property: {0} Error: {1}", validationError.PropertyName,
validationError.ErrorMessage);
}
}
sb.AppendLine(dbEntityValidationException.StackTrace);
}
if (System.Web.HttpContext.Current != null)
{
sb.AppendLine();
sb.AppendLine(string.Format("URL: {0}", System.Web.HttpContext.Current.Request.Url));
sb.AppendLine(string.Format("Referrer: {0}", System.Web.HttpContext.Current.Request.UrlReferrer));
sb.AppendLine(string.Format("QueryString: {0}", System.Web.HttpContext.Current.Request.QueryString));
sb.AppendLine(string.Format("UserHostAddress: {0}", System.Web.HttpContext.Current.Request.UserHostAddress));
sb.AppendLine(string.Format("UserAgent: {0}", System.Web.HttpContext.Current.Request.UserAgent));
if (System.Web.HttpContext.Current.Request.Form.Count > 0)
{
sb.AppendLine();
sb.AppendLine("Form:");
foreach (string key in System.Web.HttpContext.Current.Request.Form.Keys)
{
sb.AppendLine(string.Format("{0}: {1}", key, System.Web.HttpContext.Current.Request.Form[key]));
}
}
}
// log error using NLog
Logger.Fatal(sb.ToString());
}
}
}