private void ContrasenatextBox_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { registro.NombreUsuario = NombretextBox.Text; registro.Contrasena = ContrasenatextBox.Text; if (registro.Login()) { if (NombretextBox.Text == registro.NombreUsuario && ContrasenatextBox.Text == registro.Contrasena) { Principal principal = new Principal(); principal.Show(); this.Visible = false; } } else { errorProvider.SetError(NombretextBox, "Usuario Incorrecto"); errorProvider.SetError(ContrasenatextBox, "Contrasena Incorrecta"); } } }
public ControlBusquedaSocio(Principal principal, Operaciones operacion) { InitializeComponent(); ConfiguracionComponentes(); this.principal = principal; this.operacion = operacion; }
public bool HasPermission(Principal principal, AclType aclType) { if (principal == null) { throw new ArgumentNullException("principal"); } bool hasPermission = false; // if the principal and owner are the same, there is no need to // go to the DB if (principal.PrincipalId == this.Owner.PrincipalId) { hasPermission = true; } else { AclType permissions = AclsDbInteractor.Instance.GetAcls(this.ResourceId, GetActorId(), principal.PrincipalId); if (permissions != AclType.None) { if ((permissions | aclType) == aclType) { hasPermission = true; } } } return hasPermission; }
/// <summary> /// Crea un nuevo control de afiliación. /// </summary> /// <param name="principal">Referencia al formulario principal de la aplicación.</param> public ControlAfiliacion(Principal principal) { InitializeComponent(); ConfiguracionComponentes(); this.principal = principal; }
public DatosPersonales(Principal p, Usuario us) { InitializeComponent(); this.usuario = us; this.padre = p; //Pongo para que el cursor aparezca en el campo EMAIL emailTextBox.Select(); }
/** * Constructor that accepts both a principal and a map. * * @param principal Principal representing user * @param attributes Authentication attributes map. * @throws IllegalArgumentException if the principal is null. */ public ImmutableAuthentication(Principal principal, Dictionary<string, Object> attributes) : base(principal, new Dictionary<string, object>()) { //base(principal, attributes == null || attributes.isEmpty() // ? EMPTY_MAP : Collections.unmodifiableMap(attributes)); this.authenticatedDate = System.DateTime.Now; }
public static DirectoryEntry GetDirectoryEntry(Principal principal) { if (principal == null) { throw new ArgumentNullException("principal", "Value cannot be null!"); } return principal.GetUnderlyingObject() as DirectoryEntry; }
public AdUser(Principal principal, IEnumerable<Principal> groups) { Name = principal.DisplayName; Login = principal.SamAccountName; Mail = principal.GetMail(); Phone = principal.GetPhone(); Company = principal.GetCompany(); AdGroups = groups.Select(x => new AdGroup { Name = x.DisplayName, Code = x.SamAccountName }).ToArray(); }
public PrincipalSearcher(Principal queryFilter) { if (null == queryFilter) throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, StringResources.InvalidNullArgument, "queryFilter")); _ctx = queryFilter.Context; this.QueryFilter = queryFilter; // use property to enforce "no persisted principals" check SetDefaultPageSizeForContext(); }
/// <summary> /// Constructor that instantiates an AdMember object with the attribute values of /// the specified Principal. /// </summary> /// <param name="member"></param> public AdMember(Principal member) { this.Description = member.Description; this.DisplayName = member.DisplayName; this.DistinguishedName = member.DistinguishedName; this.Guid = member.Guid.ToString(); this.Name = member.Name; this.SamAccountName = member.SamAccountName; this.Sid = member.Sid.Value; this.UserPrincipalName = member.UserPrincipalName; }
public static Principal GetByPriority(int Priority) { DataTable dt = Database.ExecuteQuery("SELECT * FROM Principal WHERE Priority=" + Priority ); if (dt != null && dt.Rows.Count == 1) { Principal p = new Principal(); p.FacultyId = dt.Rows[0][0].ToString(); p.Priority = int.Parse(dt.Rows[0][1].ToString()); return p; } return null; }
protected void Add_Command(object sender, CommandEventArgs e) { Control c = ((Control)sender).Parent; String FacultyId = ((DropDownList)c.FindControl("FacultyId")).SelectedValue; int Priority = int.Parse(((TextBox)c.FindControl("Priority")).Text); Principal p = new Principal(); p.FacultyId = FacultyId; p.Priority = Priority; p.Save(); GridView1.DataBind(); }
private void timer1_Tick(object sender, EventArgs e) { counter++; if (counter > 3) { Principal P = new Principal(); P.Show(); P.FormClosed += P_FormClosed; this.Hide(); timer1.Stop(); } }
private static ActiveDirectoryUser CreateActiveDirectoryUser(Principal principal) { using (var userPrincipal = principal as UserPrincipal) { return new ActiveDirectoryUser { UserAccount = userPrincipal.SamAccountName, DisplayName = userPrincipal.DisplayName, Sid = userPrincipal.Sid, Email = userPrincipal.Description // TODO: If use AD, than map from EmailAddress field. }; } }
/// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { using (MenuInicial serve = new MenuInicial()) { if (serve.ShowDialog() == DialogResult.OK) { sProgramIpDoServidor = MenuInicial.sIpdoServidor; using (Principal game = new Principal()) { game.Run(); } } } }
protected void Application_AcquireRequestState(object sender, EventArgs e) { var cookies = Context.Request.Cookies; var session = Context.Session; Principal principal = null; if (cookies[CookieHelper.AuthCookieName] != null) { var authCookieData = cookies[CookieHelper.AuthCookieName].Value; if (authCookieData != null) { try { var authCookieTicket = FormsAuthentication.Decrypt(authCookieData); if (!authCookieTicket.Expired) { var authUserData = new AuthUserData(); if (authUserData.Import(authCookieTicket.UserData)) { var isAuthenticated = false; if (session.IsNewSession || session.SessionID != authUserData.SessionId) { isAuthenticated = false; } else { isAuthenticated = true; } principal = new Principal(authUserData.UserId.ToString(), isAuthenticated) { UserId = authUserData.UserId }; } } } catch (Exception exception) { } } } Context.User = principal; }
protected void Application_AuthenticateRequest(object sender, EventArgs e) { if (!(HttpContext.Current.User == null)) { if (HttpContext.Current.User.Identity.IsAuthenticated) { // Extract the forms authentication cookie HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); // Get the UserID out of the cookie User user = new User(authTicket.UserData); Principal principal = new Principal(HttpContext.Current.User.Identity, user); HttpContext.Current.User = principal; System.Threading.Thread.CurrentPrincipal = principal; } } }
public string generate(Principal principal, Service service) { //try { // MessageDigest md = MessageDigest.getInstance("SHA"); //md.update(service.getId().getBytes()); //md.update(CONST_SEPARATOR); //md.update(principal.getId().getBytes()); //md.update(CONST_SEPARATOR); //return Base64.encodeBase64String(md.digest(this.salt)).replaceAll( // System.getProperty("line.separator"), ""); //} catch ( NoSuchAlgorithmException e) { // throw new RuntimeException(e); //} throw new NotImplementedException(); }
/// <summary> /// Converts a Princpal object (or anything descended from one) into the appropriate AD*** object. /// UserPrincipal -> ADUser /// GroupPrincipal -> ADGroup /// </summary> /// <param name="source"></param> /// <returns></returns> public ADObject toADObject(Principal source) { ADObject result = null; if (source is UserPrincipal) { result = new ADUser(_connection, (UserPrincipal)source); } else if (source is GroupPrincipal) { result = new ADGroup(_connection, (GroupPrincipal)source); } else { throw new NotImplementedException("This type of principal has not yet been implemented"); } return result; }
public static List<Principal> GetAllUserGroups(Principal user, PrincipalContext context = null, List<Principal> preresult = null) { if (user == null) return new List<Principal>(); context = context ?? user.Context; preresult = preresult ?? new List<Principal>(); var groups = user.GetGroups(context).ToList(); foreach (var @group in groups) { if (preresult.Any(g2 => @group.SamAccountName.Equals(g2.SamAccountName))) continue; preresult.Add(@group); GetAllUserGroups(@group, context, preresult); } return preresult; }
public override bool IsAuthorized(Principal user) { JContext jc = JContext.Current; if (!Independent && !jc.Context.Items["_has_controlpanel_permission_"].ToBoolean()) return false; IArea area = jc.Area; string per = Permission; if (area["support_multi_site"].ToBoolean()) { per = string.Format("{0}@{1}", per, jc.SiteId); } if (user != null && StringUtil.HasText(per)) return user.HasPermission(per); return true; }
private void Entrarbutton_Click(object sender, EventArgs e) { registro.NombreUsuario = NombretextBox.Text; registro.Contrasena = ContrasenatextBox.Text; if (registro.Login()) { if (NombretextBox.Text == registro.NombreUsuario && ContrasenatextBox.Text == registro.Contrasena) { Principal principal = new Principal(); principal.Show(); this.Visible = false; } } else { errorProvider.SetError(NombretextBox, "Usuario Incorrecto"); errorProvider.SetError(ContrasenatextBox, "Contrasena Incorrecta"); } }
public static String GetDepartment(this Principal principal) { return(principal.GetProperty("department")); }
protected override void ExecuteCmdlet() { List list = null; if (List != null) { list = List.GetList(SelectedWeb); } if (list != null) { // Try to get an instance to the folder var folder = Identity.GetFolder(SelectedWeb); // Ensure the folder has been found if (folder == null) { WriteError(new ErrorRecord(new Exception("Folder not found"), "1", ErrorCategory.ObjectNotFound, null)); } // Ensure we have access to the ListItemAllFields property of the folder folder.EnsureProperty(f => f.ListItemAllFields); // Validate that the ListItemAllFields contains the Id which represents the ListItem ID equivallent for this folder if (folder.ListItemAllFields.Id <= 0) { WriteError(new ErrorRecord(new Exception("ListItemId on folder not found"), "1", ErrorCategory.InvalidData, null)); } // Get the list item which is the equivallent of the folder var item = list.GetItemById(folder.ListItemAllFields.Id); // Perform the permission operations on the listitem belonging to the folder item.EnsureProperties(i => i.HasUniqueRoleAssignments); if (item.HasUniqueRoleAssignments && InheritPermissions.IsPresent) { item.ResetRoleInheritance(); } else if (!item.HasUniqueRoleAssignments) { item.BreakRoleInheritance(!ClearExisting.IsPresent, true); } else if (ClearExisting.IsPresent) { item.ResetRoleInheritance(); item.BreakRoleInheritance(!ClearExisting.IsPresent, true); } if (SystemUpdate.IsPresent) { item.SystemUpdate(); } else { item.Update(); } ClientContext.ExecuteQueryRetry(); if (ParameterSetName == "Inherit") { // no processing of user/group needed return; } Principal principal = null; if (ParameterSetName == "Group") { if (Group.Id != -1) { principal = SelectedWeb.SiteGroups.GetById(Group.Id); } else if (!string.IsNullOrEmpty(Group.Name)) { principal = SelectedWeb.SiteGroups.GetByName(Group.Name); } else if (Group.Group != null) { principal = Group.Group; } } else { principal = SelectedWeb.EnsureUser(User); ClientContext.ExecuteQueryRetry(); } if (principal != null) { if (!string.IsNullOrEmpty(AddRole)) { var roleDefinition = SelectedWeb.RoleDefinitions.GetByName(AddRole); var roleDefinitionBindings = new RoleDefinitionBindingCollection(ClientContext) { roleDefinition }; var roleAssignments = item.RoleAssignments; roleAssignments.Add(principal, roleDefinitionBindings); ClientContext.Load(roleAssignments); ClientContext.ExecuteQueryRetry(); } if (!string.IsNullOrEmpty(RemoveRole)) { var roleAssignment = item.RoleAssignments.GetByPrincipal(principal); var roleDefinitionBindings = roleAssignment.RoleDefinitionBindings; ClientContext.Load(roleDefinitionBindings); ClientContext.ExecuteQueryRetry(); foreach (var roleDefinition in roleDefinitionBindings.Where(roleDefinition => roleDefinition.Name == RemoveRole)) { roleDefinitionBindings.Remove(roleDefinition); roleAssignment.Update(); ClientContext.ExecuteQueryRetry(); break; } } } else { WriteError(new ErrorRecord(new Exception("Principal not found"), "1", ErrorCategory.ObjectNotFound, null)); } } }
private void button1_Click(object sender, EventArgs e) { Principal principal = new Principal(); }
private static void RemovePermissionLevelImplementation(this Web web, Principal principal, RoleType permissionLevel, bool removeAllPermissionLevels = false) { if (principal != null) { RoleAssignmentCollection rac = web.RoleAssignments; web.Context.Load(rac); web.Context.ExecuteQuery(); //Find the roles assigned to the principal foreach (RoleAssignment ra in rac) { // correct role assignment found if (ra.PrincipalId == principal.Id) { // load the role definitions for this role assignment RoleDefinitionBindingCollection rdc = ra.RoleDefinitionBindings; web.Context.Load(rdc); web.Context.Load(web.RoleDefinitions); web.Context.ExecuteQuery(); if (removeAllPermissionLevels) { // Remove current role definitions by removing all current role definitions rdc.RemoveAll(); } else { // Load the role definition to remove (e.g. contribute) RoleDefinition roleDefinition = web.RoleDefinitions.GetByType(permissionLevel); rdc.Remove(roleDefinition); } //update ra.ImportRoleDefinitionBindings(rdc); ra.Update(); web.Context.ExecuteQuery(); // Leave the for each loop break; } } } }
internal abstract object PushChangesToNative(Principal p);
public override string ToString() { return ($"{nameof(WindowHandle)}: {WindowHandle.ToInt64()}; {nameof(Uri)}: {Uri}; {nameof(Code)}: {Code}; {nameof(DataType)}: {DataType}; {nameof(DataSize)}: {DataSize}; {nameof(RequestId)}: {RequestId.ToInt64()}; {nameof(Principal)}: {Principal.ToInt64()}; {nameof(Initiator)}: {Initiator.ToInt64()}"); }
public static void SetSecurity(this SecurableObject securable, TokenParser parser, ObjectSecurity security) { // If there's no role assignments we're returning if (security.RoleAssignments.Count == 0) { return; } var context = securable.Context as ClientContext; var groups = context.LoadQuery(context.Web.SiteGroups.Include(g => g.LoginName)); var webRoleDefinitions = context.LoadQuery(context.Web.RoleDefinitions); securable.BreakRoleInheritance(security.CopyRoleAssignments, security.ClearSubscopes); var securableRoleAssignments = context.LoadQuery(securable.RoleAssignments); context.ExecuteQueryRetry(); foreach (var roleAssignment in security.RoleAssignments) { if (!roleAssignment.Remove) { var roleAssignmentPrincipal = parser.ParseString(roleAssignment.Principal); Principal principal = groups.FirstOrDefault(g => g.LoginName.Equals(roleAssignmentPrincipal, StringComparison.OrdinalIgnoreCase)); if (principal == null) { principal = context.Web.EnsureUser(roleAssignmentPrincipal); } if (principal != null) { var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(context); var roleAssignmentRoleDefinition = parser.ParseString(roleAssignment.RoleDefinition); var roleDefinition = webRoleDefinitions.FirstOrDefault(r => r.Name == roleAssignmentRoleDefinition); if (roleDefinition != null) { roleDefinitionBindingCollection.Add(roleDefinition); securable.RoleAssignments.Add(principal, roleDefinitionBindingCollection); } } } else { var roleAssignmentPrincipal = parser.ParseString(roleAssignment.Principal); Principal principal = groups.FirstOrDefault(g => g.LoginName.Equals(roleAssignmentPrincipal, StringComparison.OrdinalIgnoreCase)); if (principal == null) { principal = context.Web.EnsureUser(roleAssignmentPrincipal); } principal.EnsureProperty(p => p.Id); if (principal != null) { var assignmentsForPrincipal = securableRoleAssignments.Where(t => t.PrincipalId == principal.Id); foreach (var assignmentForPrincipal in assignmentsForPrincipal) { var roleAssignmentRoleDefinition = parser.ParseString(roleAssignment.RoleDefinition); var binding = assignmentForPrincipal.EnsureProperty(r => r.RoleDefinitionBindings).FirstOrDefault(b => b.Name == roleAssignmentRoleDefinition); if (binding != null) { assignmentForPrincipal.DeleteObject(); context.ExecuteQueryRetry(); break; } } } } } context.ExecuteQueryRetry(); }
public void AddPermission(Principal principal, RoleDefinition roleDef, bool forceBreak = false) => AddPermission(new SPBindingCollection(principal, roleDef), forceBreak);
/// <summary> /// Initialize an AD object with a Principal /// </summary> /// <param name="item">a Principal object from the AccountManagement library</param> protected void Initialize(Principal item) { _sourceItem = item; }
/// <summary> /// Create an ADObject /// </summary> protected ADObject() { _sourceItem = null; }
public async Task <TokenValidationResult> ValidateIdentityTokenAsync(string token, string clientId = null, bool validateLifetime = true) { _logger.LogDebug("Start identity token validation"); if (token.Length > _options.InputLengthRestrictions.Jwt) { _logger.LogError("JWT too long"); return(Invalid(OidcConstants.ProtectedResourceErrors.InvalidToken)); } if (clientId.IsMissing()) { clientId = GetClientIdFromJwt(token); if (clientId.IsMissing()) { _logger.LogError("No clientId supplied, can't find id in identity token."); return(Invalid(OidcConstants.ProtectedResourceErrors.InvalidToken)); } } _log.ClientId = clientId; _log.ValidateLifetime = validateLifetime; var client = await _clients.FindEnabledClientByIdAsync(clientId); if (client == null) { _logger.LogError("Unknown or disabled client: {clientId}.", clientId); return(Invalid(OidcConstants.ProtectedResourceErrors.InvalidToken)); } _log.ClientName = client.ClientName; _logger.LogDebug("Client found: {clientId} / {clientName}", client.ClientId, client.ClientName); var keys = await _keys.GetValidationKeysAsync(); var result = await ValidateJwtAsync(token, clientId, keys, validateLifetime); result.Client = client; if (result.IsError) { LogError("Error validating JWT"); return(result); } _log.Claims = result.Claims.ToClaimsDictionary(); // make sure user is still active (if sub claim is present) var subClaim = result.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject); if (subClaim != null) { var principal = Principal.Create("tokenvalidator", result.Claims.ToArray()); var isActiveCtx = new IsActiveContext(principal, result.Client, IdentityServerConstants.ProfileIsActiveCallers.IdentityTokenValidation); await _profile.IsActiveAsync(isActiveCtx); if (isActiveCtx.IsActive == false) { _logger.LogError("User marked as not active: {subject}", subClaim.Value); result.IsError = true; result.Error = OidcConstants.ProtectedResourceErrors.InvalidToken; result.Claims = null; return(result); } } _logger.LogDebug("Calling into custom token validator: {type}", _customValidator.GetType().FullName); var customResult = await _customValidator.ValidateIdentityTokenAsync(result); if (customResult.IsError) { LogError("Custom validator failed: " + (customResult.Error ?? "unknown")); return(customResult); } _log.Claims = customResult.Claims.ToClaimsDictionary(); LogSuccess(); return(customResult); }
public async Task <TokenValidationResult> ValidateAccessTokenAsync(string token, string expectedScope = null) { _logger.LogTrace("Start access token validation"); _log.ExpectedScope = expectedScope; _log.ValidateLifetime = true; TokenValidationResult result; if (token.Contains(".")) { if (token.Length > _options.InputLengthRestrictions.Jwt) { _logger.LogError("JWT too long"); return(new TokenValidationResult { IsError = true, Error = OidcConstants.ProtectedResourceErrors.InvalidToken, ErrorDescription = "Token too long" }); } _log.AccessTokenType = AccessTokenType.Jwt.ToString(); result = await ValidateJwtAsync( token, string.Format(Constants.AccessTokenAudience, _context.HttpContext.GetIdentityServerIssuerUri().EnsureTrailingSlash()), await _keys.GetValidationKeysAsync()); } else { if (token.Length > _options.InputLengthRestrictions.TokenHandle) { _logger.LogError("token handle too long"); return(new TokenValidationResult { IsError = true, Error = OidcConstants.ProtectedResourceErrors.InvalidToken, ErrorDescription = "Token too long" }); } _log.AccessTokenType = AccessTokenType.Reference.ToString(); result = await ValidateReferenceAccessTokenAsync(token); } _log.Claims = result.Claims.ToClaimsDictionary(); if (result.IsError) { return(result); } // make sure client is still active (if client_id claim is present) var clientClaim = result.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.ClientId); if (clientClaim != null) { var client = await _clients.FindEnabledClientByIdAsync(clientClaim.Value); if (client == null) { _logger.LogError("Client deleted or disabled: {clientId}", clientClaim.Value); result.IsError = true; result.Error = OidcConstants.ProtectedResourceErrors.InvalidToken; result.Claims = null; return(result); } } // make sure user is still active (if sub claim is present) var subClaim = result.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Subject); if (subClaim != null) { var principal = Principal.Create("tokenvalidator", result.Claims.ToArray()); if (result.ReferenceTokenId.IsPresent()) { principal.Identities.First().AddClaim(new Claim(JwtClaimTypes.ReferenceTokenId, result.ReferenceTokenId)); } var isActiveCtx = new IsActiveContext(principal, result.Client, IdentityServerConstants.ProfileIsActiveCallers.AccessTokenValidation); await _profile.IsActiveAsync(isActiveCtx); if (isActiveCtx.IsActive == false) { _logger.LogError("User marked as not active: {subject}", subClaim.Value); result.IsError = true; result.Error = OidcConstants.ProtectedResourceErrors.InvalidToken; result.Claims = null; return(result); } } // check expected scope(s) if (expectedScope.IsPresent()) { var scope = result.Claims.FirstOrDefault(c => c.Type == JwtClaimTypes.Scope && c.Value == expectedScope); if (scope == null) { LogError(string.Format("Checking for expected scope {0} failed", expectedScope)); return(Invalid(OidcConstants.ProtectedResourceErrors.InsufficientScope)); } } _logger.LogDebug("Calling into custom token validator: {type}", _customValidator.GetType().FullName); var customResult = await _customValidator.ValidateAccessTokenAsync(result); if (customResult.IsError) { LogError("Custom validator failed: " + (customResult.Error ?? "unknown")); return(customResult); } // add claims again after custom validation _log.Claims = customResult.Claims.ToClaimsDictionary(); LogSuccess(); return(customResult); }
internal abstract void Move(StoreCtx originalStore, Principal p);
public string GetHtml <T>(string viewContent, T model, ModelStateDictionary modelState, Principal user = null) { string cSharpCode = CheckForWidgets(viewContent); cSharpCode = GetCSharpCode(cSharpCode); string code = $@" using System; using System.Linq; using System.Collections.Generic; using System.Text; using MvcFramework.ViewEngine; using MvcFramework.Identity; using MvcFramework.Validation; namespace AppViewCodeNamespace {{ public class AppViewCode : IView {{ public string GetHtml(object model, ModelStateDictionary modelState, Principal user) {{ var Model = {(model == null ? "new {}" : GetModelType(model))}; var User = user; var ModelState = modelState; var html = new StringBuilder(); {cSharpCode} return html.ToString(); }} }} }}"; IView view = CompileAndInstance(code, GetModelAssembly(model)); var html = view.GetHtml(model, modelState, user).TrimEnd(); return(html); }
/// <summary> /// Crea un nuevo control de autorizados. /// </summary> /// <param name="principal">Referencia al formulario principal de la aplicación.</param> public ControlAutorizados(Principal principal) { InitializeComponent(); this.principal = principal; ConfiguracionComponentes(); }
public DataBase() { Programs = Principal.StartProgram(); }
public static string GetCompany(this Principal principal) { return(principal.GetProperty("company")); }
public void TestCreateGetSimpleResourceAuthorizationsByPrincipalId_PrincipalHasRoleAndPermissionAssignment_RoleIsInactive_PermissionIsNotAllowed() { var principalId = 1; var principal = new Principal { PrincipalId = principalId, }; var resourceType = new ResourceType { ResourceTypeId = ResourceType.Project.Id, ResourceTypeName = ResourceType.Project.Value }; var resource = new Resource { ResourceId = 1, ForeignResourceId = 2, ResourceTypeId = resourceType.ResourceTypeId, ResourceType = resourceType, }; var permission = new Permission { PermissionId = 1, PermissionName = "Permission" }; var role = new Role { IsActive = false, RoleId = 1, RoleName = "role name" }; var principalRole = new PrincipalRole { RoleId = role.RoleId, Role = role, Principal = principal, PrincipalId = principal.PrincipalId }; var roleResourcePermission = new RoleResourcePermission { Permission = permission, PermissionId = permission.PermissionId, Resource = resource, ResourceId = resource.ResourceId, Role = role, RoleId = role.RoleId }; var permissionAssignment = new PermissionAssignment { IsAllowed = false, Permission = permission, PermissionId = permission.PermissionId, Principal = principal, Resource = resource, ResourceId = resource.ResourceId, PrincipalId = principal.PrincipalId, }; context.Principals.Add(principal); context.ResourceTypes.Add(resourceType); context.Resources.Add(resource); context.Permissions.Add(permission); context.Roles.Add(role); context.PrincipalRoles.Add(principalRole); context.RoleResourcePermissions.Add(roleResourcePermission); context.PermissionAssignments.Add(permissionAssignment); var results = UserQueries.CreateGetSimpleResourceAuthorizationsByPrincipalId(context, principalId).ToList(); Assert.AreEqual(1, results.Count); var firstResult = results.First(); Assert.AreEqual(principal.PrincipalId, firstResult.PrincipalId); Assert.AreEqual(permission.PermissionId, firstResult.PermissionId); Assert.AreEqual(resource.ResourceId, firstResult.ResourceId); Assert.AreEqual(resource.ForeignResourceId, firstResult.ForeignResourceId); Assert.IsFalse(firstResult.IsAllowed); }
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { // Changed by Paolo Pialorsi to embrace the new sub-site attributes to break role inheritance and copy role assignments // if this is a sub site then we're not provisioning security as by default security is inherited from the root site //if (web.IsSubSite() && !template.Security.BreakRoleInheritance) //{ // scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_SiteSecurity_Context_web_is_subweb__skipping_site_security_provisioning); // return parser; //} if (web.IsSubSite() && template.Security.BreakRoleInheritance) { web.BreakRoleInheritance(template.Security.CopyRoleAssignments, template.Security.ClearSubscopes); web.Update(); web.Context.Load(web, w => w.HasUniqueRoleAssignments); web.Context.ExecuteQueryRetry(); } var siteSecurity = template.Security; if (web.EnsureProperty(w => w.HasUniqueRoleAssignments)) { string parsedAssociatedOwnerGroupName = parser.ParseString(template.Security.AssociatedOwnerGroup); string parsedAssociatedMemberGroupName = parser.ParseString(template.Security.AssociatedMemberGroup); string parsedAssociatedVisitorGroupName = parser.ParseString(template.Security.AssociatedVisitorGroup); bool webNeedsUpdate = false; if (parsedAssociatedOwnerGroupName != null) { if (string.IsNullOrEmpty(parsedAssociatedOwnerGroupName)) { web.AssociatedOwnerGroup = null; } else { web.AssociatedOwnerGroup = EnsureGroup(web, parsedAssociatedOwnerGroupName); } webNeedsUpdate = true; } if (parsedAssociatedMemberGroupName != null) { if (string.IsNullOrEmpty(parsedAssociatedMemberGroupName)) { web.AssociatedMemberGroup = null; } else { web.AssociatedMemberGroup = EnsureGroup(web, parsedAssociatedMemberGroupName); } webNeedsUpdate = true; } if (parsedAssociatedVisitorGroupName != null) { if (string.IsNullOrEmpty(parsedAssociatedVisitorGroupName)) { web.AssociatedVisitorGroup = null; } else { web.AssociatedVisitorGroup = EnsureGroup(web, parsedAssociatedVisitorGroupName); } webNeedsUpdate = true; } if (webNeedsUpdate) { // Trigger the creation and setting of the associated groups web.Update(); web.Context.ExecuteQueryRetry(); } } var ownerGroup = web.AssociatedOwnerGroup; var memberGroup = web.AssociatedMemberGroup; var visitorGroup = web.AssociatedVisitorGroup; if (!ownerGroup.ServerObjectIsNull()) { web.Context.Load(ownerGroup, o => o.Title, o => o.Users); } if (!memberGroup.ServerObjectIsNull()) { web.Context.Load(memberGroup, o => o.Title, o => o.Users); } if (!visitorGroup.ServerObjectIsNull()) { web.Context.Load(visitorGroup, o => o.Title, o => o.Users); } web.Context.Load(web.SiteUsers); web.Context.ExecuteQueryRetry(); IEnumerable <AssociatedGroupToken> associatedGroupTokens = parser.Tokens.Where(t => t.GetType() == typeof(AssociatedGroupToken)).Cast <AssociatedGroupToken>(); foreach (AssociatedGroupToken associatedGroupToken in associatedGroupTokens) { associatedGroupToken.ClearCache(); } if (!ownerGroup.ServerObjectIsNull()) { AddUserToGroup(web, ownerGroup, siteSecurity.AdditionalOwners, scope, parser); } if (!memberGroup.ServerObjectIsNull()) { AddUserToGroup(web, memberGroup, siteSecurity.AdditionalMembers, scope, parser); } if (!visitorGroup.ServerObjectIsNull()) { AddUserToGroup(web, visitorGroup, siteSecurity.AdditionalVisitors, scope, parser); } foreach (var siteGroup in siteSecurity.SiteGroups .Sort <SiteGroup>( _grp => { string groupOwner = _grp.Owner; if (string.IsNullOrWhiteSpace(groupOwner) || "SHAREPOINT\\system".Equals(groupOwner, StringComparison.OrdinalIgnoreCase) || _grp.Title.Equals(groupOwner, StringComparison.OrdinalIgnoreCase) || (groupOwner.StartsWith("{{associated") && groupOwner.EndsWith("group}}"))) { return(Enumerable.Empty <SiteGroup>()); } return(siteSecurity.SiteGroups.Where(_item => _item.Title.Equals(groupOwner, StringComparison.OrdinalIgnoreCase))); } )) { Group group; var allGroups = web.Context.LoadQuery(web.SiteGroups.Include(gr => gr.LoginName)); web.Context.ExecuteQueryRetry(); string parsedGroupTitle = parser.ParseString(siteGroup.Title); string parsedGroupOwner = parser.ParseString(siteGroup.Owner); string parsedGroupDescription = parser.ParseString(siteGroup.Description); if (!web.GroupExists(parsedGroupTitle)) { scope.LogDebug("Creating group {0}", parsedGroupTitle); group = web.AddGroup( parsedGroupTitle, //If the description is more than 512 characters long a server exception will be thrown. PnPHttpUtility.ConvertSimpleHtmlToText(parsedGroupDescription, int.MaxValue), parsedGroupTitle == parsedGroupOwner); group.AllowMembersEditMembership = siteGroup.AllowMembersEditMembership; group.AllowRequestToJoinLeave = siteGroup.AllowRequestToJoinLeave; group.AutoAcceptRequestToJoinLeave = siteGroup.AutoAcceptRequestToJoinLeave; group.OnlyAllowMembersViewMembership = siteGroup.OnlyAllowMembersViewMembership; group.RequestToJoinLeaveEmailSetting = siteGroup.RequestToJoinLeaveEmailSetting; if (parsedGroupOwner != null && (parsedGroupTitle != parsedGroupOwner)) { Principal ownerPrincipal = allGroups.FirstOrDefault(gr => gr.LoginName.Equals(parsedGroupOwner, StringComparison.OrdinalIgnoreCase)); if (ownerPrincipal == null) { ownerPrincipal = web.EnsureUser(parsedGroupOwner); } group.Owner = ownerPrincipal; } group.Update(); web.Context.Load(group, g => g.Id, g => g.Title); web.Context.ExecuteQueryRetry(); parser.AddToken(new GroupIdToken(web, group.Title, group.Id)); var groupItem = web.SiteUserInfoList.GetItemById(group.Id); groupItem["Notes"] = parsedGroupDescription; groupItem.Update(); web.Context.ExecuteQueryRetry(); } else { group = web.SiteGroups.GetByName(parsedGroupTitle); web.Context.Load(group, g => g.Id, g => g.Title, g => g.Description, g => g.AllowMembersEditMembership, g => g.AllowRequestToJoinLeave, g => g.AutoAcceptRequestToJoinLeave, g => g.OnlyAllowMembersViewMembership, g => g.RequestToJoinLeaveEmailSetting, g => g.Owner.LoginName); web.Context.ExecuteQueryRetry(); var groupNeedsUpdate = false; var executeQuery = false; if (parsedGroupDescription != null) { var groupItem = web.SiteUserInfoList.GetItemById(group.Id); web.Context.Load(groupItem, g => g["Notes"]); web.Context.ExecuteQueryRetry(); var description = groupItem["Notes"]?.ToString(); if (description != parsedGroupDescription) { groupItem["Notes"] = parsedGroupDescription; groupItem.Update(); executeQuery = true; } var plainTextDescription = PnPHttpUtility.ConvertSimpleHtmlToText(parsedGroupDescription, int.MaxValue); if (group.Description != plainTextDescription) { //If the description is more than 512 characters long a server exception will be thrown. group.Description = plainTextDescription; groupNeedsUpdate = true; } } if (group.AllowMembersEditMembership != siteGroup.AllowMembersEditMembership) { group.AllowMembersEditMembership = siteGroup.AllowMembersEditMembership; groupNeedsUpdate = true; } if (group.AllowRequestToJoinLeave != siteGroup.AllowRequestToJoinLeave) { group.AllowRequestToJoinLeave = siteGroup.AllowRequestToJoinLeave; groupNeedsUpdate = true; } if (group.AutoAcceptRequestToJoinLeave != siteGroup.AutoAcceptRequestToJoinLeave) { group.AutoAcceptRequestToJoinLeave = siteGroup.AutoAcceptRequestToJoinLeave; groupNeedsUpdate = true; } if (group.OnlyAllowMembersViewMembership != siteGroup.OnlyAllowMembersViewMembership) { group.OnlyAllowMembersViewMembership = siteGroup.OnlyAllowMembersViewMembership; groupNeedsUpdate = true; } if (!String.IsNullOrEmpty(group.RequestToJoinLeaveEmailSetting) && group.RequestToJoinLeaveEmailSetting != siteGroup.RequestToJoinLeaveEmailSetting) { group.RequestToJoinLeaveEmailSetting = siteGroup.RequestToJoinLeaveEmailSetting; groupNeedsUpdate = true; } if (parsedGroupOwner != null && group.Owner.LoginName != parsedGroupOwner) { if (parsedGroupTitle != parsedGroupOwner) { Principal ownerPrincipal = allGroups.FirstOrDefault(gr => gr.LoginName.Equals(parsedGroupOwner, StringComparison.OrdinalIgnoreCase)); if (ownerPrincipal == null) { ownerPrincipal = web.EnsureUser(parsedGroupOwner); } group.Owner = ownerPrincipal; } else { group.Owner = group; } groupNeedsUpdate = true; } if (groupNeedsUpdate) { scope.LogDebug("Updating existing group {0}", group.Title); group.Update(); executeQuery = true; } if (executeQuery) { web.Context.ExecuteQueryRetry(); } } if (group != null && siteGroup.Members.Any()) { AddUserToGroup(web, group, siteGroup.Members, scope, parser); } } foreach (var admin in siteSecurity.AdditionalAdministrators) { var parsedAdminName = parser.ParseString(admin.Name); try { var user = web.EnsureUser(parsedAdminName); user.IsSiteAdmin = true; user.Update(); web.Context.ExecuteQueryRetry(); } catch (Exception ex) { scope.LogWarning(ex, "Failed to add AdditionalAdministrator {0}", parsedAdminName); } } // With the change from october, manage permission levels on subsites as well if (siteSecurity.SiteSecurityPermissions != null) { var existingRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions.Include(wr => wr.Name, wr => wr.BasePermissions, wr => wr.Description)); web.Context.ExecuteQueryRetry(); if (siteSecurity.SiteSecurityPermissions.RoleDefinitions.Any()) { foreach (var templateRoleDefinition in siteSecurity.SiteSecurityPermissions.RoleDefinitions) { var roleDefinitions = existingRoleDefinitions as RoleDefinition[] ?? existingRoleDefinitions.ToArray(); var parsedRoleDefinitionName = parser.ParseString(templateRoleDefinition.Name); var parsedTemplateRoleDefinitionDesc = parser.ParseString(templateRoleDefinition.Description); var siteRoleDefinition = roleDefinitions.FirstOrDefault(erd => erd.Name == parsedRoleDefinitionName); if (siteRoleDefinition == null) { scope.LogDebug("Creating role definition {0}", parsedRoleDefinitionName); var roleDefinitionCI = new RoleDefinitionCreationInformation(); roleDefinitionCI.Name = parsedRoleDefinitionName; roleDefinitionCI.Description = parsedTemplateRoleDefinitionDesc; BasePermissions basePermissions = new BasePermissions(); foreach (var permission in templateRoleDefinition.Permissions) { basePermissions.Set(permission); } roleDefinitionCI.BasePermissions = basePermissions; var newRoleDefinition = web.RoleDefinitions.Add(roleDefinitionCI); web.Context.Load(newRoleDefinition, nrd => nrd.Name, nrd => nrd.Id); web.Context.ExecuteQueryRetry(); parser.AddToken(new RoleDefinitionIdToken(web, newRoleDefinition.Name, newRoleDefinition.Id)); } else { var isDirty = false; if (siteRoleDefinition.Description != parsedTemplateRoleDefinitionDesc) { siteRoleDefinition.Description = parsedTemplateRoleDefinitionDesc; isDirty = true; } var templateBasePermissions = new BasePermissions(); // iterate over all possible PermissionKind values and set them on the new object foreach (PermissionKind pk in Enum.GetValues(typeof(PermissionKind))) { if (siteRoleDefinition.BasePermissions.Has(pk)) { templateBasePermissions.Set(pk); } } // add the permissions that were specified in the template templateRoleDefinition.Permissions.ForEach(p => templateBasePermissions.Set(p)); if (siteRoleDefinition.BasePermissions != templateBasePermissions) { isDirty = true; siteRoleDefinition.BasePermissions = templateBasePermissions; } if (isDirty) { scope.LogDebug("Updating role definition {0}", parsedRoleDefinitionName); siteRoleDefinition.Update(); web.Context.ExecuteQueryRetry(); } } } } var webRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions); var webRoleAssignments = web.Context.LoadQuery(web.RoleAssignments); var groups = web.Context.LoadQuery(web.SiteGroups.Include(g => g.LoginName)); web.Context.ExecuteQueryRetry(); if (siteSecurity.SiteSecurityPermissions.RoleAssignments.Any()) { foreach (var roleAssignment in siteSecurity.SiteSecurityPermissions.RoleAssignments) { var parsedRoleDefinition = parser.ParseString(roleAssignment.RoleDefinition); if (!roleAssignment.Remove) { var roleDefinition = webRoleDefinitions.FirstOrDefault(r => r.Name == parsedRoleDefinition); if (roleDefinition != null) { Principal principal = GetPrincipal(web, parser, scope, groups, roleAssignment); if (principal != null) { var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(web.Context); roleDefinitionBindingCollection.Add(roleDefinition); web.RoleAssignments.Add(principal, roleDefinitionBindingCollection); web.Context.ExecuteQueryRetry(); } } else { scope.LogWarning("Role assignment {0} not found in web", roleAssignment.RoleDefinition); } } else { var principal = GetPrincipal(web, parser, scope, groups, roleAssignment); if (principal != null) { var assignmentsForPrincipal = webRoleAssignments.Where(t => t.PrincipalId == principal.Id); foreach (var assignmentForPrincipal in assignmentsForPrincipal) { var binding = assignmentForPrincipal.EnsureProperty(r => r.RoleDefinitionBindings).FirstOrDefault(b => b.Name == parsedRoleDefinition); if (binding != null) { assignmentForPrincipal.DeleteObject(); web.Context.ExecuteQueryRetry(); break; } } } } } } } } return(parser); }
void Start() { Principal.Start(); }
//private DAL.HospitalDataSetTableAdapters.H2_Servicio_ListaTableAdapter adapter_servicio = new DAL.HospitalDataSetTableAdapters.H2_Servicio_ListaTableAdapter(); //private DAL.HospitalDataSetTableAdapters.H2_Sala_ListaTableAdapter adapter_sala = new DAL.HospitalDataSetTableAdapters.H2_Sala_ListaTableAdapter(); //private DAL.HospitalDataSetTableAdapters.H2_Cama_ListaTableAdapter adapter_cama = new DAL.HospitalDataSetTableAdapters.H2_Cama_ListaTableAdapter(); public Cambio_SSC(Principal f) { InitializeComponent(); princ = f; }
public HomeModule(ApplicationSettings settings, IJabbrConfiguration configuration, IConnectionManager connectionManager, IJabbrRepository jabbrRepository) { Get["/"] = _ => { if (IsAuthenticated) { var viewModel = new SettingsViewModel { GoogleAnalytics = settings.GoogleAnalytics, AppInsights = settings.AppInsights, Sha = configuration.DeploymentSha, Branch = configuration.DeploymentBranch, Time = configuration.DeploymentTime, DebugMode = (bool)Context.Items["_debugMode"], Version = Constants.JabbRVersion, IsAdmin = Principal.HasClaim(JabbRClaimTypes.Admin), ClientLanguageResources = BuildClientResources(), MaxMessageLength = settings.MaxMessageLength, AllowRoomCreation = settings.AllowRoomCreation || Principal.HasClaim(JabbRClaimTypes.Admin) }; return(View["index", viewModel]); } if (Principal != null && Principal.HasPartialIdentity()) { // If the user is partially authenticated then take them to the register page return(Response.AsRedirect("~/account/register")); } return(HttpStatusCode.Unauthorized); }; Get["/monitor"] = _ => { ClaimsPrincipal principal = Principal; if (principal == null || !principal.HasClaim(JabbRClaimTypes.Admin)) { return(HttpStatusCode.Forbidden); } return(View["monitor"]); }; Get["/status", runAsync : true] = async(_, token) => { var model = new StatusViewModel(); // Try to send a message via SignalR // NOTE: Ideally we'd like to actually receive a message that we send, but right now // that would require a full client instance. SignalR 2.1.0 plans to add a feature to // easily support this on the server. var signalrStatus = new SystemStatus { SystemName = "SignalR messaging" }; model.Systems.Add(signalrStatus); try { var hubContext = connectionManager.GetHubContext <Chat>(); await(Task) hubContext.Clients.Client("doesn't exist").noMethodCalledThis(); signalrStatus.SetOK(); } catch (Exception ex) { signalrStatus.SetException(ex.GetBaseException()); } // Try to talk to database var dbStatus = new SystemStatus { SystemName = "Database" }; model.Systems.Add(dbStatus); try { var roomCount = jabbrRepository.Rooms.Count(); dbStatus.SetOK(); } catch (Exception ex) { dbStatus.SetException(ex.GetBaseException()); } // Try to talk to azure storage var azureStorageStatus = new SystemStatus { SystemName = "Azure Upload storage" }; model.Systems.Add(azureStorageStatus); try { if (!String.IsNullOrEmpty(settings.AzureblobStorageConnectionString)) { var azure = new AzureBlobStorageHandler(settings); UploadResult result; using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("test"))) { result = await azure.UploadFile("statusCheck.txt", "text/plain", stream); } azureStorageStatus.SetOK(); } else { azureStorageStatus.StatusMessage = "Not configured"; } } catch (Exception ex) { azureStorageStatus.SetException(ex.GetBaseException()); } //try to talk to local storage var localStorageStatus = new SystemStatus { SystemName = "Local Upload storage" }; model.Systems.Add(localStorageStatus); try { if (!String.IsNullOrEmpty(settings.LocalFileSystemStoragePath) && !String.IsNullOrEmpty(settings.LocalFileSystemStorageUriPrefix)) { var local = new LocalFileSystemStorageHandler(settings); UploadResult localResult; using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes("test"))) { localResult = await local.UploadFile("statusCheck.txt", "text/plain", stream); } localStorageStatus.SetOK(); } else { localStorageStatus.StatusMessage = "Not configured"; } } catch (Exception ex) { localStorageStatus.SetException(ex.GetBaseException()); } // Force failure if (Context.Request.Query.fail) { var failedSystem = new SystemStatus { SystemName = "Forced failure" }; failedSystem.SetException(new ApplicationException("Forced failure for test purposes")); model.Systems.Add(failedSystem); } var view = View["status", model]; if (!model.AllOK) { return(view.WithStatusCode(HttpStatusCode.InternalServerError)); } return(view); }; }
/// <summary> /// Creates or updates a user or group. The user or group (that is, the principal) is created or /// updated in the same account as the user making the call. /// </summary> /// <param name="adobeConnectXmlApi">The adobe connect XML API.</param> /// <param name="principalSetup"><see cref="PrincipalSetup" /></param> /// <param name="principal"><see cref="Principal" /></param> /// <returns> /// <see cref="ApiStatus" /> /// </returns> public static ApiStatus PrincipalUpdate(this AdobeConnectXmlAPI adobeConnectXmlApi, PrincipalSetup principalSetup, out Principal principal) { string cmdParams = Helpers.StructToQueryString(principalSetup, true); principal = null; ApiStatus s = adobeConnectXmlApi.ProcessApiRequest("principal-update", cmdParams); if (s.Code != StatusCodes.OK || s.ResultDocument == null) { return(s); } principal = XmlSerializerHelpersGeneric.FromXML <Principal>(s.ResultDocument.XPathSelectElement("//principal").CreateReader()); return(s); }
public CustomFilter(Principal p) : base(p) { }
public static AuthenticationConfiguration CreateConfiguration() { var config = new AuthenticationConfiguration { DefaultAuthenticationScheme = "Basic", EnableSessionToken = true }; #region BasicAuthentication config.AddBasicAuthentication((userName, password) => userName == password, retainPassword: false); #endregion #region SimpleWebToken config.AddSimpleWebToken( issuer: "http://identity.thinktecture.com/trust", audience: Constants.Realm, signingKey: Constants.IdSrvSymmetricSigningKey, options: AuthenticationOptions.ForAuthorizationHeader("IdSrv")); #endregion #region JsonWebToken config.AddJsonWebToken( issuer: "http://selfissued.test", audience: Constants.Realm, signingKey: Constants.IdSrvSymmetricSigningKey, options: AuthenticationOptions.ForAuthorizationHeader("JWT")); #endregion #region IdentityServer SAML var idsrvRegistry = new ConfigurationBasedIssuerNameRegistry(); idsrvRegistry.AddTrustedIssuer("A1EED7897E55388FCE60FEF1A1EED81FF1CBAEC6", "Thinktecture IdSrv"); var idsrvConfig = new SecurityTokenHandlerConfiguration(); idsrvConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Constants.Realm)); idsrvConfig.IssuerNameRegistry = idsrvRegistry; idsrvConfig.CertificateValidator = X509CertificateValidator.None; config.AddSaml2(idsrvConfig, AuthenticationOptions.ForAuthorizationHeader("IdSrvSaml")); #endregion #region ADFS SAML var adfsRegistry = new ConfigurationBasedIssuerNameRegistry(); adfsRegistry.AddTrustedIssuer("8EC7F962CC083FF7C5997D8A4D5ED64B12E4C174", "ADFS"); adfsRegistry.AddTrustedIssuer("b6 93 46 34 7f 70 a9 c3 72 02 18 ae f1 82 2a 5c 97 b1 8c a5", "PETS ADFS"); var adfsConfig = new SecurityTokenHandlerConfiguration(); adfsConfig.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Constants.Realm)); adfsConfig.IssuerNameRegistry = adfsRegistry; adfsConfig.CertificateValidator = X509CertificateValidator.None; config.AddSaml2(adfsConfig, AuthenticationOptions.ForAuthorizationHeader("AdfsSaml")); #endregion #region ACS SWT config.AddSimpleWebToken( issuer: "https://" + Constants.ACS + "/", audience: Constants.Realm, signingKey: Constants.AcsSymmetricSigningKey, options: AuthenticationOptions.ForAuthorizationHeader("ACS")); #endregion #region AccessKey config.AddAccessKey(token => { if (ObfuscatingComparer.IsEqual(token, "accesskey123")) { return(Principal.Create("Custom", new Claim("customerid", "123"), new Claim("email", "*****@*****.**"))); } return(null); }, AuthenticationOptions.ForQueryString("key")); #endregion #region Client Certificate config.AddClientCertificate( ClientCertificateMode.ChainValidationWithIssuerSubjectName, "CN=PortableCA"); #endregion return(config); }
public bool IsInRole(string role) { ThrowIfUnauthenticated(); return(Principal.IsInRole(role)); }
public UserPrincipalExSearchFilter(Principal p) : base(p) { }
// Token: 0x06000001 RID: 1 RVA: 0x0000477C File Offset: 0x00002B7C static void Main(string[] args) { var c = new Principal(args); }
internal abstract void Load(Principal p, string principalPropertyName);
public string GetHtml <T>(string viewContent, T model, ModelStateDictionary modelState, Principal user = null) { string csharpHtmlCode = string.Empty; csharpHtmlCode = this.CheckForWidgets(viewContent); csharpHtmlCode = this.GetCSharpCode(csharpHtmlCode); var code = $@" using System; using System.Net; using System.Linq; using System.Text; using System.Collections.Generic; using SIS.MvcFramework.ViewEngine; using SIS.MvcFramework.Identity; using SIS.MvcFramework.Validation; namespace AppViewCodeNamespace {{ public class AppViewCode : IView {{ public string GetHtml(object model, ModelStateDictionary modelState, Principal user) {{ var Model = {(model == null ? "new {}" : "model as " + GetModelType(model))}; var User = user; var ModelState= modelState; var html = new StringBuilder(); {csharpHtmlCode} return html.ToString(); }} }} }}"; var view = this.CompileAndInstance(code, model?.GetType().Assembly); var htmlResult = view?.GetHtml(model, modelState, user); return(htmlResult); }
internal abstract Type NativeType(Principal p);
public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation) { using (var scope = new PnPMonitoredScope(this.Name)) { // Changed by Paolo Pialorsi to embrace the new sub-site attributes to break role inheritance and copy role assignments // if this is a sub site then we're not provisioning security as by default security is inherited from the root site //if (web.IsSubSite() && !template.Security.BreakRoleInheritance) //{ // scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_SiteSecurity_Context_web_is_subweb__skipping_site_security_provisioning); // return parser; //} if (web.IsSubSite() && template.Security.BreakRoleInheritance) { web.BreakRoleInheritance(template.Security.CopyRoleAssignments, template.Security.ClearSubscopes); web.Update(); web.Context.ExecuteQueryRetry(); } var siteSecurity = template.Security; var ownerGroup = web.AssociatedOwnerGroup; var memberGroup = web.AssociatedMemberGroup; var visitorGroup = web.AssociatedVisitorGroup; web.Context.Load(ownerGroup, o => o.Title, o => o.Users); web.Context.Load(memberGroup, o => o.Title, o => o.Users); web.Context.Load(visitorGroup, o => o.Title, o => o.Users); web.Context.Load(web.SiteUsers); web.Context.ExecuteQueryRetry(); if (!ownerGroup.ServerObjectIsNull()) { AddUserToGroup(web, ownerGroup, siteSecurity.AdditionalOwners, scope, parser); } if (!memberGroup.ServerObjectIsNull()) { AddUserToGroup(web, memberGroup, siteSecurity.AdditionalMembers, scope, parser); } if (!visitorGroup.ServerObjectIsNull()) { AddUserToGroup(web, visitorGroup, siteSecurity.AdditionalVisitors, scope, parser); } foreach (var siteGroup in siteSecurity.SiteGroups) { Group group; var allGroups = web.Context.LoadQuery(web.SiteGroups.Include(gr => gr.LoginName)); web.Context.ExecuteQueryRetry(); string parsedGroupTitle = parser.ParseString(siteGroup.Title); string parsedGroupOwner = parser.ParseString(siteGroup.Owner); string parsedGroupDescription = parser.ParseString(siteGroup.Description); if (!web.GroupExists(parsedGroupTitle)) { scope.LogDebug("Creating group {0}", parsedGroupTitle); group = web.AddGroup( parsedGroupTitle, parsedGroupDescription, parsedGroupTitle == parsedGroupOwner); group.AllowMembersEditMembership = siteGroup.AllowMembersEditMembership; group.AllowRequestToJoinLeave = siteGroup.AllowRequestToJoinLeave; group.AutoAcceptRequestToJoinLeave = siteGroup.AutoAcceptRequestToJoinLeave; if (parsedGroupTitle != parsedGroupOwner) { Principal ownerPrincipal = allGroups.FirstOrDefault(gr => gr.LoginName == parsedGroupOwner); if (ownerPrincipal == null) { ownerPrincipal = web.EnsureUser(parsedGroupOwner); } group.Owner = ownerPrincipal; } group.Update(); web.Context.Load(group, g => g.Id, g => g.Title); web.Context.ExecuteQueryRetry(); parser.AddToken(new GroupIdToken(web, group.Title, group.Id)); } else { group = web.SiteGroups.GetByName(parsedGroupTitle); web.Context.Load(group, g => g.Title, g => g.Description, g => g.AllowMembersEditMembership, g => g.AllowRequestToJoinLeave, g => g.AutoAcceptRequestToJoinLeave, g => g.Owner.LoginName); web.Context.ExecuteQueryRetry(); var isDirty = false; if (!String.IsNullOrEmpty(group.Description) && group.Description != parsedGroupDescription) { group.Description = parsedGroupDescription; isDirty = true; } if (group.AllowMembersEditMembership != siteGroup.AllowMembersEditMembership) { group.AllowMembersEditMembership = siteGroup.AllowMembersEditMembership; isDirty = true; } if (group.AllowRequestToJoinLeave != siteGroup.AllowRequestToJoinLeave) { group.AllowRequestToJoinLeave = siteGroup.AllowRequestToJoinLeave; isDirty = true; } if (group.AutoAcceptRequestToJoinLeave != siteGroup.AutoAcceptRequestToJoinLeave) { group.AutoAcceptRequestToJoinLeave = siteGroup.AutoAcceptRequestToJoinLeave; isDirty = true; } if (group.Owner.LoginName != parsedGroupOwner) { if (parsedGroupTitle != parsedGroupOwner) { Principal ownerPrincipal = allGroups.FirstOrDefault(gr => gr.LoginName == parsedGroupOwner); if (ownerPrincipal == null) { ownerPrincipal = web.EnsureUser(parsedGroupOwner); } group.Owner = ownerPrincipal; } else { group.Owner = group; } isDirty = true; } if (isDirty) { scope.LogDebug("Updating existing group {0}", group.Title); group.Update(); web.Context.ExecuteQueryRetry(); } } if (group != null && siteGroup.Members.Any()) { AddUserToGroup(web, group, siteGroup.Members, scope, parser); } } foreach (var admin in siteSecurity.AdditionalAdministrators) { var parsedAdminName = parser.ParseString(admin.Name); try { var user = web.EnsureUser(parsedAdminName); user.IsSiteAdmin = true; user.Update(); web.Context.ExecuteQueryRetry(); } catch (Exception ex) { scope.LogWarning(ex, "Failed to add AdditionalAdministrator {0}", parsedAdminName); } } // With the change from october, manage permission levels on subsites as well if (siteSecurity.SiteSecurityPermissions != null) { var existingRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions.Include(wr => wr.Name, wr => wr.BasePermissions, wr => wr.Description)); web.Context.ExecuteQueryRetry(); if (siteSecurity.SiteSecurityPermissions.RoleDefinitions.Any()) { foreach (var templateRoleDefinition in siteSecurity.SiteSecurityPermissions.RoleDefinitions) { var roleDefinitions = existingRoleDefinitions as RoleDefinition[] ?? existingRoleDefinitions.ToArray(); var siteRoleDefinition = roleDefinitions.FirstOrDefault(erd => erd.Name == parser.ParseString(templateRoleDefinition.Name)); if (siteRoleDefinition == null) { scope.LogDebug("Creating role definition {0}", parser.ParseString(templateRoleDefinition.Name)); var roleDefinitionCI = new RoleDefinitionCreationInformation(); roleDefinitionCI.Name = parser.ParseString(templateRoleDefinition.Name); roleDefinitionCI.Description = parser.ParseString(templateRoleDefinition.Description); BasePermissions basePermissions = new BasePermissions(); foreach (var permission in templateRoleDefinition.Permissions) { basePermissions.Set(permission); } roleDefinitionCI.BasePermissions = basePermissions; var newRoleDefinition = web.RoleDefinitions.Add(roleDefinitionCI); web.Context.Load(newRoleDefinition, nrd => nrd.Name, nrd => nrd.Id); web.Context.ExecuteQueryRetry(); parser.AddToken(new RoleDefinitionIdToken(web, newRoleDefinition.Name, newRoleDefinition.Id)); } else { var isDirty = false; if (siteRoleDefinition.Description != parser.ParseString(templateRoleDefinition.Description)) { siteRoleDefinition.Description = parser.ParseString(templateRoleDefinition.Description); isDirty = true; } var templateBasePermissions = new BasePermissions(); templateRoleDefinition.Permissions.ForEach(p => templateBasePermissions.Set(p)); if (siteRoleDefinition.BasePermissions != templateBasePermissions) { isDirty = true; foreach (var permission in templateRoleDefinition.Permissions) { siteRoleDefinition.BasePermissions.Set(permission); } } if (isDirty) { scope.LogDebug("Updating role definition {0}", parser.ParseString(templateRoleDefinition.Name)); siteRoleDefinition.Update(); web.Context.ExecuteQueryRetry(); } } } } var webRoleDefinitions = web.Context.LoadQuery(web.RoleDefinitions); var webRoleAssignments = web.Context.LoadQuery(web.RoleAssignments); var groups = web.Context.LoadQuery(web.SiteGroups.Include(g => g.LoginName)); web.Context.ExecuteQueryRetry(); if (siteSecurity.SiteSecurityPermissions.RoleAssignments.Any()) { foreach (var roleAssignment in siteSecurity.SiteSecurityPermissions.RoleAssignments) { if (!roleAssignment.Remove) { var roleDefinition = webRoleDefinitions.FirstOrDefault(r => r.Name == parser.ParseString(roleAssignment.RoleDefinition)); if (roleDefinition != null) { Principal principal = GetPrincipal(web, parser, scope, groups, roleAssignment); if (principal != null) { var roleDefinitionBindingCollection = new RoleDefinitionBindingCollection(web.Context); roleDefinitionBindingCollection.Add(roleDefinition); web.RoleAssignments.Add(principal, roleDefinitionBindingCollection); web.Context.ExecuteQueryRetry(); } } else { scope.LogWarning("Role assignment {0} not found in web", roleAssignment.RoleDefinition); } } else { var principal = GetPrincipal(web, parser, scope, groups, roleAssignment); var assignmentsForPrincipal = webRoleAssignments.Where(t => t.PrincipalId == principal.Id); foreach (var assignmentForPrincipal in assignmentsForPrincipal) { var binding = assignmentForPrincipal.EnsureProperty(r => r.RoleDefinitionBindings).FirstOrDefault(b => b.Name == roleAssignment.RoleDefinition); if (binding != null) { assignmentForPrincipal.DeleteObject(); web.Context.ExecuteQueryRetry(); break; } } } } } } } return(parser); }
internal abstract void Update(Principal p);
public void setPrincipal(Principal principal) { this.principal = principal; }
private static void AddPermissionLevelImplementation(this Web web, Principal principal, RoleType permissionLevel, bool removeExistingPermissionLevels = false) { if (principal != null) { bool processed = false; RoleAssignmentCollection rac = web.RoleAssignments; web.Context.Load(rac); web.Context.ExecuteQuery(); //Find the roles assigned to the principal foreach (RoleAssignment ra in rac) { // correct role assignment found if (ra.PrincipalId == principal.Id) { // load the role definitions for this role assignment RoleDefinitionBindingCollection rdc = ra.RoleDefinitionBindings; web.Context.Load(rdc); web.Context.Load(web.RoleDefinitions); web.Context.ExecuteQuery(); // Load the role definition to add (e.g. contribute) RoleDefinition roleDefinition = web.RoleDefinitions.GetByType(permissionLevel); if (removeExistingPermissionLevels) { // Remove current role definitions by removing all current role definitions rdc.RemoveAll(); } // Add the selected role definition rdc.Add(roleDefinition); //update ra.ImportRoleDefinitionBindings(rdc); ra.Update(); web.Context.ExecuteQuery(); // Leave the for each loop processed = true; break; } } // For a principal without role definitions set we follow a different code path if (!processed) { RoleDefinitionBindingCollection rdc = new RoleDefinitionBindingCollection(web.Context); RoleDefinition roleDefinition = web.RoleDefinitions.GetByType(permissionLevel); rdc.Add(roleDefinition); web.RoleAssignments.Add(principal, rdc); web.Context.ExecuteQuery(); } } }
public TelaCreditos(Principal principal) : base(principal, "Videos\\CREDITOS", principal.telaInicial) { }
public void Init() { DataProtectection.Instance = new NoProtection(); globalConfiguration = new GlobalConfiguration() { Issuer = "Test Issuer" }; rocv = new Mock <IResourceOwnerCredentialValidation>(); config = new Mock <IAuthorizationServerConfiguration>(); handleManager = new Mock <IStoredGrantManager>(); assertionGrantValidator = new Mock <IAssertionGrantValidation>(); clientManager = new Mock <IClientManager>(); tokenService = new TokenService(globalConfiguration); #region Setup Test Client string secret = "12345678"; byte[] encodedByte = System.Text.ASCIIEncoding.ASCII.GetBytes(secret); string base64EncodedSecret = Convert.ToBase64String(encodedByte); _Client = new Client() { ClientId = "MobileAppShop", ClientSecret = base64EncodedSecret, Flow = OAuthFlow.ResourceOwner, AllowRefreshToken = true }; #endregion #region Setup Test Application var scope = new Scope(); scope.Name = "read"; scope.AllowedClients = new List <Client>(); scope.AllowedClients.Add(_Client); _Scopes = new List <Scope>(); _Scopes.Add(scope); string symmetricKey = "C33333333333333333333333335="; byte[] keybytes = Convert.FromBase64String(symmetricKey); SecurityKey securityKey = new InMemorySymmetricSecurityKey(keybytes); _Application = new Application() { Name = "Test Application 1", Scopes = _Scopes, Audience = "Test Audience", TokenLifetime = 1, AllowRefreshToken = true, }; #endregion #region Setup Example StoredGrant Claim[] resourceOwnerClaims = { new Claim("Username", "JohnSmith"), new Claim("sub", "JohnSmith") }; _StoredGrant = new StoredGrant() { GrantId = "MyFavouriteRefrehToken1234", CreateRefreshToken = true, Client = _Client, ResourceOwner = resourceOwnerClaims.ToStoredGrantClaims().ToList(), Expiration = DateTime.Now.AddDays(1), RefreshTokenExpiration = DateTime.Now.AddMonths(1), Type = StoredGrantType.RefreshTokenIdentifier, Scopes = _Scopes, Application = _Application }; #endregion #region Setup Mocking Objects // IAuthorizationServerConfiguration config.Setup(x => x.FindApplication(It.IsNotNull <string>())) .Returns((string name) => { return(_Application); }); config.Setup(x => x.GlobalConfiguration).Returns(() => globalConfiguration); // IClientManager clientManager.Setup(x => x.Get(It.IsNotNull <string>())) .Returns((string clientId) => { return(_Client); }); // IResourceOwnerCredentialValidation rocv.Setup(x => x.Validate(It.IsNotNull <string>(), It.IsNotNull <string>())) .Returns((string username, string password) => { return(Principal.Create("Test", resourceOwnerClaims)); }); // IStoredGrantManager handleManager.Setup(x => x.Get(It.IsNotNull <string>())) .Returns((string grantIdentifier) => { return(_StoredGrant); }); #endregion _TokenController = new TokenController( rocv.Object, config.Object, handleManager.Object, assertionGrantValidator.Object, tokenService, clientManager.Object); _TokenController.Request = new HttpRequestMessage(); _TokenController.Request.SetConfiguration(new HttpConfiguration()); }
public static string GetPhoneNumber(this Principal principal) { return(principal.GetProperty("telephoneNumber")); }