Esempio n. 1
0
        private void BuildNameDropDown()
        {
            RbacPrincipal   rbacPrincipal   = RbacPrincipal.Current;
            DropDownCommand dropDownCommand = this.nameDropDown.DropDownCommand;

            dropDownCommand.Name = "UserName";
            dropDownCommand.Text = rbacPrincipal.Name;
            if (this.hasHelpdesk)
            {
                dropDownCommand.Commands.Add(new Command
                {
                    Name          = "Helpdesk",
                    Text          = Strings.EntryOnBehalfOf,
                    OnClientClick = "CrossPremise.NavTo('helpdesk');"
                });
            }
            if (rbacPrincipal.IsInRole("MailboxFullAccess") && !rbacPrincipal.IsInRole("DelegatedAdmin") && !rbacPrincipal.IsInRole("ByoidAdmin"))
            {
                if (dropDownCommand.Commands.Count > 0)
                {
                    dropDownCommand.Commands.Add(new SeparatorCommand());
                }
                dropDownCommand.Commands.Add(new Command
                {
                    Name          = "SignOff",
                    Text          = Strings.SignOff,
                    OnClientClick = "CrossPremise.NavTo('dualLogout');"
                });
            }
        }
        public JsonResult AjaxLogin(string name, string password)
        {
            var result = new Result(false);

            if (string.IsNullOrWhiteSpace(name))
            {
                result.Message = "消息:用户名不能为空!";
            }
            if (string.IsNullOrWhiteSpace(password))
            {
                result.Message = "消息:密码不能为空!";
            }
            MemoryCacheHelper.RemoveCacheAll();
            if (!RbacPrincipal.Login(name, password))
            {
                result.Message = "消息:用户或密码错误,请重新输入!!";
            }
            else
            {
                result = new Result(true);
                var identity = LEnvironment.Principal as MyFormsPrincipal <MyUserDataPrincipal>;
                if (identity != null)
                {
                    //if (identity.DepUserType == 2)
                    //{
                    //    result.Message = "../../" + LCL.MvcExtensions.PageFlowService.PageNodes.FindPageNode("LayoutHome1").Value;
                    //}
                    //else
                    //{
                    result.Message = "../../" + LCL.MvcExtensions.PageFlowService.PageNodes.FindPageNode("LayoutHome").Value;
                    // }
                }
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Esempio n. 3
0
 protected override bool CheckAccessCore(OperationContext operationContext)
 {
     if (RbacAuthorizationManager.NewAuthZMethodEnabled.Value)
     {
         if (HttpContext.Current.Items.Contains(RbacAuthorizationManager.DataServiceExceptionKey))
         {
             throw (DataServiceException)HttpContext.Current.Items[RbacAuthorizationManager.DataServiceExceptionKey];
         }
         operationContext.SetRbacPrincipal((RbacPrincipal)HttpContext.Current.User);
         return(base.CheckAccessCore(operationContext));
     }
     else
     {
         RbacPrincipal rbacPrincipal = null;
         ElapsedTimeWatcher.Watch(RequestStatistics.RequestStatItem.RbacPrincipalAcquireLatency, delegate
         {
             rbacPrincipal = RbacPrincipalManager.Instance.AcquireRbacPrincipal(HttpContext.Current);
         });
         if (rbacPrincipal == null)
         {
             return(false);
         }
         HttpContext.Current.User = rbacPrincipal;
         rbacPrincipal.SetCurrentThreadPrincipal();
         if (OperationContext.Current != null)
         {
             OperationContext.Current.SetRbacPrincipal(rbacPrincipal);
         }
         return(base.CheckAccessCore(operationContext));
     }
 }
 public ActionResult Login(Account account)
 {
     //if (Session["ValidateCode"].ToString() != account.VerifyCode)
     //{
     //    ModelState.AddModelError("VerifyCode", "validate code is error");
     //    return View();
     //}
     if (!ModelState.IsValid)
     {
         return(View());
     }
     if (string.IsNullOrWhiteSpace(account.Name))
     {
         ModelState.AddModelError("Name", "消息:用户名不能为空!");
         return(View());
     }
     if (string.IsNullOrWhiteSpace(account.Password))
     {
         ModelState.AddModelError("Name", "消息:密码不能为空!");
         return(View());
     }
     MemoryCacheHelper.RemoveCacheAll();
     if (!RbacPrincipal.Login(account.Name, account.Password))
     {
         ModelState.AddModelError("Name", "消息:用户或密码错误,请重新输入!");
         return(View());
     }
     else
     {
         return(RedirectIndex());
     }
 }
Esempio n. 5
0
        protected void RenderAlertBarBegin()
        {
            RbacPrincipal rbacPrincipal = RbacPrincipal.Current;
            string        text          = null;
            string        text2         = null;

            if (!rbacPrincipal.IsInRole("MailboxFullAccess"))
            {
                string logonUser    = HttpUtility.HtmlEncode((rbacPrincipal.IsInRole("Enterprise") && rbacPrincipal.RbacConfiguration.SecurityAccessToken != null && rbacPrincipal.RbacConfiguration.SecurityAccessToken.LogonName != null && rbacPrincipal.RbacConfiguration.Impersonated) ? rbacPrincipal.RbacConfiguration.SecurityAccessToken.LogonName : rbacPrincipal.RbacConfiguration.LogonUserDisplayName);
                string accessedUser = HttpUtility.HtmlEncode(rbacPrincipal.RbacConfiguration.ExecutingUserDisplayName);
                text  = Strings.OnbehalfOfAlert("<strong>", logonUser, "</strong>", accessedUser);
                text2 = Strings.OnbehalfOfAlert(string.Empty, logonUser, string.Empty, accessedUser);
            }
            else if (rbacPrincipal.IsInRole("DelegatedAdmin") || rbacPrincipal.IsInRole("ByoidAdmin"))
            {
                string targetTenant = HttpContext.Current.GetTargetTenant();
                text  = Strings.ManageOtherTenantAlert("<strong>", targetTenant, "</strong>");
                text2 = Strings.ManageOtherTenantAlert(string.Empty, targetTenant, string.Empty);
            }
            if (text != null)
            {
                this.renderAlertBar = true;
                string cssClass = NavigationSprite.GetCssClass(NavigationSprite.SpriteId.EsoBarEdge);
                base.Response.Output.Write("<div id=\"EsoBar\" class=\"{0}\"><img id=\"EsoBarIcon\" class=\"{1}\" src=\"{6}\" alt=\"\" /><div id=\"EsoBarMsg\" title=\"{2}\">{3}</div><img id=\"EsoBarLeftEdge\" class=\"{4}\" src=\"{6}\" alt=\"\"/><img id=\"EsoBarRightEdge\" class=\"{5}\" src=\"{6}\" alt=\"\"></div></div><div id=\"EsoNavWrap\">", new object[]
                {
                    HorizontalSprite.GetCssClass(HorizontalSprite.SpriteId.EsoBar),
                    CommonSprite.GetCssClass(CommonSprite.SpriteId.Information),
                    text2,
                    text,
                    cssClass,
                    cssClass,
                    Util.GetSpriteImageSrc(this)
                });
            }
        }
Esempio n. 6
0
        private void UpdateColumns()
        {
            if (!string.IsNullOrEmpty(this.DefaultSprite) || !string.IsNullOrEmpty(this.SpriteProperty))
            {
                this.Columns.Insert(0, new SpriteColumnHeader
                {
                    DefaultSprite         = this.DefaultSprite,
                    Name                  = this.SpriteProperty,
                    AlternateTextProperty = this.SpriteAltTextProperty
                });
            }
            if (this.AllowSorting && this.SortProperty == null)
            {
                foreach (ColumnHeader columnHeader in this.Columns)
                {
                    if (!string.IsNullOrEmpty(columnHeader.SortExpression) && !(columnHeader is SpriteColumnHeader))
                    {
                        this.SortProperty = columnHeader.SortExpression;
                        break;
                    }
                }
            }
            RbacPrincipal rbacPrincipal = RbacPrincipal.Current;

            this.Columns.RemoveAll((ColumnHeader x) => !string.IsNullOrEmpty(x.Role) && !rbacPrincipal.IsInRole(x.Role));
        }
Esempio n. 7
0
        public List <string> Validate(object target, Service profile)
        {
            List <string> list = new List <string>();
            string        text = target as string;

            if (text != null && !text.Equals("NA", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    foreach (string roleString in text.Split(new char[]
                    {
                        ','
                    }))
                    {
                        foreach (string rbacQuery in RbacPrincipal.SplitRoles(roleString))
                        {
                            new RbacQuery(rbacQuery);
                        }
                    }
                }
                catch (ArgumentException ex)
                {
                    list.Add(ex.Message);
                }
            }
            return(list);
        }
        public RbacPrincipal AcquireRbacPrincipalWrapper(HttpContext httpContext)
        {
            RbacPrincipal rbacPrincipal = null;

            ElapsedTimeWatcher.Watch(RequestStatistics.RequestStatItem.RbacPrincipalAcquireLatency, delegate
            {
                rbacPrincipal = this.AcquireRbacPrincipal(httpContext);
            });
            return(rbacPrincipal);
        }
Esempio n. 9
0
        internal static VariantConfigurationSnapshot GetSnapshotForCurrentUser(out bool isGlobal)
        {
            RbacPrincipal current = RbacPrincipal.GetCurrent(false);

            if (current != null && current.RbacConfiguration != null && current.RbacConfiguration.ConfigurationSettings != null && current.RbacConfiguration.ConfigurationSettings.VariantConfigurationSnapshot != null)
            {
                isGlobal = false;
                return(current.RbacConfiguration.ConfigurationSettings.VariantConfigurationSnapshot);
            }
            isGlobal = true;
            return(EacFlightUtility.EacGlobalSnapshot);
        }
 public ActionResult LogOut()
 {
     try
     {
         Request.Cookies.Clear();
         RbacPrincipal.Logout();
     }
     catch (Exception ex)
     {
         Logger.LogError("退出系统", ex);
     }
     FormsAuthentication.SignOut();
     return(Redirect(FormsAuthentication.LoginUrl));
 }
        internal static string GetPeriodicKeyPerUser()
        {
            RbacPrincipal current = RbacPrincipal.GetCurrent(false);

            if (current != null)
            {
                return(current.NameForEventLog);
            }
            if (HttpContext.Current.Request.IsAuthenticated)
            {
                return(HttpContext.Current.User.Identity.GetSafeName(true));
            }
            return(null);
        }
Esempio n. 12
0
        private static string BuildEhcHref(string helpId, bool isEACHelpId)
        {
            string result;

            if (isEACHelpId)
            {
                RbacPrincipal rbacPrincipal = HttpContext.Current.User as RbacPrincipal;
                result = ((rbacPrincipal != null) ? HelpProvider.ConstructHelpRenderingUrl(helpId, rbacPrincipal.RbacConfiguration).ToString() : HelpProvider.ConstructHelpRenderingUrl(helpId).ToString());
            }
            else
            {
                result = HelpUtil.ConstructOwaOptionsHelpUrl(helpId);
            }
            return(result);
        }
Esempio n. 13
0
        internal static JsonDictionary <bool> GetRbacData()
        {
            Dictionary <string, bool> dictionary    = new Dictionary <string, bool>(ClientRbac.rbacRoles.Count + ClientRbac.HybridEcpFeatures.Count, StringComparer.OrdinalIgnoreCase);
            RbacPrincipal             rbacPrincipal = RbacPrincipal.Current;

            foreach (string text in ClientRbac.rbacRoles)
            {
                dictionary.Add(text, rbacPrincipal.IsInRole(text));
            }
            foreach (EcpFeature ecpFeature in ClientRbac.HybridEcpFeatures)
            {
                string name = ecpFeature.GetName();
                dictionary.Add(name, rbacPrincipal.IsInRole(name));
            }
            return(new JsonDictionary <bool>(dictionary));
        }
Esempio n. 14
0
 public static void SendReportForCriticalException(HttpContext context, Exception exception)
 {
     if (exception.IsUICriticalException() && exception.IsControlPanelException())
     {
         ExWatson.AddExtraData(ErrorHandlingUtil.GetEcpWatsonExtraData(context, exception));
         EcpPerfCounters.SendWatson.Increment();
         RbacPrincipal rbacPrincipal = context.User as RbacPrincipal;
         if (rbacPrincipal != null && ExTraceConfiguration.Instance.InMemoryTracingEnabled)
         {
             TroubleshootingContext troubleshootingContext = rbacPrincipal.RbacConfiguration.TroubleshootingContext;
             troubleshootingContext.SendTroubleshootingReportWithTraces(exception, ErrorHandlingUtil.GetEcpWatsonTitle(exception, context));
             return;
         }
         ExWatson.SendReport(exception, ReportOptions.ReportTerminateAfterSend, exception.GetCustomMessage());
     }
 }
Esempio n. 15
0
        protected override ICollection <KeyValuePair <string, object> > GetComponentSpecificData(IActivityScope activityScope, string eventId)
        {
            Dictionary <string, object> dictionary = null;

            if (activityScope != null)
            {
                HttpContext httpContext = HttpContext.Current;
                if (httpContext != null)
                {
                    string sourceCafeServer = CafeHelper.GetSourceCafeServer(httpContext.Request);
                    if (!string.IsNullOrEmpty(sourceCafeServer))
                    {
                        activityScope.SetProperty(ActivityContextLoggerMetaData.FrontEndServer, sourceCafeServer);
                    }
                    string requestUrlForLog = httpContext.GetRequestUrlForLog();
                    activityScope.SetProperty(ActivityContextLoggerMetaData.Url, requestUrlForLog);
                }
                RbacPrincipal current = RbacPrincipal.GetCurrent(false);
                if (current != null)
                {
                    string value;
                    if (current.RbacConfiguration.DelegatedPrincipal != null)
                    {
                        value = current.RbacConfiguration.DelegatedPrincipal.UserId;
                    }
                    else
                    {
                        SmtpAddress executingUserPrimarySmtpAddress = current.RbacConfiguration.ExecutingUserPrimarySmtpAddress;
                        value = (executingUserPrimarySmtpAddress.IsValidAddress ? executingUserPrimarySmtpAddress.ToString() : current.RbacConfiguration.ExecutingUserPrincipalName);
                    }
                    if (!string.IsNullOrEmpty(value))
                    {
                        activityScope.SetProperty(ActivityContextLoggerMetaData.PrimarySmtpAddress, value);
                    }
                    OrganizationId organizationId = current.RbacConfiguration.OrganizationId;
                    if (organizationId != null && organizationId.OrganizationalUnit != null)
                    {
                        string name = organizationId.OrganizationalUnit.Name;
                        activityScope.SetProperty(ActivityContextLoggerMetaData.Organization, name);
                    }
                }
                dictionary = new Dictionary <string, object>(ActivityContextLogger.EnumToShortKeyMapping.Count);
                ExtensibleLogger.CopyPIIProperty(activityScope, dictionary, ActivityContextLoggerMetaData.PrimarySmtpAddress, ActivityContextLogger.PrimarySmtpAddressKey);
                ExtensibleLogger.CopyProperties(activityScope, dictionary, ActivityContextLogger.EnumToShortKeyMapping);
            }
            return(dictionary);
        }
Esempio n. 16
0
        internal ClientLogEvent(Datapoint datapoint)
        {
            this.datapoint = datapoint;
            LocalSession localSession = RbacPrincipal.GetCurrent(false) as LocalSession;
            string       value        = (localSession == null) ? string.Empty : localSession.LogonTypeFlag;

            this.datapointProperties = new Dictionary <string, object>
            {
                {
                    "TIME",
                    this.datapoint.Time
                },
                {
                    "SID",
                    HttpContext.Current.GetSessionID()
                },
                {
                    "USID",
                    (HttpContext.Current.User is RbacSession) ? HttpContext.Current.GetCachedUserUniqueKey() : string.Empty
                },
                {
                    "SRC",
                    this.datapoint.Src
                },
                {
                    "REQID",
                    this.datapoint.ReqId
                },
                {
                    "IP",
                    this.GetClientIP()
                },
                {
                    "UA",
                    HttpUtility.UrlEncode(HttpContext.Current.Request.UserAgent)
                },
                {
                    "BLD",
                    ExchangeSetupContext.InstalledVersion.ToString()
                },
                {
                    "LTYPE",
                    value
                }
            };
        }
Esempio n. 17
0
        private Uri GetECPExternalUrl()
        {
            Uri           result        = null;
            RbacPrincipal rbacPrincipal = RbacPrincipal.Current;

            if (rbacPrincipal.IsInRole("Mailbox"))
            {
                ExchangePrincipal exchangePrincipal = ExchangePrincipal.FromDirectoryObjectId((IRecipientSession)((RecipientObjectResolver)RecipientObjectResolver.Instance).CreateAdSession(), rbacPrincipal.ExecutingUserId, RemotingOptions.LocalConnectionsOnly);
                try
                {
                    result = FrontEndLocator.GetFrontEndEcpUrl(exchangePrincipal);
                }
                catch (ServerNotFoundException)
                {
                }
            }
            return(result);
        }
Esempio n. 18
0
        private void OnPostAuthenticateRequest(object sender, EventArgs e)
        {
            HttpApplication applicationInstance = HttpContext.Current.ApplicationInstance;
            HttpContext     httpContext         = HttpContext.Current;
            HttpRequest     request             = httpContext.Request;

            if (request.IsAuthenticated && RbacPrincipal.GetCurrent(false) != null && ClientAccessRulesModule.ShouldBlockConnection(httpContext, RbacPrincipal.Current.RbacConfiguration))
            {
                if (httpContext.IsWebServiceRequest() || httpContext.IsUploadRequest())
                {
                    ClientAccessRulesModule.SendAjaxErrorToClient(httpContext);
                }
                else
                {
                    httpContext.Response.Redirect(string.Format("{0}logoff.owa?reason=6", EcpUrl.OwaVDir));
                }
                applicationInstance.CompleteRequest();
            }
        }
        internal static string GetUserNameToLog()
        {
            string        result  = Strings.UserUnauthenticated;
            RbacPrincipal current = RbacPrincipal.GetCurrent(false);

            if (current != null)
            {
                result = current.NameForEventLog;
            }
            else if (HttpContext.Current.Request.IsAuthenticated)
            {
                result = HttpContext.Current.User.Identity.GetSafeName(true);
            }
            else if (HttpContext.Current.User == null)
            {
                result = Strings.UserNotSet;
            }
            return(result);
        }
        public static void GetObjectPostAction(DataRow inputRow, DataTable dataTable, DataObjectStore store)
        {
            DataRow dataRow = dataTable.Rows[0];
            RecipientTypeDetails recipientTypeDetails = (RecipientTypeDetails)dataRow["RecipientTypeDetails"];

            if (recipientTypeDetails == RecipientTypeDetails.LinkedMailbox)
            {
                dataRow["DomainUserName"] = (string)dataRow["LinkedMasterAccount"];
                return;
            }
            RbacPrincipal rbacPrincipal = RbacPrincipal.Current;

            if (rbacPrincipal.RbacConfiguration.SecurityAccessToken != null && rbacPrincipal.RbacConfiguration.SecurityAccessToken.LogonName != null)
            {
                dataRow["DomainUserName"] = rbacPrincipal.RbacConfiguration.SecurityAccessToken.LogonName;
                return;
            }
            dataRow["DomainUserName"] = string.Format("{0}\\{1}", ((ADObjectId)dataRow["Identity"]).DomainId.Name, (string)dataRow["SamAccountName"]);
        }
Esempio n. 21
0
        private void OnAuthorizeRequest(object sender, EventArgs e)
        {
            ExTraceGlobals.ReportingWebServiceTracer.TraceDebug((long)this.GetHashCode(), "ReportingModule.OnAuthorizeRequest");
            HttpApplication   httpApplication   = (HttpApplication)sender;
            HttpContext       context           = httpApplication.Context;
            RequestStatistics requestStatistics = context.Items[RequestStatistics.RequestStatsKey] as RequestStatistics;

            if (context.Request.IsAuthenticated)
            {
                requestStatistics.AddExtendedStatisticsDataPoint("AuthN", "True");
                try
                {
                    RbacPrincipal rbacPrincipal = RbacPrincipalManager.Instance.AcquireRbacPrincipalWrapper(context);
                    if (rbacPrincipal != null)
                    {
                        ExTraceGlobals.ReportingWebServiceTracer.TraceDebug((long)this.GetHashCode(), "[OnAuthorizeRequest] RbacPrincipal != null");
                        context.User = rbacPrincipal;
                        rbacPrincipal.SetCurrentThreadPrincipal();
                        requestStatistics.AddExtendedStatisticsDataPoint("AuthZ", "True");
                    }
                    else
                    {
                        ExTraceGlobals.ReportingWebServiceTracer.TraceDebug((long)this.GetHashCode(), "[OnAuthorizeRequest] RbacPrincipal == null");
                        context.Response.StatusCode = 401;
                        httpApplication.CompleteRequest();
                        requestStatistics.AddExtendedStatisticsDataPoint("AuthZ", "False");
                    }
                    goto IL_138;
                }
                catch (DataServiceException value)
                {
                    ExTraceGlobals.ReportingWebServiceTracer.TraceDebug((long)this.GetHashCode(), "[OnAuthorizeRequest] DataServiceException got");
                    context.Items.Add(RbacAuthorizationManager.DataServiceExceptionKey, value);
                    requestStatistics.AddExtendedStatisticsDataPoint("AuthZ", "False");
                    goto IL_138;
                }
            }
            requestStatistics.AddExtendedStatisticsDataPoint("AuthN", "False");
            requestStatistics.AddExtendedStatisticsDataPoint("AuthZ", "False");
IL_138:
            ExTraceGlobals.ReportingWebServiceTracer.TraceDebug((long)this.GetHashCode(), "ReportingModule.OnAuthorizeRequest - End");
        }
Esempio n. 22
0
 public void AppendToIisLog()
 {
     if (!string.IsNullOrEmpty(HttpContext.Current.GetSessionID()))
     {
         StringBuilder stringBuilder = new StringBuilder();
         stringBuilder.Append("&perfRecord=");
         stringBuilder.Append(this.ToString().Replace("&", "%26"));
         stringBuilder.Append("&sessionId=");
         using (StringWriter stringWriter = new StringWriter(stringBuilder))
         {
             HttpContext.Current.Server.UrlEncode(HttpContext.Current.GetSessionID(), stringWriter);
         }
         LocalSession localSession = RbacPrincipal.GetCurrent(false) as LocalSession;
         if (localSession != null)
         {
             stringBuilder.Append("&logonType=");
             stringBuilder.Append(localSession.LogonTypeFlag);
         }
         HttpContext.Current.Response.AppendToLog(stringBuilder.ToString());
     }
 }
Esempio n. 23
0
        public static bool IsFederatedUser(this RbacPrincipal rbacPrincipal)
        {
            bool result = false;
            ExchangeRunspaceConfiguration rbacConfiguration = rbacPrincipal.RbacConfiguration;
            SmtpAddress executingUserPrimarySmtpAddress     = rbacConfiguration.ExecutingUserPrimarySmtpAddress;

            if (!executingUserPrimarySmtpAddress.IsValidAddress)
            {
                string executingUserPrincipalName = rbacConfiguration.ExecutingUserPrincipalName;
                if (!string.IsNullOrEmpty(executingUserPrincipalName) && SmtpAddress.IsValidSmtpAddress(executingUserPrincipalName))
                {
                    executingUserPrimarySmtpAddress = new SmtpAddress(executingUserPrincipalName);
                }
            }
            if (executingUserPrimarySmtpAddress.IsValidAddress)
            {
                SmtpDomainWithSubdomains smtpDomainWithSubdomains = new SmtpDomainWithSubdomains(executingUserPrimarySmtpAddress.Domain);
                DomainCacheValue         domainCacheValue         = DomainCache.Singleton.Get(smtpDomainWithSubdomains, rbacConfiguration.OrganizationId);
                result = (domainCacheValue != null && domainCacheValue.AuthenticationType != null && domainCacheValue.AuthenticationType.Value == AuthenticationType.Federated);
            }
            return(result);
        }
Esempio n. 24
0
        private void BuildNameDropDown()
        {
            RbacPrincipal   rbacPrincipal   = RbacPrincipal.Current;
            DropDownCommand dropDownCommand = this.nameDropDown.DropDownCommand;

            dropDownCommand.Name = "UserName";
            dropDownCommand.Text = rbacPrincipal.Name;
            if (NavigationUtil.ShouldRenderOwaLink(rbacPrincipal, this.showAdminFeatures.Value))
            {
                dropDownCommand.Commands.Add(new Command
                {
                    Name          = "MailLnk",
                    Text          = Strings.MyMail,
                    OnClientClick = "JumpTo('" + EcpUrl.OwaVDir + "', true);"
                });
            }
            if (this.HasAccessTo("helpdesk"))
            {
                dropDownCommand.Commands.Add(new Command
                {
                    Name          = "Helpdesk",
                    Text          = Strings.EntryOnBehalfOf,
                    OnClientClick = "JumpTo('helpdesk');"
                });
            }
            if (NavigationUtil.ShouldRenderLogoutLink(rbacPrincipal))
            {
                if (dropDownCommand.Commands.Count > 0)
                {
                    dropDownCommand.Commands.Add(new SeparatorCommand());
                }
                dropDownCommand.Commands.Add(new Command
                {
                    Name          = "SignOff",
                    Text          = Strings.SignOff,
                    OnClientClick = "Navigation.SignOut();"
                });
            }
        }
Esempio n. 25
0
        private string GetRoles(RbacPrincipal rbacPrincipal)
        {
            StringBuilder stringBuilder = new StringBuilder();
            bool          flag          = true;

            foreach (object obj in Enum.GetValues(typeof(RoleType)))
            {
                RoleType roleType = (RoleType)obj;
                string   text     = roleType.ToString();
                if (rbacPrincipal.IsInRole(text))
                {
                    if (flag)
                    {
                        flag = false;
                    }
                    else
                    {
                        stringBuilder.Append(", ");
                    }
                    stringBuilder.Append(text);
                }
            }
            return(stringBuilder.ToString());
        }
        private static void Application_Error(object sender, EventArgs e)
        {
            HttpContext httpContext = HttpContext.Current;
            Exception   ex          = httpContext.GetError();

            ExTraceGlobals.EventLogTracer.TraceError <EcpTraceFormatter <Exception> >(0, 0L, "Application Error: {0}", ex.GetTraceFormatter());
            DDIHelper.Trace("Application Error: {0}", new object[]
            {
                ex.GetTraceFormatter()
            });
            EcpPerfCounters.AspNetErrors.Increment();
            EcpEventLogConstants.Tuple_RequestFailed.LogPeriodicFailure(EcpEventLogExtensions.GetUserNameToLog(), httpContext.GetRequestUrlForLog(), ex, EcpEventLogExtensions.GetFlightInfoForLog());
            RbacPrincipal current    = RbacPrincipal.GetCurrent(false);
            string        tenantName = string.Empty;

            if (current != null)
            {
                OrganizationId organizationId = current.RbacConfiguration.OrganizationId;
                if (organizationId != null && organizationId.OrganizationalUnit != null)
                {
                    tenantName = organizationId.OrganizationalUnit.Name;
                }
            }
            ActivityContextLogger.Instance.LogEvent(new PeriodicFailureEvent(ActivityContext.ActivityId.FormatForLog(), tenantName, httpContext.GetRequestUrlForLog(), ex, EcpEventLogExtensions.GetFlightInfoForLog()));
            ActivityContextManager.CleanupActivityContext(httpContext);
            if (ex is DelegatedSecurityTokenExpiredException)
            {
                ErrorHandlingModule.HandleDelegatedSecurityTokenExpire(httpContext);
                return;
            }
            if (httpContext.IsWebServiceRequest())
            {
                string errorCause = DiagnosticsBehavior.GetErrorCause(ex);
                ErrorHandlingUtil.SendReportForCriticalException(httpContext, ex);
                ErrorHandlingModule.SendJsonError(httpContext, ex, errorCause);
                return;
            }
            if (httpContext.IsUploadRequest())
            {
                ErrorHandlingUtil.SendReportForCriticalException(httpContext, ex);
                ErrorHandlingModule.SendJsonErrorForUpload(httpContext, ex);
                return;
            }
            if (ex is HttpException && ex.InnerException != null)
            {
                ex = ex.InnerException;
            }
            httpContext.Request.ServerVariables["X-ECP-ERROR"] = ex.GetType().FullName;
            string text  = null;
            string text2 = null;

            if (ex is OverBudgetException)
            {
                text = "overbudget";
            }
            else if (ex is IdentityNotMappedException || ex is TransientException)
            {
                text = "transientserviceerror";
            }
            else if (ex is ObjectNotFoundException)
            {
                if (ex.InnerException is NonUniqueRecipientException)
                {
                    text = "nonuniquerecipient";
                }
                else
                {
                    text = "nonmailbox";
                }
            }
            else if (ex is ServerNotInSiteException || ex is LowVersionUserDeniedException)
            {
                text = "lowversion";
            }
            else if (ex is CmdletAccessDeniedException || ex is DelegatedAccessDeniedException)
            {
                text = "noroles";
            }
            else if (ex is UrlNotFoundOrNoAccessException)
            {
                text = "urlnotfoundornoaccess";
            }
            else if (ex is BadRequestException)
            {
                text = "badrequest";
            }
            else if (ex is BadQueryParameterException)
            {
                text = "badqueryparameter";
            }
            else if (ex is ProxyFailureException)
            {
                text = "transientserviceerror";
            }
            else if (ex is ProxyCantFindCasServerException)
            {
                text = "proxy";
            }
            else if (ex is CasServerNotSupportEsoException)
            {
                text = "noeso";
            }
            else if (ex is RegionalSettingsNotConfiguredException)
            {
                text = "regionalsettingsnotconfigured";
            }
            else if (ex is SecurityException || (ErrorHandlingUtil.KnownReflectedExceptions.Value.ContainsKey("Microsoft.Exchange.Hygiene.Security.Authorization.NoValidRolesAssociatedToUserException, Microsoft.Exchange.Hygiene.Security.Authorization") && ex.GetType() == ErrorHandlingUtil.KnownReflectedExceptions.Value["Microsoft.Exchange.Hygiene.Security.Authorization.NoValidRolesAssociatedToUserException, Microsoft.Exchange.Hygiene.Security.Authorization"]))
            {
                text = "noroles";
            }
            else if (ex is ExchangeConfigurationException)
            {
                text = "anonymousauthenticationdisabled";
            }
            else if (ex is CannotAccessOptionsWithBEParamOrCookieException)
            {
                text = "cannotaccessoptionswithbeparamorcookie";
            }
            else if (ex.IsMaxRequestLengthExceededException())
            {
                EcpPerfCounters.RedirectToError.Increment();
                text2 = httpContext.Request.AppRelativeCurrentExecutionFilePath;
            }
            else
            {
                ErrorHandlingUtil.SendReportForCriticalException(httpContext, ex);
                if (!ErrorHandlingUtil.ShowIisNativeErrorPage && !ex.IsInterestingHttpException())
                {
                    text = "unexpected";
                }
            }
            if (text2 != null)
            {
                httpContext.Server.Transfer(text2, true);
                return;
            }
            if (text != null)
            {
                ErrorHandlingModule.TransferToErrorPage(text, ErrorHandlingUtil.CanShowDebugInfo(ex));
            }
        }
Esempio n. 27
0
        private static PowerShellResults InvokeAsyncCore(Func <PowerShellResults> callback, Action <PowerShellResults> onCompleted, string uniqueUserIdentity, AsyncServiceManager.AsyncTaskBudgetManager asyncTaskBudget, string commandStringForTrace, ThrottlingType throttlingType)
        {
            if (string.IsNullOrEmpty(uniqueUserIdentity))
            {
                throw new ArgumentNullException("uniqueUserIdentity cannot be null.");
            }
            AsyncServiceManager.AsyncTaskThrottlingStatus asyncTaskThrottlingStatus = asyncTaskBudget.RegisterAsyncTask(uniqueUserIdentity, commandStringForTrace, throttlingType);
            if (asyncTaskThrottlingStatus != AsyncServiceManager.AsyncTaskThrottlingStatus.None)
            {
                LocalizedString value = (asyncTaskThrottlingStatus == AsyncServiceManager.AsyncTaskThrottlingStatus.PerAppThrottlingHit) ? Strings.LongRunPerAppThrottlingHit : Strings.LongRunPerUserThrottlingHit;
                asyncTaskBudget.UnregisterAsyncTask(uniqueUserIdentity, throttlingType);
                return(new PowerShellResults
                {
                    ErrorRecords = new ErrorRecord[]
                    {
                        new ErrorRecord(new InvalidOperationException(value))
                    }
                });
            }
            AsyncServiceManager.WorkItem workItem = new AsyncServiceManager.WorkItem(Guid.NewGuid().ToString());
            AsyncServiceManager.workItems[workItem.Id] = workItem;
            CultureInfo      currentCulture          = CultureInfo.CurrentCulture;
            IPrincipal       currentPrincipal        = Thread.CurrentPrincipal;
            OperationContext currentOperationContext = OperationContext.Current;
            HttpContext      currentHttpContext      = HttpContext.Current;

            commandStringForTrace = ((commandStringForTrace == null) ? string.Empty : commandStringForTrace);
            RbacPrincipal rbacSession = RbacPrincipal.GetCurrent(false);

            ThreadPool.QueueUserWorkItem(delegate(object state)
            {
                int managedThreadId = Thread.CurrentThread.ManagedThreadId;
                AsyncServiceManager.WorkItem workItem;
                AsyncServiceManager.workerThreads[managedThreadId] = workItem;
                CultureInfo currentCulture          = CultureInfo.CurrentCulture;
                IPrincipal currentPrincipal         = Thread.CurrentPrincipal;
                OperationContext value2             = OperationContext.Current;
                HttpContext value3                  = HttpContext.Current;
                Thread.CurrentThread.CurrentCulture = (Thread.CurrentThread.CurrentUICulture = currentCulture);
                Thread.CurrentPrincipal             = currentPrincipal;
                OperationContext.Current            = currentOperationContext;
                HttpContext.Current                 = AsyncServiceManager.CloneHttpContextForLongRunningThread(currentHttpContext);
                ActivityContextManager.InitializeActivityContext(HttpContext.Current, ActivityContextLoggerId.LongRunning);
                PowerShellResults powerShellResults = null;
                try
                {
                    EcpEventLogConstants.Tuple_AsyncWebRequestStarted.LogEvent(new object[]
                    {
                        uniqueUserIdentity,
                        managedThreadId,
                        commandStringForTrace
                    });
                    powerShellResults = callback();
                    object obj        = AsyncServiceManager.workerThreads[managedThreadId];
                }
                catch (Exception exception)
                {
                    powerShellResults = new PowerShellResults();
                    powerShellResults.ErrorRecords = new ErrorRecord[]
                    {
                        new ErrorRecord(exception)
                    };
                    EcpEventLogConstants.Tuple_AsyncWebRequestFailed.LogEvent(new object[]
                    {
                        uniqueUserIdentity,
                        managedThreadId,
                        exception.GetTraceFormatter(),
                        commandStringForTrace
                    });
                    ErrorHandlingUtil.SendReportForCriticalException(currentHttpContext, exception);
                    DDIHelper.Trace("Async work item {0}, Error: {1}", new object[]
                    {
                        workItem.Id,
                        exception.GetTraceFormatter()
                    });
                }
                finally
                {
                    AsyncServiceManager.workerThreads.Remove(managedThreadId);
                    lock (workItem)
                    {
                        workItem.Results = powerShellResults;
                        ProgressRecord progressRecord    = workItem.LegacyProgressRecord ?? ((workItem.ProgressCalculator == null) ? new ProgressRecord() : workItem.ProgressCalculator.ProgressRecord);
                        powerShellResults.ProgressRecord = progressRecord;
                        progressRecord.HasCompleted      = true;
                        progressRecord.IsCancelled       = workItem.Cancelled;
                        workItem.FinishedEvent.Set();
                    }
                    asyncTaskBudget.UnregisterAsyncTask(uniqueUserIdentity, throttlingType);
                    if (onCompleted != null)
                    {
                        onCompleted(powerShellResults);
                    }
                    EcpEventLogConstants.Tuple_AsyncWebRequestEnded.LogEvent(new object[]
                    {
                        uniqueUserIdentity,
                        managedThreadId,
                        commandStringForTrace
                    });
                    ActivityContextManager.CleanupActivityContext(HttpContext.Current);
                    Thread.CurrentThread.CurrentCulture = (Thread.CurrentThread.CurrentUICulture = currentCulture);
                    Thread.CurrentPrincipal             = currentPrincipal;
                    OperationContext.Current            = value2;
                    HttpContext.Current = value3;
                    GC.KeepAlive(rbacSession);
                }
            });
            return(new PowerShellResults
            {
                ProgressId = workItem.Id
            });
        }
        private RbacPrincipal CreateRbacPrincipal(IIdentity identity, string tenantDomain, string cacheKey, HttpContext httpContext)
        {
            ExTraceGlobals.ReportingWebServiceTracer.TraceDebug <string, string, string>((long)this.GetHashCode(), "[RbacPrincipalManager::CreateRbacPrincipal] Create RbacPrincipal. Identity: {0}; tenantDomain: {1}; cacheKey: '{2}'", identity.GetSafeName(true), tenantDomain ?? string.Empty, cacheKey);
            ExchangeRunspaceConfigurationSettings rbacSettings = null;

            ElapsedTimeWatcher.Watch(RequestStatistics.RequestStatItem.NewExchangeRunspaceConfigurationSettingsLatency, delegate
            {
                rbacSettings = new ExchangeRunspaceConfigurationSettings(ExchangeRunspaceConfigurationSettings.ExchangeApplication.ReportingWebService, tenantDomain, ExchangeRunspaceConfigurationSettings.SerializationLevel.None);
            });
            ReportingSchema schema = ReportingSchema.GetCurrentReportingSchema(httpContext);

            try
            {
                RequestStatistics requestStatistics = HttpContext.Current.Items[RequestStatistics.RequestStatsKey] as RequestStatistics;
                if (requestStatistics != null)
                {
                    requestStatistics.AddExtendedStatisticsDataPoint("AuthType", identity.AuthenticationType);
                }
                using (new AverageTimePerfCounter(RwsPerfCounters.AverageRbacPrincipalCreation, RwsPerfCounters.AverageRbacPrincipalCreationBase, true))
                {
                    RwsExchangeRunspaceConfiguration rbacConfiguration = null;
                    ElapsedTimeWatcher.Watch(RequestStatistics.RequestStatItem.NewRwsExchangeRunspaceConfigurationLatency, delegate
                    {
                        rbacConfiguration = RwsExchangeRunspaceConfiguration.NewInstance(identity, rbacSettings, schema.CmdletFilter, this.GetSnapinSet());
                    });
                    RbacPrincipal rbacPrincipal = null;
                    ElapsedTimeWatcher.Watch(RequestStatistics.RequestStatItem.NewRbacPrincipalLatency, delegate
                    {
                        rbacPrincipal = new RbacPrincipal(rbacConfiguration, cacheKey);
                    });
                    return(rbacPrincipal);
                }
            }
            catch (CmdletAccessDeniedException ex)
            {
                HttpRuntime.Cache.Remove(cacheKey);
                ExTraceGlobals.ReportingWebServiceTracer.TraceError <CmdletAccessDeniedException>((long)this.GetHashCode(), "[RbacPrincipalManager::CreateRbacPrincipal] CmdletAccessDeniedException: {0}", ex);
                ServiceDiagnostics.ThrowError(ReportingErrorCode.ErrorTenantNotInOrgScope, Strings.ErrorTenantNotInOrgScope(tenantDomain), ex);
            }
            catch (CannotResolveTenantNameException ex2)
            {
                HttpRuntime.Cache.Remove(cacheKey);
                ExTraceGlobals.ReportingWebServiceTracer.TraceError <CannotResolveTenantNameException>((long)this.GetHashCode(), "[RbacPrincipalManager::CreateRbacPrincipal] CannotResolveTenantNameException: {0}", ex2);
                ServiceDiagnostics.ThrowError(ReportingErrorCode.ErrorTenantNotResolved, Strings.ErrorTenantNotResolved(tenantDomain), ex2);
            }
            catch (ADTransientException ex3)
            {
                HttpRuntime.Cache.Remove(cacheKey);
                ExTraceGlobals.ReportingWebServiceTracer.TraceError <ADTransientException>((long)this.GetHashCode(), "[RbacPrincipalManager::CreateRbacPrincipal] ADTransientException: {0}", ex3);
                ServiceDiagnostics.ThrowError(ReportingErrorCode.ADTransientError, Strings.ADTransientError, ex3);
            }
            catch (DataSourceOperationException ex4)
            {
                HttpRuntime.Cache.Remove(cacheKey);
                ExTraceGlobals.ReportingWebServiceTracer.TraceError <DataSourceOperationException>((long)this.GetHashCode(), "[RbacPrincipalManager::CreateRbacPrincipal] DataSourceOperationException: {0}", ex4);
                ServiceDiagnostics.ThrowError(ReportingErrorCode.ADOperationError, Strings.ADOperationError, ex4);
            }
            catch (TimeoutException ex5)
            {
                HttpRuntime.Cache.Remove(cacheKey);
                ExTraceGlobals.ReportingWebServiceTracer.TraceError <TimeoutException>((long)this.GetHashCode(), "[RbacPrincipalManager::CreateRbacPrincipal] TimeoutException: {0}", ex5);
                ServiceDiagnostics.ThrowError(ReportingErrorCode.CreateRunspaceConfigTimeoutError, Strings.CreateRunspaceConfigTimeoutError, ex5);
            }
            catch (Exception ex6)
            {
                HttpRuntime.Cache.Remove(cacheKey);
                ExTraceGlobals.ReportingWebServiceTracer.TraceError <Exception>((long)this.GetHashCode(), "[RbacPrincipalManager::CreateRbacPrincipal] Exception: {0}", ex6);
                ServiceDiagnostics.ThrowError(ReportingErrorCode.UnknownError, Strings.UnknownError, ex6);
            }
            return(null);
        }
Esempio n. 29
0
 internal static bool ShouldRenderLogoutLink(RbacPrincipal rbacPrincipal)
 {
     return(rbacPrincipal.IsInRole("MailboxFullAccess+!DelegatedAdmin+!ByoidAdmin"));
 }
Esempio n. 30
0
 internal static bool ShouldRenderOwaLink(RbacPrincipal rbacPrincipal, bool showAdminFeature)
 {
     return(!showAdminFeature && !NavigationUtil.LaunchedFromOutlook && rbacPrincipal.IsInRole("Mailbox+OWA+MailboxFullAccess"));
 }