protected void Page_Load (object sender, EventArgs e) { state = ("" + Request["state"]).Trim().ToLower(); account = ("" + Request["account"]).Trim().ToLower(); currentUserId = Convert.ToInt32(HttpContext.Current.User.Identity.Name); _currentUser = Person.FromIdentity(currentUserId); _authority = _currentUser.GetAuthority(); if (!_authority.HasPermission(Permission.CanEditMailDB, Organization.PPSEid, -1, Authorization.Flag.AnyGeographyExactOrganization)) { Response.Write("You do not have authority to use this."); Response.End(); } if (!IsPostBack) { if (state == "edit") { LabelAccount.Text = account; LabelAccount.Font.Bold = true; addSpan.Visible = false; pwTR.Visible = true; ButtonDelete.Visible = true; List<MailServerDatabase.MailAccount> objAccList = MailServerDatabase.SearchAccount(account); TextBoxForward.Text = objAccList.Count > 0 ? "" + (objAccList[0].forwardedTo.Count > 0 ? objAccList[0].forwardedTo[0] : "") : ""; } else if (state == "add") { LabelAccount.Text = ""; TextBoxAccount.Text = account; addSpan.Visible = true; pwTR.Visible = true; ButtonDelete.Visible = false; } } }
public RadTreeNodeData[] GetNodes (RadTreeNodeData node, object context) { if (node.Attributes.ContainsKey("perm")) { int persID = int.Parse(node.Attributes["uid"].ToString()); authority = Person.FromIdentity(persID).GetAuthority(); PermissionSet ps = new PermissionSet(node.Attributes["perm"].ToString()); requiredPermission = ps.permsList[0].perm; } List<RadTreeNodeData> nodes = new List<RadTreeNodeData>(); int parentId = Organization.RootIdentity; int.TryParse(node.Value, out parentId); Organizations orgs = Organization.FromIdentity(parentId).Children; foreach (Organization org in orgs) { RadTreeNodeData nodeData = new RadTreeNodeData(); nodeData.Text = org.Name; nodeData.Value = org.Identity.ToString(); Organizations orgs2 = Organization.FromIdentity(org.Identity).Children; if (orgs2.Count > 0) nodeData.ExpandMode = TreeNodeExpandMode.WebService; SetAuthorityForNode(nodeData); nodes.Add(nodeData); } return nodes.ToArray(); }
public static Authority Instance() { if (authority == null) { authority = new Authority(); } return authority; }
/// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param> protected override void OnInitComplete (System.EventArgs e) { base.OnInitComplete(e); int currentUserId = 0; currentUserId = Convert.ToInt32(HttpContext.Current.User.Identity.Name); _currentUser = Person.FromIdentity(currentUserId); _authority = _currentUser.GetAuthority(); }
public void CertificateInstallationShouldRemoveSSLIfFound() { var ca = new Authority("TestAuthority"); var sslCert = ca.GetSSLCertificate(); _mockPersonalStore.Setup(_ => _.Find(sslCert.Thumbprint)) .Returns(sslCert); _certInstall.UninstallSSL(sslCert.Thumbprint); _mockPersonalStore.Verify(_ => _.Find(sslCert.Thumbprint)); _mockPersonalStore.Verify(_ => _.Delete(sslCert)); }
public OperationResult Post(WrapUserResponse userResponse, Authority authorization) { if (authorization == Authority.Deny) return UserDenied(userResponse); if(_accounts.Verify(userResponse.Username, userResponse.Password)) { return UserAccepted(userResponse); } return UserBadCredentials(); }
public Authority BuildAuthority(string authorityKey, IList<Role> roles) { lock(_lock) { // prepare roles foreach(var role in roles) if(role.RuntimeData == null) BuildRuntimeData(_app.Model, role); var authority = new Authority(authorityKey, roles); BuildAuthorityPermissions(authority); return authority; } }
public void CertificateInstallationShouldInstallBothCertificates() { var ca = new Authority("TestAuthority"); var sslCert = ca.GetSSLCertificate(); _mockPersonalStore.Setup(_ => _.Find(ca.X509Certificate.Thumbprint)) .Returns(ca.X509Certificate); _certInstall.Install(ca.X509Certificate, sslCert); _mockPersonalStore.Verify(_ => _.Save(ca.X509Certificate)); _mockRootStore.Verify(_ => _.Save(ca.X509Certificate)); _mockPersonalStore.Verify(_ => _.Delete(ca.X509Certificate)); _mockPersonalStore.Verify(_ => _.Save(sslCert)); }
protected override void OnLoad(EventArgs e) { int currentUserId = 0; int currentOrganizationId = 0; string identity = HttpContext.Current.User.Identity.Name; string[] identityTokens = identity.Split(','); string userIdentityString = identityTokens[0]; string organizationIdentityString = identityTokens[1]; currentUserId = Convert.ToInt32(userIdentityString); currentOrganizationId = Convert.ToInt32(organizationIdentityString); _currentUser = Person.FromIdentity(currentUserId); _currentOrganization = Organization.FromIdentity(currentOrganizationId); _authority = _currentUser.GetAuthority(); base.OnLoad(e); }
public static AuthenticationRequestParameters CreateAuthenticationRequestParameters( IServiceBundle serviceBundle, Authority authority = null, HashSet <string> scopes = null, RequestContext requestContext = null) { var commonParameters = new AcquireTokenCommonParameters { Scopes = scopes ?? TestConstants.s_scope, }; authority = authority ?? Authority.CreateAuthority(TestConstants.AuthorityTestTenant); requestContext = requestContext ?? new RequestContext(serviceBundle, Guid.NewGuid()); return(new AuthenticationRequestParameters( serviceBundle, new TokenCache(serviceBundle, false), commonParameters, requestContext, authority) { }); }
/// <summary> /// 创建权限 /// </summary> /// <param name="infoSystemNo">信息系统编号</param> /// <param name="applicationType">应用程序类型</param> /// <param name="authorityName">权限名称</param> /// <param name="authorityPath">权限路径</param> /// <param name="description">描述</param> public void CreateAuthority(string infoSystemNo, ApplicationType applicationType, string authorityName, string authorityPath, string description) { #region # 验证 if (this._repMediator.AuthorityRep.ExistsPath(infoSystemNo, applicationType, authorityPath)) { throw new ArgumentOutOfRangeException(nameof(authorityPath), "给定信息系统与应用程序类型已存在该权限路径!"); } #endregion Authority authority = new Authority(infoSystemNo, applicationType, authorityName, authorityPath, description); //为系统管理员角色追加权限 Guid adminRoleId = this._repMediator.RoleRep.GetManagerRoleId(infoSystemNo); Role adminRole = this._unitOfWork.Resolve <Role>(adminRoleId); adminRole.AppendAuthorities(new[] { authority }); this._unitOfWork.RegisterAdd(authority); this._unitOfWork.RegisterSave(adminRole); this._unitOfWork.Commit(); }
/// <summary> /// Handle a request. /// </summary> /// <param name="pDisplay">The display which called this function.</param> /// <param name="pSurface">The surface which this display is hosted on.</param> /// <param name="dArguments">A dictionary of arguments which are passed to the function as parameters.</param> /// <returns>True if the request was processed sucessfully. False if there was an error.</returns> public bool ProcessRequest(Display pDisplay, Surface pSurface, JSObject dArguments) { // Find the new surface. var pTargetSurface = Authority.FindSurface(dArguments.GetValueOrDefault("target", "")); if (pTargetSurface == null) { Log.Write("Cannot swap display to target surface. Missing valid 'target' parameter.", pDisplay.ToString(), Log.Type.DisplayWarning); return(false); } // Check the surface this view is on is not our target. if (pTargetSurface == pDisplay.ActiveSurface) { Log.Write("Cannot swap display to target surface because it is already there.", pDisplay.ToString(), Log.Type.DisplayWarning); return(false); } // If the target surface has a display, get a reference and remove it. Display pOtherView = pTargetSurface.ActiveDisplay; if (pOtherView != null) { Authority.RemoveDisplay(pOtherView); } // Remove this display from this surface and put it on the target surface. Authority.RemoveDisplay(pDisplay); Authority.ShowDisplay(pDisplay, pTargetSurface); // Now put the other display on the original surface. if (pOtherView != null) { Authority.ShowDisplay(pOtherView, pSurface); } // Boom. return(true); }
public AuthenticationRequestParameters( IServiceBundle serviceBundle, ITokenCacheInternal tokenCache, AcquireTokenCommonParameters commonParameters, RequestContext requestContext, string homeAccountId = null) { _serviceBundle = serviceBundle; _commonParameters = commonParameters; Authority = Authority.CreateAuthorityForRequest(serviceBundle.Config.AuthorityInfo, commonParameters.AuthorityOverride); UserConfiguredAuthority = Authority; ClientId = serviceBundle.Config.ClientId; CacheSessionManager = new CacheSessionManager(tokenCache, this); Scope = ScopeHelper.CreateScopeSet(commonParameters.Scopes); RedirectUri = new Uri(serviceBundle.Config.RedirectUri); RequestContext = requestContext; IsBrokerConfigured = serviceBundle.Config.IsBrokerEnabled; // Set application wide query parameters. ExtraQueryParameters = serviceBundle.Config.ExtraQueryParameters ?? new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase); // Copy in call-specific query parameters. if (commonParameters.ExtraQueryParameters != null) { foreach (KeyValuePair <string, string> kvp in commonParameters.ExtraQueryParameters) { ExtraQueryParameters[kvp.Key] = kvp.Value; } } ClaimsAndClientCapabilities = ClaimsHelper.GetMergedClaimsAndClientCapabilities( _commonParameters.Claims, _serviceBundle.Config.ClientCapabilities); HomeAccountId = homeAccountId; }
/// <summary> /// 批量创建权限 /// </summary> /// <param name="systemNo">信息系统编号</param> /// <param name="authorityParams">权限参数模型集</param> /// <returns>权限Id集</returns> public IEnumerable <Guid> CreateAuthorities(string systemNo, IEnumerable <AuthorityParam> authorityParams) { //验证 Assert.IsTrue(this._repMediator.InfoSystemRep.Exists(systemNo), $"编号为\"{systemNo}\"的信息系统不存在!"); IList <Guid> authorityIds = new List <Guid>(); foreach (AuthorityParam param in authorityParams) { Authority authority = new Authority(systemNo, param.AuthorityName, param.EnglishName, param.Description, param.AssemblyName, param.Namespace, param.ClassName, param.MethodName); //验证 Assert.IsFalse(this._repMediator.AuthorityRep.ExistsPath(authority.AuthorityPath), "已存在该权限!"); this._unitOfWork.RegisterAdd(authority); authorityIds.Add(authority.Id); } this._unitOfWork.UnitedCommit(); return(authorityIds); }
public ActionResult A74Detail() { ViewBag.year = new SelectList( A7Repository.GetA51SearchYear() .Select(x => new { Text = x, Value = x.Split('(')[0] }), "Value", "Text"); var _Authority = new Authority(Table_Type.A51.ToString()); ViewBag.UserAccount = _Authority.userAccount; var datas = new List <SelectOption>() { new SelectOption() { Text = " ", Value = " " } }; if (_Authority.Auditors.Any()) { datas.AddRange(_Authority.Auditors.Select(x => new SelectOption() { Text = $"{x.User_Account}({x.User_Name})", Value = x.User_Account })); } ViewBag.Auditor = new SelectList(datas, "Value", "Text"); ViewBag.Authority = _Authority.AuthorityType.GetDescription(); ViewBag.Status = new SelectList(new List <SelectOption>() { new SelectOption() { Text = "1.啟用", Value = Audit_Type.Enable.ToString() }, new SelectOption() { Text = "2.暫不啟用", Value = Audit_Type.TempDisabled.ToString() } }, "Value", "Text"); return(View()); }
//初始化权限 private void initAuthorityMenu() { const string menuArr = "组类"; List <string> listModel = Authority.ReadMenusXmlData("AuthorityUrl").Where(c => menuArr.Contains(c.ParentID)).Select(c => c.MenuName).ToList <string>(); foreach (NavBarGroup g in navBarControl1.Groups) { g.Visible = false; foreach (NavBarItemLink i in g.ItemLinks) { if (listModel.Contains(i.Caption)) { i.Visible = true; g.Visible = true; } else { i.Visible = false; } } } }
public ActionResult EditAuthority(Authority authority) { DealViewBag("UserAuthority"); if (ModelState.IsValid) { if (allUserInfo.SaveAuthority(authority) == 1) { TempData["Success"] = "修改成功!"; } else { TempData["Fault"] = "修改失败!"; ViewBag.EditAuthorityModal = true; } } else { TempData["Fault"] = "修改失败!"; ViewBag.EditAuthorityModal = true; } return(View("Authority", allUserInfo.Authoritys)); }
/// <summary> /// 添加职权信息 /// </summary> /// <param name="authority"></param> /// <returns></returns> public ActionResult AddAuthority(Authority authority) { DealViewBag("UserAuthority"); if (ModelState.IsValid) { if (allUserInfo.AddAuthority(authority) == 1) { TempData["Success"] = "添加成功"; } else { TempData["Fault"] = "添加失败,该编号已存在!"; ViewBag.Number = authority.Number; ViewBag.AuthorityString = authority.AuthorityString; } } else { TempData["Fault"] = "添加失败!请检查输入内容!"; } return(View("Authority", allUserInfo.Authoritys)); }
public void CanonicalAuthorityInitTest() { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); const string UriNoPort = "https://login.microsoftonline.in/mytenant.com"; const string UriNoPortTailSlash = "https://login.microsoftonline.in/mytenant.com/"; const string UriDefaultPort = "https://login.microsoftonline.in:443/mytenant.com"; const string UriCustomPort = "https://login.microsoftonline.in:444/mytenant.com"; const string UriCustomPortTailSlash = "https://login.microsoftonline.in:444/mytenant.com/"; var authority = Authority.CreateAuthority(UriNoPort); Assert.AreEqual(UriNoPortTailSlash, authority.AuthorityInfo.CanonicalAuthority); authority = Authority.CreateAuthority(UriDefaultPort); Assert.AreEqual(UriNoPortTailSlash, authority.AuthorityInfo.CanonicalAuthority); authority = Authority.CreateAuthority(UriCustomPort); Assert.AreEqual(UriCustomPortTailSlash, authority.AuthorityInfo.CanonicalAuthority); }
public void NotEnoughPathSegmentsTest() { try { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); var instance = Authority.CreateAuthority("https://login.microsoftonline.in/tfp/"); Assert.IsNotNull(instance); Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.B2C); var resolver = new AuthorityResolutionManager(); var endpoints = resolver.ResolveEndpoints( instance, null, new RequestContext(serviceBundle, Guid.NewGuid())); Assert.Fail("test should have failed"); } catch (Exception exc) { Assert.IsInstanceOfType(exc, typeof(ArgumentException)); Assert.AreEqual(MsalErrorMessage.B2cAuthorityUriInvalidPath, exc.Message); } }
public async Task ConfidentialClientWithSignedAssertionTestAsync() { var confidentialClientAuthority = PublicCloudTestAuthority; var claims = GetClaims(); var confidentialApp = ConfidentialClientApplicationBuilder .Create(PublicCloudConfidentialClientID) .WithAuthority(new Uri(confidentialClientAuthority), true) .WithClientAssertion(GetSignedClientAssertionUsingMsalInternal(PublicCloudConfidentialClientID, claims)) .WithTestLogging() .Build(); var appCacheRecorder = confidentialApp.AppTokenCache.RecordAccess(); var authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope) .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); appCacheRecorder.AssertAccessCounts(1, 1); Assert.AreEqual(TokenSource.IdentityProvider, authResult.AuthenticationResultMetadata.TokenSource); Assert.AreEqual( GetExpectedCacheKey(PublicCloudConfidentialClientID, Authority.CreateAuthority(confidentialClientAuthority, false).TenantId), appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey); Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache); ValidateClaimsInAssertion(claims, ((ConfidentialClientApplication)confidentialApp).ClientCredential.SignedAssertion); MsalAssert.AssertAuthResult(authResult); // call again to ensure cache is hit authResult = await confidentialApp.AcquireTokenForClient(s_keyvaultScope) .ExecuteAsync(CancellationToken.None) .ConfigureAwait(false); appCacheRecorder.AssertAccessCounts(2, 1); Assert.AreEqual(TokenSource.Cache, authResult.AuthenticationResultMetadata.TokenSource); Assert.AreEqual( GetExpectedCacheKey(PublicCloudConfidentialClientID, Authority.CreateAuthority(confidentialClientAuthority, false).TenantId), appCacheRecorder.LastAfterAccessNotificationArgs.SuggestedCacheKey); Assert.IsTrue(appCacheRecorder.LastAfterAccessNotificationArgs.IsApplicationCache); }
protected override void OnOpen() { Console.WriteLine(" * Attempted socket connection"); string authBase64 = Context.QueryString["Auth"]; authBase64 = Uri.UnescapeDataString(authBase64); // Defensive programming - % sign does not exist in base64 so this won't ever collapse a working encoding if (Authority.IsSystemAuthorityTokenValid(authBase64)) { _authority = null; // System authority Console.WriteLine(" - - valid system authentication token"); } else { _authority = Authority.FromEncryptedXml(authBase64); this.Sessions.RegisterSession(this, this._authority); // Only register non-system sessions Console.WriteLine(" - - authenticated: " + this._authority.Person.Canonical); } base.OnOpen(); }
public void TestPluginSelection() { var ex = AssertException.Throws <MsalClientException>( () => _wamBroker.IsMsaRequest(Authority.CreateAuthority(TestConstants.B2CAuthority), null, false)); Assert.AreEqual(MsalError.WamNoB2C, ex.ErrorCode); Assert.IsFalse( _wamBroker.IsMsaRequest(Authority.CreateAuthority(TestConstants.ADFSAuthority), null, false), "ADFS authorities should be handled by AAD plugin"); Assert.IsTrue( _wamBroker.IsMsaRequest(Authority.CreateAuthority(TestConstants.AuthorityCommonTenant), TestConstants.MsaTenantId, false), "Common authority - look at account tenant ID to determine plugin"); Assert.IsFalse( _wamBroker.IsMsaRequest(Authority.CreateAuthority(TestConstants.AuthorityCommonTenant), TestConstants.TenantId, false), "Common authority - look at account tenant ID to determine plugin"); Assert.IsFalse( _wamBroker.IsMsaRequest(Authority.CreateAuthority(TestConstants.AuthorityOrganizationsTenant), TestConstants.TenantId, false), "Organizations authority - AAD plugin unless MSA-pt"); Assert.IsFalse( _wamBroker.IsMsaRequest(Authority.CreateAuthority(TestConstants.AuthorityOrganizationsTenant), TestConstants.TenantId, true), "Organizations authority with MSA-pt - based on home account id"); Assert.IsTrue( _wamBroker.IsMsaRequest(Authority.CreateAuthority(TestConstants.AuthorityOrganizationsTenant), TestConstants.MsaTenantId, true), "Organizations authority with MSA-pt - based on home account id"); Assert.IsTrue( _wamBroker.IsMsaRequest(Authority.CreateAuthority(TestConstants.AuthorityConsumersTenant), TestConstants.TenantId, false), "Consumer authority - msa plugin"); Assert.IsFalse( _wamBroker.IsMsaRequest(Authority.CreateAuthority(TestConstants.AuthorityGuidTenant), TestConstants.TenantId, true), "Tenanted authorities - AAD plugin"); }
protected void Page_Load (object sender, EventArgs e) { _currentUser = Person.FromIdentity(CurrentUserId); _authority = _currentUser.GetAuthority(); if (!Page.IsPostBack) { List<int> organizationIds = new List<int>(); foreach (Membership membership in DisplayedPerson.GetMemberships()) { foreach (Organization org in membership.Organization.GetLine()) { if (!organizationIds.Contains(org.Identity)) { organizationIds.Add(org.Identity); } } } this.ViewState["Organizations"] = organizationIds.ToArray(); } }
private void LoadGridInfos() { grdGridColumns.DataRows.Clear(); IBoundGrid masterGrid = m_masterGrid as IBoundGrid; if (masterGrid != null) { Dictionary <string, GridColumnInfo> visibleColumns = new Dictionary <string, GridColumnInfo>(); bool hasInfo = GridSettingInfoCollection.Instance[masterGrid.GridName].GridColumnInfos.Count > 0; foreach (GridColumnInfo info in GridSettingInfoCollection.Instance[masterGrid.GridName].GridColumnInfos) { if (!Authority.AuthorizeByRule(info.ColumnVisible)) { continue; } visibleColumns[info.GridColumnName] = info; } foreach (Xceed.Grid.Column column in masterGrid.Columns) { if (hasInfo && !visibleColumns.ContainsKey(column.FieldName)) { continue; } Xceed.Grid.DataRow row = grdGridColumns.DataRows.AddNew(); row.Cells["是否显示"].Value = column.Visible; row.Cells["名称"].Value = column.Title; row.EndEdit(); if (visibleColumns.ContainsKey(column.FieldName)) { row.ReadOnly = Authority.AuthorizeByRule(visibleColumns[column.FieldName].NotNull); } } } }
/// <summary> /// 重新读入是否显示等属性 /// </summary> public override void LoadDefaultLayout() { foreach (GridColumnInfo info in ADInfoBll.Instance.GetGridColumnInfos(this.GridName)) { Xceed.Grid.Column column = this.Columns[info.GridColumnName]; if (column != null) { column.Visible = Authority.AuthorizeByRule(info.ColumnVisible); column.VisibleIndex = info.SeqNo; } else { foreach (Xceed.Grid.DataRow row in this.DataRows) { if (row.DetailGrids.Count > 0) { LoadDefaultLayout(row.DetailGrids[0], info); } } } } }
private void CreateAllFilesForRegion(Authority region, RegionFilterModel filterModel) { int orgsInRegionCount; if (region.IsOutsideUnitedKingdom) { orgsInRegionCount = region.HauntedPubCount; } else { var firstDescendantAuthoritiesInRegion = _queryManager.GetHauntedFirstDescendantAuthoritiesInRegion(region.Id); orgsInRegionCount = firstDescendantAuthoritiesInRegion.Sum(x => x.HauntedPubCount); } if (orgsInRegionCount == 0) { return; } var inRegion = CreateRegionHeaderFile(region, orgsInRegionCount); if (!inRegion.Any()) { CreateAuthorityFilesTop(region); } else { // todo - work out why filterModel == null? var filtered = inRegion.Where(authority => filterModel == null || filterModel.Division.IsNullOrEmpty() || authority.Name == filterModel.Division); foreach (var authority in filtered) { CreateAuthorityFilesTop(authority); } } }
private void CreateAuthorityFilesTop(Authority authority) { if (authority == null) { return; } if (authority.Authoritys != null && authority.Authoritys.Any()) { if (authority.Authoritys == null) { return; } foreach (var district in authority.Authoritys) { CreateAuthorityFiles(district); } } CreateAuthorityFiles(authority); }
private async Task <AuthenticationResult> AcquireTokenAsync(IEnumerable <string> scopes, IAccount account, UIBehavior behavior, string extraQueryParameters, IEnumerable <string> extraScopesToConsent, string authority, UIParent parent, string userName, string password, bool cacheResult) { Authority authorityInstance = Instance.Authority.CreateAuthority(ServiceBundle, authority, ValidateAuthority); var requestParams = CreateRequestParameters(authorityInstance, scopes, account, cacheResult ? UserTokenCache : null); requestParams.ExtraQueryParameters = extraQueryParameters; var handler = new NonInteractiveLoginRequest( ServiceBundle, requestParams, ApiEvent.ApiIds.AcquireTokenWithScopeUserBehaviorAuthority, extraScopesToConsent, behavior, CreateWebAuthenticationDialog(parent, behavior, requestParams.RequestContext), userName, password); return(await handler.RunAsync(CancellationToken.None).ConfigureAwait(false)); }
/// <summary> /// 根据参数名创建参数(如是单个参数则返回此参数,如是多个,则返回object[]) /// </summary> /// <param name="paramName"></param> /// <param name="hasParamCreatorInfos"></param> /// <returns></returns> public static object CreateParam(string paramName, out bool hasParamCreatorInfos) { IList <ParamCreatorInfo> list = ADInfoBll.Instance.GetParamCreatorInfos(paramName); if (list.Count == 0) { hasParamCreatorInfos = false; return(null); } hasParamCreatorInfos = true; IList <ParamCreatorInfo> realList = new List <ParamCreatorInfo>(); foreach (ParamCreatorInfo i in list) { if (string.IsNullOrEmpty(i.Permission) || Authority.AuthorizeByRule(i.Permission)) { realList.Add(i); } } if (realList.Count == 0) { return(null); } else if (realList.Count == 1) { return(CreateParam(realList[0])); } else { object[] arr = new object[realList.Count]; for (int i = 0; i < realList.Count; ++i) { arr[i] = CreateParam(realList[i]); } return(arr); } }
public void GetAccessTokenUserAssertionMismatchInCacheTest() { TokenCache cache = new TokenCache() { ClientId = TestConstants.ClientId }; AccessTokenCacheItem atItem = new AccessTokenCacheItem() { Authority = TestConstants.AuthorityHomeTenant, ClientId = TestConstants.ClientId, TokenType = "Bearer", ScopeSet = TestConstants.Scope, ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromHours(1)), RawIdToken = MockHelpers.CreateIdToken(TestConstants.UniqueId, TestConstants.DisplayableId) }; // create key out of access token cache item and then // set it as the value of the access token. AccessTokenCacheKey atKey = atItem.GetAccessTokenItemKey(); atItem.AccessToken = atKey.ToString(); atItem.UserAssertionHash = CryptographyHelper.CreateBase64UrlEncodedSha256Hash(atKey.ToString()); cache.TokenCacheAccessor.AccessTokenCacheDictionary[atKey.ToString()] = JsonHelper.SerializeToJson(atItem); var param = new AuthenticationRequestParameters() { RequestContext = new RequestContext(Guid.Empty, null), ClientId = TestConstants.ClientId, Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false), Scope = TestConstants.Scope, UserAssertion = new UserAssertion(atItem.UserAssertionHash + "-random") }; AccessTokenCacheItem item = cache.FindAccessToken(param); // cache lookup should fail because there was userassertion hash did not match the one // stored in token cache item. Assert.IsNull(item); }
public void B2CMicrosoftOnlineCreateAuthority() { using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); // add mock response for tenant endpoint discovery httpManager.AddMockHandler( new MockHttpMessageHandler { Method = HttpMethod.Get, Url = "https://login.microsoftonline.com/tfp/mytenant.com/my-policy/v2.0/.well-known/openid-configuration", ResponseMessage = MockHelpers.CreateSuccessResponseMessage( File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("OpenidConfiguration-B2C.json"))) }); Authority instance = Authority.CreateAuthority( serviceBundle, "https://login.microsoftonline.com/tfp/mytenant.com/my-policy/", true); Assert.IsNotNull(instance); Assert.AreEqual(instance.AuthorityType, AuthorityType.B2C); Task.Run( async() => { await instance.ResolveEndpointsAsync( null, new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))).ConfigureAwait(false); }).GetAwaiter().GetResult(); Assert.AreEqual( "https://login.microsoftonline.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/my-policy/oauth2/v2.0/authorize", instance.AuthorizationEndpoint); Assert.AreEqual( "https://login.microsoftonline.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/my-policy/oauth2/v2.0/token", instance.TokenEndpoint); Assert.AreEqual("https://sts.windows.net/6babcaad-604b-40ac-a9d7-9fd97c0b779f/", instance.SelfSignedJwtAudience); } }
public void FailedTenantDiscoveryMissingEndpointsTest() { using (var httpManager = new MockHttpManager()) { var serviceBundle = ServiceBundle.CreateWithCustomHttpManager(httpManager); //add mock response for tenant endpoint discovery httpManager.AddMockHandler( new MockHttpMessageHandler { Method = HttpMethod.Get, Url = "https://login.microsoftonline.in/mytenant.com/v2.0/.well-known/openid-configuration", ResponseMessage = MockHelpers.CreateSuccessResponseMessage( File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("OpenidConfiguration-MissingFields.json"))) }); var aadInstanceDiscovery = new AadInstanceDiscovery(httpManager, new TelemetryManager()); Authority instance = Authority.CreateAuthority(serviceBundle, "https://login.microsoftonline.in/mytenant.com", false); Assert.IsNotNull(instance); Assert.AreEqual(instance.AuthorityType, AuthorityType.Aad); try { Task.Run( async() => { await instance.ResolveEndpointsAsync( null, new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))).ConfigureAwait(false); }).GetAwaiter().GetResult(); Assert.Fail("validation should have failed here"); } catch (MsalClientException exc) { Assert.AreEqual(CoreErrorCodes.TenantDiscoveryFailedError, exc.ErrorCode); } } }
public async Task ForceRefreshParameterFalseTestAsync() { await RunWithMockHttpAsync( async (httpManager, serviceBundle, receiver) => { httpManager.AddInstanceDiscoveryMockHandler(); var cache = new TokenCache(); _tokenCacheHelper.PopulateCacheForClientCredential(cache.TokenCacheAccessor); string authority = Authority.CreateAuthority(serviceBundle, MsalTestConstants.AuthorityTestTenant, false) .CanonicalAuthority; var app = new ConfidentialClientApplication( serviceBundle, MsalTestConstants.ClientId, authority, MsalTestConstants.RedirectUri, new ClientCredential(MsalTestConstants.ClientSecret), null, cache) { ValidateAuthority = false }; ICollection <MsalAccessTokenCacheItem> accessTokens = cache.GetAllAccessTokensForClient(new RequestContext(null, new MsalLogger(Guid.NewGuid(), null))); var accessTokenInCache = accessTokens .Where(item => ScopeHelper.ScopeContains(item.ScopeSet, MsalTestConstants.Scope)) .ToList().FirstOrDefault(); // Don't add mock to fail in case of network call // If there's a network call by mistake, then there won't be a proper number // of mock web request/response objects in the queue and we'll fail. var result = await app.AcquireTokenForClientAsync(MsalTestConstants.Scope, false).ConfigureAwait(false); Assert.AreEqual(accessTokenInCache.Secret, result.AccessToken); }).ConfigureAwait(false); }
public AuthenticationRequestParameters CreateAuthenticationRequestParameters( string authority, IEnumerable <string> scopes = null, ITokenCacheInternal tokenCache = null, IAccount account = null, IDictionary <string, string> extraQueryParameters = null, string claims = null, ApiEvent.ApiIds apiId = ApiEvent.ApiIds.None, bool validateAuthority = false) { scopes = scopes ?? TestConstants.s_scope; tokenCache = tokenCache ?? new TokenCache(ServiceBundle, false); var commonParameters = new AcquireTokenCommonParameters { Scopes = scopes ?? TestConstants.s_scope, ExtraQueryParameters = extraQueryParameters ?? new Dictionary <string, string>(), Claims = claims, ApiId = apiId }; var authorityObj = Authority.CreateAuthority(authority, validateAuthority); var requestContext = new RequestContext(ServiceBundle, Guid.NewGuid()); AuthenticationRequestParameters authenticationRequestParameters = new AuthenticationRequestParameters( ServiceBundle, tokenCache, commonParameters, requestContext, authorityObj) { Account = account, }; authenticationRequestParameters.RequestContext.ApiEvent = new ApiEvent(Guid.NewGuid()); return(authenticationRequestParameters); }
public void GetAppTokenFromCacheTest() { cache = new TokenCache() { ClientId = TestConstants.ClientId }; AccessTokenCacheItem item = new AccessTokenCacheItem() { Authority = TestConstants.AuthorityHomeTenant, ClientId = TestConstants.ClientId, TokenType = "Bearer", ExpiresOnUnixTimestamp = MsalHelpers.DateTimeToUnixTimestamp(DateTime.UtcNow + TimeSpan.FromSeconds(ValidExpiresIn)), RawIdToken = null, RawClientInfo = null, User = null, Scope = TestConstants.Scope.AsSingleString(), ScopeSet = TestConstants.Scope }; item.AccessToken = item.GetAccessTokenItemKey().ToString(); cache.TokenCacheAccessor.AccessTokenCacheDictionary[item.GetAccessTokenItemKey().ToString()] = JsonHelper.SerializeToJson(item); AccessTokenCacheItem cacheItem = cache.FindAccessToken(new AuthenticationRequestParameters() { IsClientCredentialRequest = true, RequestContext = new RequestContext(Guid.Empty, null), Authority = Authority.CreateAuthority(TestConstants.AuthorityHomeTenant, false), ClientId = TestConstants.ClientId, ClientCredential = TestConstants.CredentialWithSecret, Scope = TestConstants.Scope }); Assert.IsNotNull(cacheItem); Assert.AreEqual(item.GetAccessTokenItemKey().ToString(), cacheItem.GetAccessTokenItemKey().ToString()); }
private void ParseURI(String url) { int len = url.Length(); int delim = url.IndexOf(':'); if (delim == -1 || delim + 1 == len) { throw new IllegalArgumentException("invalid URL string"); } Scheme = url.Substring(0, delim).ToLowerCase(); this.Ssp = url.Substring(delim + 1); if (!Ssp.StartsWith("//")) { if (!Ssp.Equals("*")) { throw new IllegalArgumentException("invalid URL string"); } this.Authority = new Authority(Scheme, "*"); return; } String authpath = Ssp.Substring(2); delim = authpath.IndexOf('/'); String auth; if (delim == -1) { this.Path = ""; auth = authpath; } else { auth = authpath.Substring(0, delim); this.Path = authpath.Substring(delim); } this.Authority = new Authority(Scheme, auth.ToLowerCase()); }
public void FailedValidationMissingFieldsTest() { using (var harness = CreateTestHarness()) { // add mock response for instance validation harness.HttpManager.AddMockHandler( new MockHttpMessageHandler { ExpectedMethod = HttpMethod.Get, ExpectedUrl = "https://login.windows.net/common/discovery/instance", ExpectedQueryParams = new Dictionary <string, string> { { "api-version", "1.0" }, { "authorization_endpoint", "https://login.microsoft0nline.com/mytenant.com/oauth2/v2.0/authorize" }, }, ResponseMessage = MockHelpers.CreateSuccessResponseMessage("{}") }); Authority instance = Authority.CreateAuthority(harness.ServiceBundle, "https://login.microsoft0nline.com/mytenant.com"); Assert.IsNotNull(instance); Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.Aad); try { var resolver = new AuthorityEndpointResolutionManager(harness.ServiceBundle); var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, null, new RequestContext(harness.ServiceBundle, Guid.NewGuid())) .ConfigureAwait(false).GetAwaiter().GetResult(); Assert.Fail("validation should have failed here"); } catch (Exception exc) { Assert.IsNotNull(exc); } } }
public void FailedValidationMissingFieldsInDrsResponseTest() { using (var harness = CreateTestHarness()) { // add mock failure response for on-premise DRS request harness.HttpManager.AddMockHandler( new MockHttpMessageHandler { ExpectedMethod = HttpMethod.Get, ExpectedUrl = "https://enterpriseregistration.fabrikam.com/enrollmentserver/contract", ExpectedQueryParams = new Dictionary <string, string> { { "api-version", "1.0" } }, ResponseMessage = MockHelpers.CreateSuccessResponseMessage( ResourceHelper.GetTestResourceRelativePath(File.ReadAllText("drs-response-missing-field.json"))) }); Authority instance = Authority.CreateAuthority(TestConstants.OnPremiseAuthority); Assert.IsNotNull(instance); Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.Adfs); try { var resolver = new AuthorityEndpointResolutionManager(harness.ServiceBundle); var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, TestConstants.FabrikamDisplayableId, new RequestContext(harness.ServiceBundle, Guid.NewGuid())) .GetAwaiter().GetResult(); Assert.Fail("ResolveEndpointsAsync should have failed here"); } catch (Exception exc) { Assert.IsNotNull(exc); } } }
public Notification CreateNotification(Authority authority) { var notification = new Notification { Created = DateTime.Now, ExpectedMessageTemplateTypes = NotificationMessageTemplateTypeDictionary.Email | NotificationMessageTemplateTypeDictionary.Sms | NotificationMessageTemplateTypeDictionary.Web, }; List<NotificationDataRow> notificationData = GetNotificationData(authority) .Select(pair => new NotificationDataRow { Id = Guid.NewGuid(), Key = pair.Key, Data = pair.Value }) .ToList(); notification.Data = notificationData; notification.NotificationStatus = NotificationStatusDictionary.CreateSendtries; return notification; }
public int DeleteAuthority(int number) { Authority authority = gameClubEntities.Authority.Where(u => u.Number == number).FirstOrDefault(); if (authority != null) { if (gameClubEntities.UserInfo.Where(u => u.Authority == number).FirstOrDefault() == null) { gameClubEntities.Authority.Remove(authority); gameClubEntities.SaveChanges(); EFUserRecord.AddUserOperateRecord("删除了" + authority.AuthorityString + "的权限"); return(1); } else { return(0); } } else { return(0); } }
public void BeforeEachTest() { _auth = new Authority("TestAuthority"); _sslCert = _auth.GetSSLCertificate(); }
public void AfterEachTest() { _sslCert = null; _auth = null; }
internal void BuildAuthorityPermissions(Authority authority) { var nonEntPermGrants = authority.NonEntityPermissionGrants; var objPermissions = authority.ObjectPermissionTable; var dynGrants = authority.DynamicGrants; foreach (var role in authority.Roles) { foreach (var grantedPerm in role.RuntimeData.GrantedPermissions) { var dynGrant = grantedPerm.Grant as DynamicActivityGrant; if (dynGrant != null) dynGrants.Add(dynGrant); var entPerm = grantedPerm.Permission as EntityGroupPermission; if(entPerm != null) { AddEntityPermission(authority, grantedPerm.Grant, entPerm); continue; } var objPerm = grantedPerm.Permission as ObjectAccessPermission; if(objPerm != null) { foreach(var objType in objPerm.Types) { AccessType newAccess = objPerm.AccessType; AccessType oldAccess; if(objPermissions.TryGetValue(objType, out oldAccess)) newAccess |= oldAccess; objPermissions[objType] = newAccess; }//foreach objType continue; }//if objPerm != null //Non-entity permission nonEntPermGrants.Add(grantedPerm); }// foreach permGrant } //foreach role // Final processing: complete processing for each entPermSet foreach(var entPermSet in authority.EntityPermissionTable.Values) FinalizePermissionSet(entPermSet); }
public void ShouldRemoveAuthorityIfFound() { var ca = new Authority("TestAuthority"); _mockRootStore.Setup(_ => _.Find(ca.X509Certificate.Thumbprint)) .Returns(ca.X509Certificate); _certInstall.UninstallAuthority(ca.X509Certificate.Thumbprint); _mockRootStore.Verify(_ => _.Find(ca.X509Certificate.Thumbprint)); _mockRootStore.Verify(_ => _.Delete(ca.X509Certificate)); }
public void SetAuthority (Authority pAuthority, Permission pRequiredPermission) { authority = pAuthority; requiredPermission = pRequiredPermission; foreach (RadTreeNode nod in Tree.GetAllNodes()) { SetAuthorityForNode(nod); } }
public Dictionary<string, string> GetNotificationData(Authority authority) { Dictionary<string, string> res = new Dictionary<string, string>(); res["AuthorityEndDate"] = authority.EndDate.Value.ToString(Consts.DateTimeFormat); return res; }
private bool SetupMenuItemsEnabling (Authority authority, Dictionary<string, bool> enableCache, RadMenuItemCollection menuItems) { //TODO: Need to handle setup when user is not swedish, current handling supposes that top org is Organization.PPSEid string thisPageUrl = Request.Url.Segments[Request.Url.Segments.Length - 1].ToLower(); bool anyItem = false; foreach (RadMenuItem item in menuItems) { string itemID = CollectItemID(item); if (enableCache.ContainsKey(itemID)) { item.Enabled = enableCache[itemID]; } else { item.Enabled = true; if (string.IsNullOrEmpty(item.Attributes["Permission"]) == false) { string permString = item.Attributes["Permission"].ToString(); PermissionSet allowedFor = new PermissionSet(permString); item.Enabled = Authorization.CheckAuthorization(allowedFor, -1, -1, authority, Authorization.Flag.AnyGeographyAnyOrganization); } else { RadMenuItem permissionParent = item; while (permissionParent.Parent is RadMenuItem) { if (string.IsNullOrEmpty(permissionParent.Attributes["Permission"]) == false) { item.Enabled = permissionParent.Enabled; item.Attributes["Permission"] = permissionParent.Attributes["Permission"].ToString(); break; } permissionParent = permissionParent.Parent as RadMenuItem; } } if (string.IsNullOrEmpty(item.NavigateUrl) && item.Items.Count == 0) item.Enabled = false; enableCache[itemID] = item.Enabled; } string[] currentItemUrlSplit = item.NavigateUrl.ToLower().Split(new char[] { '/', '?' }, StringSplitOptions.RemoveEmptyEntries); if (Array.Exists<string>(currentItemUrlSplit, delegate(String s) { if (s == thisPageUrl) return true; else return false; }) ) { if (string.IsNullOrEmpty(item.Attributes["Permission"]) == false) { string permString = item.Attributes["Permission"].ToString(); ((PageV4Base)(this.Page)).pagePermissionDefault = new PermissionSet(permString); } } if (item.Items.Count > 0) { bool enabledSubItems = SetupMenuItemsEnabling(authority, enableCache, item.Items); if (enabledSubItems) item.Enabled = true; else item.Enabled = false; } else if (string.IsNullOrEmpty(item.NavigateUrl)) { item.Enabled = false; } anyItem |= item.Enabled; } return anyItem; }
public void ShouldThrowIfAuthorityIsNotFound() { var ca = new Authority("TestAuthority"); _mockRootStore.Setup(_ => _.Find(ca.X509Certificate.Thumbprint)) .Returns<X509Certificate>(null); Assert.Throws<CertificateNotFoundException>(() => _certInstall.UninstallAuthority(ca.X509Certificate.Thumbprint) ); }
protected void Page_Load (object sender, EventArgs e) { int currentUserId = 0; currentUserId = Convert.ToInt32(HttpContext.Current.User.Identity.Name); _currentUser = Person.FromIdentity(currentUserId); _authority = _currentUser.GetAuthority(); _listedOrganisation = null; if (ListedOrg != 0) _listedOrganisation = Organization.FromIdentity(ListedOrg); ; }
private void AddEntityPermission(Authority authority, ActivityGrant grant, EntityGroupPermission entPerm) { // Entity group permission. Go through each entity in groups var filter = grant.Filter; foreach(var entGroupRes in entPerm.GroupResources) { foreach(var entRes in entGroupRes.Entities) { var entType = entRes.EntityType; var newRecPerms = new UserRecordPermission(entPerm.AccessType, entRes.MemberMask); //Find/create entity permission set for the entity type UserEntityPermissionSet permSet = authority.GetEntityPermissionSet(entType, create: true); var log = " Source permission " + entPerm.Name + ":"; // Go through each permission and try to merge var compatiblePerm = permSet.ConditionalPermissions.FirstOrDefault(p => p.CanMerge(grant)); if(compatiblePerm == null) { //create new cumulative permission var permId = "P" + permSet.ConditionalPermissions.Count; //artificial Id var newPerm = new CumulativeRecordPermission(permId, entType, newRecPerms, grant); permSet.ConditionalPermissions.Add(newPerm); log += " - added as " + permId; } else { //merge compatiblePerm.RecordPermission.Merge(newRecPerms); compatiblePerm.SourceGrants.Add(grant); //add grant log += " - merged into " + compatiblePerm.Id; } permSet.LogBuilder.AppendLine(log); } //foreach entRes }//foreach entGroupRes }
protected void Page_Load (object sender, EventArgs e) { _authority = Person.FromIdentity(Convert.ToInt32(HttpContext.Current.User.Identity.Name)).GetAuthority(); if (!Page.IsPostBack) { // Initialize the fields from the Person object this.ButtonSaveChanges.Text = this.GetLocalResourceObject("Interface.Controls.Common.ButtonSaveChanges").ToString()/*Save Changes*/; // Member number this.TextMemberNumber.Text = Person.Identity.ToString(); this.LabelMemberNumber.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.MemberNumber").ToString()/*Member #*/ + " "; // Name this.TextName.Text = Person.Name; this.TextName.Attributes.Add("onkeypress", "OnTextChange (this);"); this.TextName.Attributes.Add("onchange", "OnTextChange (this);"); this.LabelName.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.Name").ToString()/*Name*/ + " "; // Street this.TextStreet.Text = Person.Street; this.TextStreet.Attributes.Add("onkeypress", "OnTextChange (this);"); this.TextStreet.Attributes.Add("onchange", "OnTextChange (this);"); this.LabelStreet.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.Street").ToString()/*Street*/ + " "; // Postal code, city this.TextPostalCode.Text = Person.PostalCode; this.TextPostalCode.Attributes.Add("onkeypress", "OnTextChangePostals();"); this.TextCity.Text = Person.CityName; this.TextCity.Attributes.Add("onkeypress", "OnTextChangePostals();"); this.TextCity.Attributes.Add("onchange", "OnTextChangePostals();"); this.LabelPostal.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.Postal").ToString()/*Postal code, CityName*/ + " "; this.DropDownMunicipalities.Attributes.Add("onchange", "OnChangeMunicipality();"); // Countries this.DropCountries.Attributes.Add("onchange", "OnChangeCountries();"); this.LabelCountry.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.Country").ToString()/*Country*/ + " "; Cities cities = Cities.FromPostalCode(Person.PostalCode.Replace(" ", ""), person.Country); int personGeography = person.GeographyId; DropDownMunicipalities.Items.Clear(); bool foundCurrent = false; foreach (City city in cities) { Geographies subGeo = city.Geography.GetTree(); foreach (Geography geo in subGeo) { // ignore if it is not a leaf if (geo.ChildrenCount == 0) { DropDownMunicipalities.Items.Add(new ListItem(geo.Name, geo.GeographyId.ToString())); if (geo.GeographyId == person.GeographyId) { foundCurrent = true; } } } } if (!foundCurrent) { DropDownMunicipalities.Items.Add(new ListItem(Person.Geography.Name, Person.GeographyId.ToString())); } DropDownMunicipalities.SelectedValue = Person.GeographyId.ToString(); // Populate countries Countries countries = Countries.GetAll(); foreach (Country country in countries) { DropCountries.Items.Add(new ListItem(country.Code + " " + country.Name, country.Code)); } DropCountries.Items.FindByValue(Person.Country.Code).Selected = true; // Email this.TextEmail.Text = Person.Email; this.TextEmail.Attributes.Add("onkeypress", "OnTextChange (this);"); this.TextEmail.Attributes.Add("onchange", "OnTextChange (this);"); this.LabelEmail.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.Email").ToString() + " "; if (Person.MailUnreachable) { this.LabelEmailMessage.Text = "Unreachable!"; this.LabelEmailMessage.CssClass = "ErrorMessage"; } // Party Email this.TextPartyEmail.Text = Person.PartyEmail; if (Person.PartyEmail.Length > 2) { this.ButtonSendNewPassword.Enabled = true; } else { this.ButtonSendNewPassword.Visible = false; } this.LabelPartyEmail.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.PartyEmail").ToString()/*Party Email*/ + " "; // Phone this.TextPhone.Text = Person.Phone; this.TextPhone.Attributes.Add("onkeypress", "OnTextChange(this);"); this.TextPhone.Attributes.Add("onchange", "OnTextChange(this);"); this.LabelPhone.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.Phone").ToString()/*Phone #*/ + " "; // Birthdate this.TextBirthdate.Text = Person.Birthdate.ToShortDateString(); this.TextBirthdate.Attributes.Add("onkeypress", "OnTextChange(this);"); this.TextBirthdate.Attributes.Add("onchange", "OnTextChange(this);"); this.LabelBirthdate.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.Birthdate").ToString()/*Birthdate*/ + " "; // Gender this.DropGenders.SelectedValue = Person.Gender.ToString(); this.DropGenders.Attributes.Add("onclick", "OnTextChange(this);"); // Handle try { this.TextHandle.Text = Person.Handle; } catch (Exception ex) { this.TextHandle.Text = "Connection Error"; this.TextHandle.ToolTip = ex.Message ; this.TextHandle.Enabled = false; } this.TextHandle.Attributes.Add("onkeypress", "OnTextChange(this);"); this.TextHandle.Attributes.Add("onchange", "OnTextChange(this);"); this.LabelHandle.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.ForumHandle").ToString()/*Forum Handle*/ + " "; // Personal Number this.TextPersonalNumber.Text = Person.PersonalNumber; this.TextPersonalNumber.Attributes.Add("onkeypress", "OnTextChange (this);"); this.TextPersonalNumber.Attributes.Add("onchange", "OnTextChange (this);"); this.LabelPersonalNumber.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.PersonalNumber").ToString()/*Personal #*/ + " "; // Bank name this.TextBankName.Text = Person.BankName; this.TextBankName.Attributes.Add("onkeypress", "OnTextChange (this);"); this.TextBankName.Attributes.Add("onchange", "OnTextChange (this);"); this.LabelBankName.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.BankName").ToString()/*Bank Name*/ + " "; // Bank clearing# this.TextBankClearing.Text = Person.BankClearing; this.TextBankClearing.Attributes.Add("onkeypress", "OnTextChange (this);"); this.TextBankClearing.Attributes.Add("onchange", "OnTextChange (this);"); // this.LabelBankClearing.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.BankName").ToString()/*Bank Name*/ + " "; // Bank account this.TextBankAccount.Text = Person.BankAccount; this.TextBankAccount.Attributes.Add("onkeypress", "OnTextChange (this);"); this.TextBankAccount.Attributes.Add("onchange", "OnTextChange (this);"); this.LabelBankAccount.Text = this.GetLocalResourceObject("Interface.Controls.EditPerson.BankAccount").ToString()/*Bank Account*/ + " "; // Crypto key this.TextCryptoFingerprint.Enabled = false; this.TextCryptoFingerprint.ReadOnly = true; if (Person.CryptoFingerprint.Length > 4) { this.TextCryptoFingerprint.Text = Person.CryptoFingerprint; } else { this.TextCryptoFingerprint.Text = "--"; } // T-Shirt Size this.TextTShirtSize.Enabled = false; this.TextTShirtSize.ReadOnly = true; this.TextTShirtSize.Text = Person.TShirtSize; // If we are looking at ourselves, enable the bank fields, which are otherwise disabled if (Person.Identity == Convert.ToInt32(HttpContext.Current.User.Identity.Name)) { this.TextBankName.ReadOnly = false; this.TextBankClearing.ReadOnly = false; this.TextBankAccount.ReadOnly = false; } else { if (!_authority.HasAnyPermission(Permission.CanEditPeople)) { this.TextBirthdate.ReadOnly = true; this.DropGenders.Enabled = false; this.TextCity.ReadOnly = true; this.TextEmail.ReadOnly = true; this.TextHandle.ReadOnly = true; this.TextMemberNumber.ReadOnly = true; this.TextName.ReadOnly = true; this.TextPartyEmail.ReadOnly = true; this.TextPersonalNumber.ReadOnly = true; this.TextPhone.ReadOnly = true; this.TextPostalCode.ReadOnly = true; this.TextStreet.ReadOnly = true; this.DropCountries.Enabled = false; this.DropDownMunicipalities.Enabled = false; this.ButtonSendNewPassword.Enabled = false; this.ButtonSaveChanges.Visible = false; } } } if (_authority.HasPermission(Permission.CanEditMailDB, Organization.PPSEid, -1, Authorization.Flag.AnyGeographyExactOrganization)) { ButtonDeleteMail.Visible = true; if (TextPartyEmail.Text.Trim() != "") ButtonDeleteMail.Enabled = true; else ButtonDeleteMail.Enabled = false; } }
public void DestroyHookPossible(Authority authority, bool polite = false){ if(!OFFLINE){ if((authority == Authority.SERVER && Network.isServer) || (authority == Authority.OWNER && networkController.isOwner) || (authority == Authority.OTHER && polite)) { networkView.RPC ("NotifyDestroyHook", RPCMode.Others); DestroyHook(); } } else { DestroyHook(); } }
public void ShouldThrowIfSSLCertificateIsNotFoundAndCannotBeRemoved() { var ca = new Authority("TestAuthority"); var sslCert = ca.GetSSLCertificate(); _mockPersonalStore.Setup(_ => _.Find(sslCert.Thumbprint)) .Returns<X509Certificate2>(null); Assert.Throws<CertificateNotFoundException>(() => _certInstall.UninstallSSL(sslCert.Thumbprint) ); }
public AuthenticodeFormatter () : base () { certs = new X509CertificateCollection (); crls = new ArrayList (); authority = Authority.Maximum; pkcs7 = new PKCS7.SignedData (); }