/// <summary> /// Creates a new group. /// </summary> /// <param name="group">Group object with all information.</param> /// <param name="token">Token of user who is allowed to create a group.</param> /// <param name="connectionString">Connection string of authorization store.</param> /// <returns>True if group is created successfully, else false.</returns> public static bool CreateGroup(Group group, AuthenticatedToken token, string connectionString) { #region Parameter Validation ValidateStrings("connectionString", connectionString); #endregion using (ZentityContext context = new ZentityContext(connectionString)) { return(CreateGroup(group, token, context)); } }
/// <summary> /// Processes the request sent to the specified Uri. /// This method assumes that the request is already validated. /// </summary> /// <param name="context">An instance of HttpContext containing the request details.</param> /// <param name="statusCode">The HttpStatusCode indicating status of the request.</param> /// <returns> /// A string containing the response to the request. /// </returns> public string ProcessRequest(HttpContext context, out HttpStatusCode statusCode) { string response = string.Empty; SyndicationRequestType requestType = SyndicationHelper.GetSyndicationRequestType(context, this.baseUri); if (SyndicationRequestType.Help == requestType) { statusCode = HttpStatusCode.OK; response = Properties.Resources.Help; } else { string searchQuery = HttpUtility.UrlDecode(context.Request.QueryString.ToString()); int pageSize = int.Parse(ConfigurationManager.AppSettings["DefaultPageSize"], CultureInfo.InvariantCulture); int maxPageSize = int.Parse(ConfigurationManager.AppSettings["MaxPageSize"], CultureInfo.InvariantCulture); if (SyndicationRequestType.DefaultSearchWithPageNo == requestType || SyndicationRequestType.RSSSearchWithPageNo == requestType || SyndicationRequestType.ATOMSearchWithPageNo == requestType) { pageSize = int.Parse(SyndicationHelper.GetValueOfParameterFromUri(context, this.baseUri, requestType, SyndicationParameterType.PageSize), CultureInfo.InvariantCulture); pageSize = (pageSize > maxPageSize) ? maxPageSize : pageSize; } AuthenticatedToken token = (AuthenticatedToken)context.Items["AuthenticatedToken"]; List <Resource> resources; try { SearchEngine searchEngin = new SearchEngine(pageSize, true, token); int totalRecords; ZentityContext zentityContext = CoreHelper.CreateZentityContext(); SortProperty sortProperty = new SortProperty("dateModified", SortDirection.Descending); resources = searchEngin.SearchResources(searchQuery, zentityContext, sortProperty, 0, out totalRecords).ToList(); ; } catch (SearchException exception) { statusCode = HttpStatusCode.BadRequest; response = exception.Message; return(response); } SyndicationFeed feed = SyndicationHelper.CreateSyndicationFeed(resources, searchQuery, context.Request.Url); response = SyndicationHelper.GetResponseDocument(feed, requestType); statusCode = HttpStatusCode.OK; } return(response); }
/// <summary> /// Validates the authenticated token /// </summary> /// <param name="token">Authenticated token</param> private static void ValidateToken(AuthenticatedToken token) { if (token == null) { throw new ArgumentNullException("token"); } if (!token.Validate()) { throw new AuthorizationException(ConstantStrings.TokenNotValidException); } }
/// <summary> /// Validates the authenticated token. /// </summary> /// <param name="token">Authenticated token</param> private static void ValidateToken(AuthenticatedToken token) { if (token == null) { throw new ArgumentNullException("token"); } if (!token.Validate()) { throw new AuthorizationException(Resources.InvalidToken); } }
/// <summary> /// Ges the identity of the entity accessessing zentity core. /// </summary> /// <param name="context">Zentity context</param> /// <param name="token">Authenticated tokend </param> /// <returns>Identity of the entity accessessing zentity core</returns> private static Identity GetIdentity(ZentityContext context, AuthenticatedToken token) { Identity identity = context.Resources.OfType <Identity>() .Where(s => s.IdentityName == token.IdentityName).First(); if (identity == null) { throw new AuthenticationException(Resources.InvalidToken); } return(identity); }
/// <summary> /// Validates the token. The token is valid if it is /// not null and Validate() on the token returns true. /// </summary> /// <param name="token">Authenticated token</param> private static void ValidateToken(AuthenticatedToken token) { if (token == null) { throw new ArgumentNullException("token"); } if (!token.Validate()) { throw new AuthenticationException(ConstantStrings.InvalidTokenMessage); } }
private void InitializeContols() { Initialize(); userToken = (AuthenticatedToken)Session[Constants.AuthenticationTokenKey]; ValidatePage(); if (!Page.IsPostBack) { PopulateGlobalPermission(); } }
/// <summary> /// Appends the authorization clause to TSQL query. /// </summary> /// <param name="token">Authenticated token representing the user.</param> /// <param name="transactionSqlQuery">Tsql query</param> /// <param name="storeConnectionString">Store connection string.</param> /// <returns>TSQL with authorization clause.</returns> public static string AppendAuthorizationCriteria( AuthenticatedToken token, string transactionSqlQuery, string storeConnectionString) { string securityWhereClause = TsqlAuthorization.GetAuthorizationCriteria(token, storeConnectionString); string matchingResourcesSqlQuery = String.Format(CultureInfo.InvariantCulture, SearchConstants.TSQL_AUTHORIZATION, transactionSqlQuery, securityWhereClause); return(matchingResourcesSqlQuery); }
/// <summary> /// Authenticates a user by calling the authentication provider's Authenticate API. /// </summary> /// <param name="userName">Name of the user.</param> /// <param name="password">The password.</param> /// <returns>The <see cref="AuthenticatedToken"/>.</returns> private AuthenticatedToken AuthenticateUser(string userName, string password) { #region Parameter Validation if (string.IsNullOrEmpty(userName)) { return(null); } #endregion UserNameSecurityToken token = new UserNameSecurityToken(userName, password); AuthenticatedToken userToken = provider.Authenticate(token); return(userToken); }
protected void Page_Load(object sender, EventArgs e) { userToken = Session[Constants.AuthenticationTokenKey] as AuthenticatedToken; if (!Page.IsPostBack) { using (ZentityContext context = Utility.CreateContext()) { if (ControlMode == RoleType.Group) { List <Group> listGroup = new List <Group>(); using (ResourceDataAccess dataAccess = new ResourceDataAccess(Utility.CreateContext())) { listGroup = dataAccess.GetGroups(string.Empty).OrderBy(tuple => tuple.GroupName).ToList(); } HandledExsitingGroups(listGroup); } else if (ControlMode == RoleType.User) { List <Identity> listIdentity = new List <Identity>(); using (ResourceDataAccess dataAccess = new ResourceDataAccess(Utility.CreateContext())) { listIdentity = dataAccess.GetIdentities(string.Empty).OrderBy(tuple => tuple.IdentityName).ToList(); } HandledExsitingIdentities(listIdentity); } else { List <Resource> listResource = context.Resources.ToList(); foreach (Resource resource in listResource) { if (SelectedMode == ListSelectionMode.Single) { lstGroupList.Items.Add(new ListItem(resource.Title, resource.Id.ToString())); chkGroupList.Visible = false; lstGroupList.Visible = true; } else { chkGroupList.Items.Add(new ListItem(resource.Title, resource.Id.ToString())); } } } } } InitializeLabels(); }
void Application_Start(object sender, EventArgs e) { //Fired when the first instance of the HttpApplication class is created. //It allows you to create objects that are accessible by all //HttpApplication instances. string guestUserName = UserManager.GuestUserName; string guestPassword = Resources.Resources.GuestPassword; using (ResourceDataAccess resourceDataAccess = new ResourceDataAccess()) { guestSecurityToken = resourceDataAccess.Authenticate(guestUserName, guestPassword); } }
/// <summary> /// Creates a new Resource.File for a specified resource of type collectionName in the repository. /// </summary> /// <param name="collectionName">The resource type.</param> /// <param name="mimeType">The MIME type of media.</param> /// <param name="media">The new File contents.</param> /// <param name="fileExtension">The media file extension.</param> /// <returns>A SyndicationItem that describes the newly created resource.</returns> /// <exception cref="ArgumentNullException">Throws exception if collectionName is null/empty /// or mimeType is null/empty or media is null.</exception> protected SyndicationItem CreateMedia(string collectionName, string mimeType, byte[] media, string fileExtension) { if (string.IsNullOrEmpty(collectionName)) { throw new ArgumentNullException("collectionName"); } if (string.IsNullOrEmpty(mimeType)) { throw new ArgumentNullException("mimeType"); } if (null == media) { throw new ArgumentNullException("media"); } AuthenticatedToken authenticatedToken = CoreHelper.GetAuthenticationToken(); using (ZentityContext context = CoreHelper.CreateZentityContext()) { if (!authenticatedToken.HasCreatePermission(context)) { throw new UnauthorizedException(Resources.ATOMPUB_UNAUTHORIZED); } ScholarlyWork resource = CreateScholarlyWork(collectionName); resource.DateModified = DateTime.Now; Core.File mediaResource = new Core.File(); mediaResource.MimeType = mimeType; mediaResource.FileExtension = string.IsNullOrEmpty(fileExtension) ? AtomPubHelper.GetFileExtension(mimeType) : fileExtension; context.AddToResources(mediaResource); context.SaveChanges(); resource.Files.Add(mediaResource); MemoryStream mediaStream = ZentityAtomPubStoreWriter.GetMediaStream(media); context.UploadFileContent(mediaResource, mediaStream); mediaStream.Close(); resource.GrantDefaultPermissions(context, authenticatedToken); mediaResource.GrantDefaultPermissions(context, authenticatedToken); context.SaveChanges(); return(ZentityAtomPubStoreReader.GenerateSyndicationItem(this.BaseUri, resource)); } }
private bool ValidateToken(AuthenticatedToken token) { bool valid = token.Validate(); if (valid) { if (string.Equals(token.IdentityName, this.LogOnName, StringComparison.OrdinalIgnoreCase) || DataAccessLayer.IsAdmin(token.IdentityName)) { return true; } } return false; }
/// <summary> /// Initializes a new instance of the ZentityUser class using the /// logon name of the user and his authenticated token. /// </summary> /// <param name="logOnName">LogOn name of the user</param> /// <param name="userToken">Authenticated token of the logged on user.</param> public ZentityUser(string logOnName, AuthenticatedToken userToken) { #region Parameter Validation ValidateParameters("logOnName", logOnName); if (userToken == null) { throw new ArgumentNullException("userToken"); } #endregion this.Profile = new ZentityUserProfile(); this.LogOnName = logOnName; this.Token = userToken; }
protected void Page_Load(object sender, EventArgs e) { #region Get authentication token AuthenticatedToken token = Session[Constants.AuthenticationTokenKey] as AuthenticatedToken; if (token != null) { userName = token.IdentityName; if (string.Compare(userName, UserManager.GuestUserName, StringComparison.OrdinalIgnoreCase) == 0) { throw new UnauthorizedAccessException(Resources.Resources.UnauthorizedAccessException); } } #endregion }
private DataTable GetSearchResult(Resource resource, ICollection <PropertyValuePair> searchCriteria) { int totalRecords = 0; int totalParsedRecords = GridViewMatchingRecord.PageSize * pager.PageIndex; int index = resource.ToString().LastIndexOf(_CharDot); int minimumPercentageMatchExpected = Convert.ToInt32((MinPerMatchTextBox.Text)); IEnumerable <SimilarRecord> records = null; AuthenticatedToken userToken = (AuthenticatedToken)Session[Constants.AuthenticationTokenKey]; DataTable similarRecordsTable = new DataTable(); similarRecordsTable.Columns.Add(_id); similarRecordsTable.Columns.Add(_title); similarRecordsTable.Columns.Add(_percentageMatch); using (ResourceDataAccess dataAccess = new ResourceDataAccess(Utility.CreateContext())) { records = dataAccess.SearchSimilarResource(resource.ToString().Substring(index + 1), searchCriteria, userToken, totalParsedRecords, out totalRecords, GridViewMatchingRecord.PageSize) .Where(tuple => tuple.PercentageMatch > minimumPercentageMatchExpected); foreach (SimilarRecord record in records) { DataRow row = similarRecordsTable.NewRow(); row[_id] = record.MatchingResource.Id; row[_title] = HttpUtility.HtmlEncode(record.MatchingResource.Title); row[_percentageMatch] = record.PercentageMatch; similarRecordsTable.Rows.Add(row); } } if (GridViewMatchingRecord.PageSize > 0 && totalRecords > 0) { if (totalRecords > GridViewMatchingRecord.PageSize) { pager.TotalPages = Convert.ToInt32(Math.Ceiling((double)totalRecords / GridViewMatchingRecord.PageSize)); } else { pager.PageIndex = 0; pager.TotalPages = 1; } } else { pager.PageIndex = 0; pager.TotalPages = 0; } return(similarRecordsTable); }
private bool GrantOwnership(Guid resourceId) { AuthenticatedToken userToken = (AuthenticatedToken)Session[Constants.AuthenticationTokenKey]; if (resourceId != Guid.Empty) { using (ResourceDataAccess dataAccess = new ResourceDataAccess(Utility.CreateContext())) { return(dataAccess.GrantDefaultOwnership(userToken, resourceId)); } } return(false); }
private async void button6_Click(object sender, EventArgs e) { List <string> grupy = new List <string> { "jira-users", "jira-restricted-users" }; timer.Start(); using (Authentication a = new Authentication()) { AuthenticatedToken token = a.Authenticate(); try { SecurityServer s = a.securityServer; List <string> JiraUsers = new List <string>(); List <string> RestrictedUsers = new List <string>(); List <string> CommonUsers = new List <string>(); SOAPGroup Jiragroup = await s.findGroup(token, grupy[0]); SOAPGroup Restrictedgroup = await s.findGroup(token, grupy[1]); JiraUsers.AddRange(Jiragroup.members.ToList()); RestrictedUsers.AddRange(Restrictedgroup.members.ToList()); CommonUsers = JiraUsers.FindAll(x => RestrictedUsers.Contains(x)); List <SOAPPrincipal> CommonPrincipals = new List <SOAPPrincipal>(); foreach (var user in CommonUsers) { SOAPPrincipal SOAPuser = await s.findPrincipalAsync(token, user); if (SOAPuser.active) { CommonPrincipals.Add(SOAPuser); } } MessageBox.Show(string.Join(" ", CommonPrincipals.Select(x => x.name)), timer.Elapsed.ToString()); timer.Reset(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
/// <summary> /// Gets a SyndicationFeed containing resources of type collectionName. /// </summary> /// <param name="collectionName">The name of the resource type.</param> /// <param name="skip">The number of resources to skip from the start.</param> /// <param name="count">The number of resources to return.</param> /// <returns>A SyndicationFeed of resources of the specified type.</returns> /// <exception cref="ArgumentNullException">Throws exception if collectionName is null/empty.</exception> /// <exception cref="ArgumentException">Throws exception if skip value is negative or count value is negative.</exception> SyndicationFeed IAtomPubStoreReader.GetMembers(string collectionName, long skip, long count) { if (string.IsNullOrEmpty(collectionName)) { throw new ArgumentNullException("collectionName"); } if (0 > skip) { throw new ArgumentException(Resources.ATOMPUB_INVALID_VALUE, "skip"); } if (0 > count) { throw new ArgumentException(Resources.ATOMPUB_INVALID_VALUE, "count"); } int skipCount = (int)skip; int takeCount = (int)count; ResourceType collectionType = coreHelper.GetResourceType(collectionName); // Prepare a query to get a resource with specified Id and specified type. string commandText = string.Format(CultureInfo.InvariantCulture, AtomPubConstants.EsqlToGetAllResources, collectionType.FullName); AuthenticatedToken authenticatedToken = CoreHelper.GetAuthenticationToken(); using (ZentityContext zentityContext = CoreHelper.CreateZentityContext()) { ObjectQuery <ScholarlyWork> resourcesQuery = new ObjectQuery <ScholarlyWork>(commandText, zentityContext); List <ScholarlyWork> resources = resourcesQuery.Authorize("Read", zentityContext, authenticatedToken) .OrderByDescending(resource => resource.DateModified) .Skip(skipCount).Take(takeCount) .ToList(); List <SyndicationItem> syndicationItems = new List <SyndicationItem>(); if (null != resources && 0 < resources.Count) { foreach (ScholarlyWork resource in resources) { SyndicationItem syndicationItem = ZentityAtomPubStoreReader.GenerateSyndicationItem(this.BaseUri, resource); syndicationItems.Add(syndicationItem); } } return(new SyndicationFeed(syndicationItems)); } }
/// <summary> /// Authenticates a user whose credentials are sent in digest authorization header. /// </summary> /// <param name="authorizationHeader">Authorization header</param> /// <param name="httpMethod">Request HttpMethod</param> /// <param name="statusCode">Request status code</param> /// <returns>AuthenticatedToken if user is authenticated, null otherwise.</returns> public AuthenticatedToken Authenticate(string authorizationHeader, string httpMethod, out int statusCode) { #region Parameter validation if (string.IsNullOrEmpty(authorizationHeader)) { statusCode = 401; return(null); } if (string.IsNullOrEmpty(httpMethod)) { statusCode = 400; return(null); } #endregion this.httpMethod = httpMethod; if (!IsAuthorizationHeaderValid(authorizationHeader)) { statusCode = 400; return(null); } //Extract various parts of the header. reqInfo = ExtractAuthorizationHeaderElements(authorizationHeader); if (ValidateAuthorizationHeader(reqInfo)) { AuthenticatedToken userToken = AuthenticateUser(); if (userToken == null) { statusCode = 401; return(null); } else { if (IsNonceStale(reqInfo["nonce"])) { statusCode = 401; return(null); } statusCode = 200; return(userToken); } } else { statusCode = 400; return(null); } }
/// <summary> /// Gets the number of resources present in a collection. /// </summary> /// <param name="collectionName">The collection name.</param> /// <returns>Number of members present in the specified collection.</returns> long IAtomPubStoreReader.GetMembersCount(string collectionName) { Type collectionType = CoreHelper.GetSystemResourceType(collectionName); // Prepare a query to get a resource with specified Id and specified type. string commandText = string.Format(CultureInfo.InvariantCulture, AtomPubConstants.EsqlToGetAllResources, collectionType.FullName); AuthenticatedToken authenticatedToken = CoreHelper.GetAuthenticationToken(); using (ZentityContext zentityContext = CoreHelper.CreateZentityContext()) { ObjectQuery <ScholarlyWork> resourcesQuery = new ObjectQuery <ScholarlyWork>(commandText, zentityContext); return(Convert.ToInt64(resourcesQuery.Authorize("Read", zentityContext, authenticatedToken) .Count())); } }
/// <summary> /// Gets user permission for the resources in the specified resource list. /// </summary> /// <param name="token">Authentication token</param> /// <param name="resources">List of resources</param> /// <returns>List of resources mapped with user permissions.</returns> public IEnumerable <ResourcePermissions <T> > GetResourcePermissions <T>(AuthenticatedToken token, IList <T> resources) where T : Resource { using (ZentityContext context = new ZentityContext()) { if (token != null && resources != null) { if (resources != null && resources.Count > 0 && token != null) { return(resources.GetPermissions <T>(context, token)); } } return(null); } }
/// <summary> /// Process digest authentication consists of verifying the user credentials sent in the /// authorization header, and setting the response properties - status code, headers. /// </summary> /// <param name="context">The context.</param> /// <param name="authorizationHeader">The authorization header.</param> /// <param name="provider">The provider.</param> /// <returns>System.Boolean value; <c>true</c> if the processing was successful, <c>false</c> otherwise.</returns> private static bool ProcessDigestAuthentication( HttpContext context, string authorizationHeader, IAuthenticationProvider provider) { //Create an instance of DigestAuthentication. //Call Authenticate() on the instance to validate the user credentials. //If request is unauthorized, get the WWW-Authenticate header and add to response headers. //If request is authorized, add the AuthenticatedToken to HttpContext.Items. //If request if authorized add 'Authentication-Info' header to response headers. int statusCode; DigestAuthentication authenticator = new DigestAuthentication(provider); if (IsGuest(authenticator.GetUserName(authorizationHeader), context)) { context.Response.StatusCode = 200; return(true); } AuthenticatedToken token = authenticator.Authenticate(authorizationHeader, context.Request.HttpMethod, out statusCode); context.Response.StatusCode = statusCode; //If the user credentials are invalid or empty, this method adds WWW-Authenticate header to the response if (statusCode == 401) { string wwwAuthHeader = authenticator.GetWwwAuthenticateHeader(); context.Response.AppendHeader("WWW-Authenticate", wwwAuthHeader); return(false); } else if (statusCode == 200) //OK { context.Items.Add("AuthenticatedToken", token); string authInfoHeader = authenticator.GetAuthenticationInfoHeader(); context.Response.AppendHeader("Authentication-Info", authInfoHeader); return(true); } else if (statusCode == 400) //Bad request { return(false); } else { return(false); } }
private async void button4_Click(object sender, EventArgs e) { timer.Start(); using (Authentication a = new Authentication()) { AuthenticatedToken token = a.Authenticate(); try { SecurityServer s = a.securityServer; List <string> users = await s.findAllPrincipalsAsync(token); Dictionary <string, int> UsersWithWrongPassword = new Dictionary <string, int>(); foreach (string user in users) { this.Text = timer.Elapsed.ToString(@"mm\:ss\:ff"); SOAPPrincipal SOAPuser = await s.findPrincipalAsync(token, user); if (SOAPuser.active) { try { string zleHasla = SOAPuser.attributes.SingleOrDefault(x => x.name == "invalidPasswordAttempts")?.values[0]; int.TryParse(zleHasla, out int wrPass); if (wrPass > 2) { UsersWithWrongPassword.Add(SOAPuser.attributes.SingleOrDefault(x => x.name == "displayName")?.values[0], wrPass); } } catch (Exception uex) { MessageBox.Show(uex.Message + '\n' + SOAPuser.name); } } } MessageBox.Show(string.Join("\n", UsersWithWrongPassword.OrderBy(x => x.Key)), timer.Elapsed.ToString()); this.Text = "Form1"; timer.Reset(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } }
/// <summary> /// Deletes a group. /// </summary> /// <param name="group">Group object with all information.</param> /// <param name="token">Token of user who is allowed to delete the group.</param> /// <returns>True if group is deleted successfully, else false.</returns> public static bool DeleteGroup(Group group, AuthenticatedToken token) { #region Parameter Validation ValidateToken(token); ValidateGroup(group); if (group.GroupName == AdminGroupName || group.GroupName == AllUsersGroupName) { throw new ArgumentException(ConstantStrings.AdministratorsOrAllUsersUpdateException); } #endregion using (ZentityContext context = new ZentityContext()) { return(DeleteGroup(group, token, context)); } }
/// <summary> /// Updates user information. /// </summary> /// <param name="identity">Identity object with all information.</param> /// <param name="token">Token of user who is allowed to update the user.</param> /// <returns>True if user is updated successfully, else false.</returns> public static bool UpdateUser(Identity identity, AuthenticatedToken token) { #region Parameter Validation ValidateToken(token); ValidateIdentity(identity); if (identity.IdentityName == AdminUserName || identity.IdentityName == GuestUserName) { throw new ArgumentException(ConstantStrings.AdministratorOrGuestUpdateException); } #endregion using (ZentityContext context = new ZentityContext()) { return(UpdateIdentity(identity, token, context)); } }
/// <summary> /// This method returns the authorized predicates out of the given list of predicates for the given resource. /// </summary> /// <typeparam name="T">Zentity.Core.Resource or its derivative</typeparam> /// <param name="resource">Resource for which the authorized predicates are to be retrieved.</param> /// <param name="predicateUris">List of predicate uri's to be looked for.</param> /// <param name="token">AuthenticatedToken of the logged on user.</param> /// <param name="context">ZentityContext object.</param> /// <returns>List of predicate uris (out of the list given by the user) /// for which the logged on user has authorization.</returns> public static IQueryable <string> GetAuthorizedPredicates <T>( this T resource, IQueryable <string> predicateUris, AuthenticatedToken token, ZentityContext context) where T : Resource { #region Parameter Validation if (resource == null) { throw new ArgumentNullException("resource"); } ValidateParameters(context, predicateUris); ValidateToken(token); #endregion Identity currentUser = GetIdentity(context, token); ////Query for user's relationships as subject with the resource. IQueryable <string> predicatesQuery = context.Relationships.Where( rel => rel.Subject.Id == currentUser.Id && rel.Object.Id == resource.Id) .Select(rel => rel.Predicate.Uri); ////Get the group ids for groups to which the user belongs. var groupIds = context.Relationships.Where(tuple => tuple.Predicate.Uri.Equals(AuthorizingPredicates.IdentityBelongsToGroups, StringComparison.OrdinalIgnoreCase) && tuple.Subject.Id == currentUser.Id).Select(tuple => tuple.Object) .OfType <Group>().Select(tuple => tuple.Id).ToArray(); if (groupIds != null) { for (int i = 0; i < groupIds.Length; i++) { Guid id = groupIds[i]; ////Append the query criteria for each group's relationships as subject with the resource. predicatesQuery = predicatesQuery.Union(context.Relationships.Where( rel => rel.Subject.Id == id && rel.Object.Id == resource.Id) .Select(rel => rel.Predicate.Uri)); } } var authorizedPredicates = from uri1 in predicateUris join uri2 in predicatesQuery.ToList() on uri1 equals uri2 select uri1; return(authorizedPredicates.Distinct()); }
/// <summary> /// Gets the member. /// </summary> /// <param name="context">The context.</param> /// <param name="collectionName">Name of the collection.</param> /// <param name="memberResourceId">The member resource id.</param> /// <param name="permissionName">Name of the permission.</param> /// <returns>A <see cref="Resource"/>.</returns> internal static Resource GetMember( ZentityContext context, string collectionName, string memberResourceId, string permissionName) { Resource resource = GetMember(context, collectionName, memberResourceId); AuthenticatedToken authenticatedToken = CoreHelper.GetAuthenticationToken(); if (!resource.Authorize(permissionName, context, authenticatedToken)) { throw new UnauthorizedException(Resources.ATOMPUB_UNAUTHORIZED); } return(resource); }
protected void Page_Load(object sender, EventArgs e) { //Set AuthenticatedToken to controls. AuthenticatedToken token = this.Session[Constants.AuthenticationTokenKey] as AuthenticatedToken; YearMonthBrowseTree.AuthenticatedToken = CategoryNodeBrowseTree.AuthenticatedToken = ResourceTypeBrowseTree.AuthenticatedToken = AuthorsView.AuthenticatedToken = token; //Set base Url to HiddenUrl control. string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + Request.ApplicationPath; HiddenUrl.Value = baseUrl + _searchPagePath; //Add onclick event Search button SearchButton.Attributes.Add(_onClickEvent, string.Format(CultureInfo.InstalledUICulture, _redirectToSearchPageFunction, SearchTextBox.ClientID, HiddenUrl.ClientID)); }
/// <summary> /// Gets resources on which user is having read permission. /// </summary> /// <param name="token">Authentication Token</param> /// <param name="fetchedRecords">Records fetched</param> /// <param name="pageSize">Page size</param> /// <param name="totalRecords">Total record count</param> /// <param name="sortExpression">Column to sort on</param> /// <param name="sortDirection">Direction to sort in</param> /// <returns>List of Entities</returns> private IList <Resource> GetEntityList(AuthenticatedToken token, int fetchedRecords, int pageSize, out int totalRecords, string sortExpression, System.Web.UI.WebControls.SortDirection sortDirection) { using (ResourceDataAccess dataAccess = new ResourceDataAccess(base.CreateContext())) { if (sortDirection == System.Web.UI.WebControls.SortDirection.Ascending) { return(dataAccess.SearchForResources(token, SearchCriteria, fetchedRecords, pageSize, out totalRecords, sortExpression, Zentity.Platform.SortDirection.Ascending, IsSecurityAwareControl).ToList()); } else { return(dataAccess.SearchForResources(token, SearchCriteria, fetchedRecords, pageSize, out totalRecords, sortExpression, Zentity.Platform.SortDirection.Descending, IsSecurityAwareControl).ToList()); } } }