public AspNetRequest(HttpRequestBase request, IPrincipal user) { _request = request; Cookies = new HttpCookieCollectionWrapper(request.Cookies); User = user; ResolveFormAndQueryString(); }
public static bool UserInGroup(IPrincipal user, params AdGroup[] groups) { using (WindowsImpersonationContextFacade impersonationContext = new WindowsImpersonationContextFacade( nc)) { var context = new PrincipalContext(ContextType.Domain); var userPrincipal = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, user.Identity.Name); if (userPrincipal.IsMemberOf(context, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(AdGroup.SuperAdmin))) { return true; } //Если юзер Суперадмин if (userPrincipal.IsMemberOf(context, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(AdGroup.SpeCalcKontroler))) { return true; } //Если юзер Контролер foreach (var grp in groups) { if (userPrincipal.IsMemberOf(context, IdentityType.Sid, AdUserGroup.GetSidByAdGroup(grp))) { return true; } } return false; } }
protected override Task<SQLQueuedMessage> InsertQueuedMessage(Message message, IPrincipal senderPrincipal) { CheckDisposed(); var op = new SQLiteOperation<SQLQueuedMessage>(() => base.InsertQueuedMessage(message, senderPrincipal)); _operationQueue.Post(op); return op.Task; }
public FakeHttpContext(string relativeUrl, IPrincipal principal, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies, SessionStateItemCollection sessionItems, NameValueCollection serverVariables) : this(relativeUrl, null, principal, formParams, queryStringParams, cookies, sessionItems, serverVariables) { }
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData) { culture = Thread.CurrentThread.CurrentCulture; principal = Thread.CurrentPrincipal; processRequest = ProcessRequest; return processRequest.BeginInvoke(context, cb, extraData); }
public ProjectionConfig(IPrincipal runAs, int checkpointHandledThreshold, int checkpointUnhandledBytesThreshold, int pendingEventsThreshold, int maxWriteBatchLength, bool emitEventEnabled, bool checkpointsEnabled, bool createTempStreams, bool stopOnEof) { if (checkpointsEnabled) { if (checkpointHandledThreshold <= 0) throw new ArgumentOutOfRangeException("checkpointHandledThreshold"); if (checkpointUnhandledBytesThreshold < checkpointHandledThreshold) throw new ArgumentException("Checkpoint threshold cannot be less than checkpoint handled threshold"); } else { if (checkpointHandledThreshold != 0) throw new ArgumentOutOfRangeException("checkpointHandledThreshold must be 0"); if (checkpointUnhandledBytesThreshold != 0) throw new ArgumentException("checkpointUnhandledBytesThreshold must be 0"); } _runAs = runAs; _checkpointHandledThreshold = checkpointHandledThreshold; _checkpointUnhandledBytesThreshold = checkpointUnhandledBytesThreshold; _pendingEventsThreshold = pendingEventsThreshold; _maxWriteBatchLength = maxWriteBatchLength; _emitEventEnabled = emitEventEnabled; _checkpointsEnabled = checkpointsEnabled; _createTempStreams = createTempStreams; _stopOnEof = stopOnEof; }
public UserInboxViewModel GetUserInbox(IPrincipal requestingUser) { UserInboxViewModel retVal = null; //get the requesting sender User user = GetUser(requestingUser.Identity.Name); if (user != null) { //get all their active conversations var activeConversations = user.Conversations.ToList(); retVal = new UserInboxViewModel(); foreach (var conversation in activeConversations) { var users = conversation.Users.ToList(); users.Remove(user); var sender = users.Single(); var conv = new UserInboxViewModel.ConversationViewModel { Id = conversation.Id, HasUnreadMessages = conversation.HasNewMessagesFor(user), SenderImage = sender.ProfileImage != null ? sender.ProfileImage.ImageData.ThumbFileName : Constants.DEFAULT_PROFILE_IMAGE, Sender = sender.Username, LastMessage = conversation.Messages.First().Text }; retVal.Conversations.Add(conv); } FillBaseProperties(retVal, user, requestingUser); } return retVal; }
private static bool IsPermitted(ISecurityManager security, object possiblyPermittable, IPrincipal user, ContentItem item) { var permittable = possiblyPermittable as IPermittable; if (permittable != null && permittable.RequiredPermission > Permission.Read && !security.IsAuthorized(user, item, permittable.RequiredPermission)) return false; return true; }
public static ProfileUser Get(this IProfileRepository repository, IPrincipal user) { string username = GetUserName(user); if (string.IsNullOrEmpty(username)) return new ProfileUser { Name = "Anonymous" }; return repository.Get(username); }
/// <summary> /// Evaluates the specified authority against the specified context that is either a task or operation in Authorization Manager. If the context is an operation it should be prefixed by "O". /// </summary> /// <param name="principal">Principal object containing a windows identity.</param> /// <param name="context">Name of the task or operation to evaluate.</param> /// <returns><strong>True</strong> if AzMan evaluates to true, /// otherwise <strong>false</strong>.</returns> public bool Authorize(IPrincipal principal, string context) { ArgumentValidation.CheckForNullReference(principal, "principal"); ArgumentValidation.CheckForNullReference(context, "context"); SecurityAuthorizationCheckEvent.Fire(principal.Identity.Name, context); AzManAuthorizationProviderData data = GetConfigurationData(); string auditIdentifier = data.AuditIdentifierPrefix + principal.Identity.Name + ":" + context; bool result = false; bool operation = false; if (context.IndexOf(OperationContextPrefix) == 0) { operation = true; context = context.Substring(OperationContextPrefix.Length); } if (operation) { string[] operations = new string[] {context}; result = CheckAccessOperations(data, auditIdentifier, principal.Identity, operations); } else { string[] tasks = new string[] {context}; result = CheckAccessTasks(data, auditIdentifier, principal.Identity, tasks); } if (result == false) { SecurityAuthorizationFailedEvent.Fire(principal.Identity.Name, context); } return result; }
private static bool IsAuthorized(object possiblySecurable, IPrincipal user, ContentItem item) { var securable = possiblySecurable as ISecurable; if (securable != null && securable.AuthorizedRoles != null && !PermissionMap.IsInRoles(user, securable.AuthorizedRoles)) return false; return true; }
public override bool IsInVirtualRole(IPrincipal principal, object context) { var httpContext = HttpContext.Current; if (httpContext == null) return false; var queryStringToken = httpContext.Request.QueryString["token"]; if (string.IsNullOrEmpty(queryStringToken)) return false; if (!ParseGuid(queryStringToken)) return false; var pageRef = new PageReference(httpContext.Request.QueryString["id"]); var pageLanguage = httpContext.Request.QueryString["epslanguage"]; var tokenGuid = new Guid(queryStringToken); if (tokenGuid == Guid.Empty) return false; Logger.InfoFormat("Token present and has the correct format {0}", tokenGuid); var tokenStore = new AccessTokenDataStore(); return tokenStore.PresentToken(tokenGuid, pageRef.ID, pageRef.WorkID, pageLanguage); }
public async Task<string> GetEmailAddress(IPrincipal user) { try { var identities = await (user as ServiceUser).GetIdentitiesAsync(); //Check if the user has logged in using Google as Identity provider var google = identities.OfType<GoogleCredentials>().FirstOrDefault(); if (google != null) { var cachedEmail = LookupEmailFromToken(google.AccessToken); if (!string.IsNullOrEmpty(cachedEmail)) { return cachedEmail; } var googleInfo = await GetProviderInfo(google.AccessToken); var userEmail = googleInfo.Value<string>("email"); await StoreToken(google.AccessToken, userEmail); return userEmail; } } catch(HttpRequestException requestException) { // Swallow error and return null } return null; }
public override List<string> GetApprovedDatabases(IPrincipal user, IHttpContext context = null) { var oAuthUser = user as OAuthPrincipal; if (oAuthUser == null) return new List<string>(); return oAuthUser.GetApprovedDatabases(); }
protected void DoTheSaving(IPrincipal user, IItemEditor editor) { using (mocks.Playback()) { editManager.Save(editor.CurrentItem, editor.AddedEditors, editor.VersioningMode, user); } }
/// <summary> /// Stores the current <see cref="Thread.CurrentPrincipal"/> and replaces it with /// a new role identified in constructor. /// </summary> /// <param name="methodUnderTest">The method under test</param> public override void Before(MethodInfo methodUnderTest) { originalPrincipal = Thread.CurrentPrincipal; var identity = new GenericIdentity("xUnit"); var principal = new GenericPrincipal(identity, new string[] { Name }); Thread.CurrentPrincipal = principal; }
public void Authenticate(IPrincipal principal) { if (ThisIsAValidPrincipal(principal)) UseThePrincipleFromTheTicket(principal); else UseAnUnauthenticatedPrinciple(); }
public SQLQueuedMessage(Message message, IPrincipal senderPrincipal, int attempts) { if (message == null) throw new ArgumentNullException("message"); _message = message; _senderPrincipal = senderPrincipal; _attempts = attempts; }
public void SaveContext() { currentDirectory = Environment.CurrentDirectory; currentCulture = CultureInfo.CurrentCulture; currentUICulture = CultureInfo.CurrentUICulture; currentPrincipal = Thread.CurrentPrincipal; }
public PostController(IPrincipal principal, IUserTasks userTasks, IPostOverviewQuery postOverviewQuery, IPostTasks postTasks) { _principal = principal; _userTasks = userTasks; _postOverviewQuery = postOverviewQuery; _postTasks = postTasks; }
/// <summary> /// Initializes an instance of <see cref="ExecutionContext"/> /// </summary> /// <param name="principal"><see cref="IPrincipal"/> to populate with</param> /// <param name="cultureInfo"><see cref="CultureInfo"/> for the <see cref="ExecutionContext"/></param> /// <param name="detailsPopulator">Callback that gets called for populating the details of the <see cref="ExecutionContext"/></param> /// <param name="system">Name of the system that is running</param> public ExecutionContext(IPrincipal principal, CultureInfo cultureInfo, ExecutionContextPopulator detailsPopulator, string system) { Principal = principal; Culture = cultureInfo; System = system; Details = new WriteOnceExpandoObject(d => detailsPopulator(this,d)); }
/// <inheritdoc /> public Task<string> GetUserIdAsync(IPrincipal user) { if (user == null) { throw new ArgumentNullException("user"); } string id = null; ClaimsPrincipal principal = user as ClaimsPrincipal; if (principal != null) { Claim claim = principal.FindFirst(_claimsType); if (claim != null) { id = claim.Value; } } // Fall back to name property if (id == null && user.Identity != null) { id = user.Identity.Name; } if (id == null) { string msg = CustomResources.Manager_NoUser; throw new InvalidOperationException(msg); } return Task.FromResult(id); }
//[Authorize(Roles=TadmapRoles.Collector)] public ActionResult Index(IPrincipal principal) { if (Request.IsAuthenticated) { List<ImageItem> images = ImageRepository.GetAllImages() .IsOwnedBy((principal.Identity as TadmapIdentity).Id) .Select(i => new ImageItem { Id = i.Id, Title = i.Title, Description = i.Description, SquareUrl = BinaryRepository.GetUrl(i.ImageSet.Square), IconAvailable = i.HasIcon } ).ToList(); ViewData.Model = images; return View(); } else { return new RedirectResult(FormsAuthentication.LoginUrl); } }
internal static IQueryable<Agreement> VisibleTo(this IQueryable<Agreement> agreements, IPrincipal principal, IEnumerable<int> ownedTenantIds) { if (agreements == null) return null; if (principal == null) throw new ArgumentNullException("principal"); if (ownedTenantIds == null) throw new ArgumentNullException("ownedTenantIds"); // when user is not an agreement admin, filter out private agreements // and protected agreements that the user does not own if (!principal.IsInAnyRole(RoleName.AgreementManagers)) { return agreements.Where(x => Public.Equals(x.VisibilityText, StringComparison.OrdinalIgnoreCase) || ( Protected.Equals(x.VisibilityText, StringComparison.OrdinalIgnoreCase) && x.Participants.Any(y => y.IsOwner && ownedTenantIds.Contains(y.EstablishmentId)) ) ); } // when user is an agreement admin, include all agreements they own return agreements.Where(x => Public.Equals(x.VisibilityText, StringComparison.OrdinalIgnoreCase) || ( x.Participants.Any(y => y.IsOwner && ownedTenantIds.Contains(y.EstablishmentId)) ) ); }
public static void CheckRegionAllowed(IPrincipal principal,DbContext db, string regionID) { String userID = ((KawalDesaIdentity)principal.Identity).User.Id; if (userID == null) throw new ApplicationException("region is not allowed for thee"); var region = db.Set<Region>() .AsNoTracking() .Include(r => r.Parent) .Include(r => r.Parent.Parent) .Include(r => r.Parent.Parent.Parent) .Include(r => r.Parent.Parent.Parent.Parent) .First(r => r.Id == regionID); var regionIDs = new List<string>(); var current = region; while(current != null) { regionIDs.Add(current.Id); current = current.Parent; } var allowed = db.Set<UserScope>() .Any(s => s.fkUserId == userID && regionIDs.Contains(s.fkRegionId)); if (!allowed) throw new ApplicationException("region is not allowed for thee"); }
public virtual bool OperationPermitted(PamContext context, IPrincipal principal, string operation, object target, bool allowIfNoRule) { if (this.Catalog == null) throw new ApplicationException("Catalog is undefined"); if (principal == null) throw new ArgumentNullException("principal"); if (operation == null) throw new ArgumentNullException("operation"); var ctx = context ?? new PamContext(principal, operation, target); ctx["RawTarget"] = target; try { this.Catalog[operation].Execute(ctx); } catch (Zetetic.Chain.NoSuchCommandException) { this.OnResult(ctx, operation, allowIfNoRule, true); return allowIfNoRule; } this.OnResult(ctx, operation, ctx.Permit, false); return ctx.Permit; }
private void checkThread(){ if (_current != null && HttpContext.Current != null){ if (HttpContext.Current.Timestamp != _stamp){ _current = null; _stamp = HttpContext.Current.Timestamp; } } if (null == _current){ _current = getHttpUser() ?? Thread.CurrentPrincipal; var un = UserName.For(_current); if (un.IsLocal && un.Domain!="local") { var n = un.Name; if (n.noContent()) { var domain = Environment.UserDomainName; if(domain.ToLower()==Environment.MachineName.ToLower()) { domain = "local"; } _current = (domain + "\\" + Environment.UserName).toPrincipal(); } else { _current = (@"local\" + un.Name).toPrincipal(); } } } }
public List<string> GetApprovedDatabases(IPrincipal user) { var oAuthUser = user as OAuthPrincipal; if (oAuthUser == null) return new List<string>(); return oAuthUser.GetApprovedDatabases(); }
public string GetHtml(IPrincipal currentPrincipal, string returnUrl) { if (currentPrincipal == null) throw new ArgumentNullException(nameof(currentPrincipal)); if (returnUrl == null) throw new ArgumentNullException(nameof(returnUrl)); return GetHtmlInternal(currentPrincipal, returnUrl); }
private PrincipalProviderResult CreateResultWithThisPrincipal(IPrincipal principal) { return new PrincipalProviderResult { Principal = principal, }; }
/// <summary> /// Update the specified object /// </summary> public override ActRelationship UpdateInternal(DataContext context, ActRelationship data, IPrincipal principal) { data.TargetActKey = data.TargetAct?.Key ?? data.TargetActKey; data.RelationshipTypeKey = data.RelationshipType?.Key ?? data.RelationshipTypeKey; return(base.UpdateInternal(context, data, principal)); }
public Espn(IRepositoryProvider provider, IPrincipal user) : base(provider, ImportSite.Espn, user) { }
private string GetHtmlInternal(IPrincipal currentPrincipal, string returnUrl) { var css = Resources.GetCss(); var currentUser = currentPrincipal.Identity.Name; if (string.IsNullOrEmpty(currentUser)) { currentUser = AnonymousUser; } var items = _options.Users.Select(x => string.Format(@" <li class=""{0}""> <a href=""{1}?{2}={3}{4}"" class=""stuntman-item"" title=""{5}Source: {6}""> <h3>{7}</h3> </a> </li>", string.Equals(currentUser, x.Name, StringComparison.OrdinalIgnoreCase) ? "stuntman-active" : string.Empty, _options.SignInUri, Constants.StuntmanOptions.OverrideQueryStringKey, WebUtility.UrlEncode(x.Id), returnUrl == null ? null : $"&{Constants.StuntmanOptions.ReturnUrlQueryStringKey}={WebUtility.UrlEncode(returnUrl)}", string.IsNullOrWhiteSpace(x.Description) ? null : WebUtility.HtmlEncode(x.Description) + " ", x.Source, x.Name)) .ToList(); items.Add($@" <li> <a href=""{_options.SignOutUri}?{Constants.StuntmanOptions.ReturnUrlQueryStringKey}={WebUtility.UrlEncode(returnUrl)}"" class=""stuntman-item stuntman-logout""> <h3>Logout</h3> </a> </li>"); return(@" <!-- Begin Stuntman -->" + Environment.NewLine + $@"<style> {css} </style> <div class=""stuntman-widget stuntman-alignment-{_options.UserPickerAlignment.ToString().ToLowerInvariant()}""> <div id=""stuntman-header-js"" class=""stuntman-header""> <h2 class=""stuntman-title""> <a href=""#""> <img class=""stuntman-helmet{(currentUser == AnonymousUser ? " stuntman-helmet-disabled" : null)}"" src=""{HelmetImgSrc}"" /> {currentUser} </a> </h2> </div> <div id=""stuntman-collapse-container-js"" class=""stuntman-body""> <ul> {string.Join(Environment.NewLine, items)} </ul> </div> </div> <script> (function() {{ var header = document.getElementById('stuntman-header-js'); var collapseContainer = document.getElementById('stuntman-collapse-container-js'); collapseContainer.style.display = 'none'; header.addEventListener('click', function() {{ var currentDisplay = collapseContainer.style.display; if (currentDisplay === 'none') {{ collapseContainer.style.display = 'inherit'; }} else {{ collapseContainer.style.display = 'none'; }} }}, false); }})(); </script>".Replace(Environment.NewLine, null) + Environment.NewLine + "<!-- End Stuntman -->" + Environment.NewLine); }
private async Task ProcessRequest(MessageContext restbusContext, CancellationToken cancellationToken) { //NOTE: This method is called on a background thread and must be protected by an outer big-try catch HttpRequestMessage requestMsg; HttpResponseMessage responseMsg = null; if (!restbusContext.Request.TryGetHttpRequestMessage(appVirtualPath ?? (appVirtualPath = System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath), out requestMsg)) { responseMsg = new HttpResponseMessage(HttpStatusCode.BadRequest) { ReasonPhrase = "Bad Request" }; } if (disposed) { responseMsg = requestMsg.CreateErrorResponse(HttpStatusCode.ServiceUnavailable, "The server is no longer available."); } else { requestHandler.EnsureInitialized(); // Add current synchronization context to request parameter SynchronizationContext syncContext = SynchronizationContext.Current; if (syncContext != null) { requestMsg.SetSynchronizationContext(syncContext); } // Add HttpConfiguration to request parameter requestMsg.SetConfiguration(config); // Ensure we have a principal, even if the host didn't give us one IPrincipal originalPrincipal = Thread.CurrentPrincipal; if (originalPrincipal == null) { Thread.CurrentPrincipal = anonymousPrincipal.Value; } // Ensure we have a principal on the request context (if there is a request context). HttpRequestContext requestContext = requestMsg.GetRequestContext(); if (requestContext == null) { requestContext = new RequestBackedHttpRequestContext(requestMsg); // if the host did not set a request context we will also set it back to the request. requestMsg.SetRequestContext(requestContext); } try { try { responseMsg = await requestHandler.SendMessageAsync(requestMsg, cancellationToken); } catch (HttpResponseException exception) { responseMsg = exception.Response; } catch (NullReferenceException exception) { // There is a bug in older versions of HttpRoutingDispatcher which causes a null reference exception when // a route could not be found // This bug can be triggered by sending a request for a url that doesn't have a route // This commit fixes the bug https://github.com/ASP-NET-MVC/aspnetwebstack/commit/6a0c03f9e549966a7f806f8b696ec4cb2ec272e6#diff-c89c7bee3d225a037a6d04e8e4447460 if (exception.TargetSite != null && exception.TargetSite.DeclaringType != null && exception.TargetSite.DeclaringType.FullName == "System.Web.Http.Dispatcher.HttpRoutingDispatcher" && exception.TargetSite.Name == "SendAsync") { //This is the bug, so send a 404 instead const string NoRouteMatchedHttpPropertyKey = "MS_NoRouteMatched"; requestMsg.Properties.Add(NoRouteMatchedHttpPropertyKey, true); responseMsg = requestMsg.CreateErrorResponse( HttpStatusCode.NotFound, String.Format("No HTTP resource was found that matches the request URI '{0}'.", requestMsg.RequestUri)); } else { responseMsg = CreateResponseMessageFromException(exception); } } catch (Exception exception) { responseMsg = CreateResponseMessageFromException(exception); } if (responseMsg == null) { //TODO: Not good, Log this //TODO: derive exception from RestBus.Exceptions class responseMsg = CreateResponseMessageFromException(new ApplicationException("Unable to get response")); } } finally { Thread.CurrentPrincipal = originalPrincipal; } } //Send Response try { //TODO: Why can't the subscriber append the subscriber id itself from within sendresponse subscriber.SendResponse(restbusContext, CreateResponsePacketFromMessage(responseMsg, subscriber)); } catch { //TODO: Log SendResponse error } }
public bool IsVisible(IPrincipal principal, object target, string memberName) => throw new Exception($"MyBar1Authorizer#IsVisible, user: {principal.Identity.Name}, target: {target}, memberName: {memberName}");
public bool IsVisible(IPrincipal principal, object target, string memberName) => true;
public async Task WebSocketSslMutalAuthTest() { string testName = "WebSocketSslMutalAuthTest"; Address listenAddress = new Address("wss://localhost:18081/" + testName + "/"); X509Certificate2 cert = ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, "localhost"); string output; int code = Exec("netsh.exe", string.Format("http show sslcert hostnameport={0}:{1}", listenAddress.Host, listenAddress.Port), out output); if (code != 0) { string args = string.Format("http add sslcert hostnameport={0}:{1} certhash={2} certstorename=MY appid={{{3}}} clientcertnegotiation=enable", listenAddress.Host, listenAddress.Port, cert.Thumbprint, Guid.NewGuid()); code = Exec("netsh.exe", args, out output); Assert.AreEqual(0, code, "failed to add ssl cert: " + output); } X509Certificate serviceCert = null; X509Certificate clientCert = null; ListenerLink listenerLink = null; var linkProcessor = new TestLinkProcessor(); linkProcessor.SetHandler(a => { listenerLink = a.Link; return(false); }); var host = new ContainerHost(listenAddress); host.Listeners[0].SASL.EnableExternalMechanism = true; host.Listeners[0].SSL.ClientCertificateRequired = true; host.Listeners[0].SSL.CheckCertificateRevocation = true; host.Listeners[0].SSL.RemoteCertificateValidationCallback = (a, b, c, d) => { clientCert = b; return(true); }; host.RegisterLinkProcessor(linkProcessor); host.Open(); try { ServicePointManager.ServerCertificateValidationCallback = (a, b, c, d) => { serviceCert = b; return(true); }; var wssFactory = new WebSocketTransportFactory(); wssFactory.Options = o => { o.ClientCertificates.Add(ContainerHostTests.GetCertificate(StoreLocation.LocalMachine, StoreName.My, listenAddress.Host)); }; ConnectionFactory connectionFactory = new ConnectionFactory(new TransportProvider[] { wssFactory }); connectionFactory.SASL.Profile = SaslProfile.External; Connection connection = await connectionFactory.CreateAsync(listenAddress); Session session = new Session(connection); SenderLink sender = new SenderLink(session, "sender-" + testName, "q1"); await sender.SendAsync(new Message("test") { Properties = new Properties() { MessageId = testName } }); await connection.CloseAsync(); Assert.IsTrue(serviceCert != null, "service cert not received"); Assert.IsTrue(clientCert != null, "client cert not received"); Assert.IsTrue(listenerLink != null, "link not attached"); IPrincipal principal = ((ListenerConnection)listenerLink.Session.Connection).Principal; Assert.IsTrue(principal != null, "connection pricipal is null"); Assert.IsTrue(principal.Identity is X509Identity, "identify should be established by client cert"); } finally { host.Close(); } }
public AuditServices(IMongoDBRepository <AuditLog, ObjectId> auditLogRepository, IMongoDBRepository <AuditEntry, ObjectId> auditEntryRepository, IMongoDBRepository <AuditPropertysEntry, ObjectId> auditPropertysEntryRepository, UserManager <User> userManager, IPrincipal principal) { _auditLogRepository = auditLogRepository; _auditEntryRepository = auditEntryRepository; _auditPropertysEntryRepository = auditPropertysEntryRepository; _userManager = userManager; _principal = principal; }
private ResolvedEvent[] ResolveReadAllResult(IList <CommitEventRecord> records, bool resolveLinks, IPrincipal user) { var result = new ResolvedEvent[records.Count]; if (resolveLinks) { for (var i = 0; i < result.Length; ++i) { var record = records[i]; var resolvedPair = ResolveLinkToEvent(record.Event, user, record.CommitPosition); if (resolvedPair == null) { return(null); } result[i] = resolvedPair.Value; } } else { for (var i = 0; i < result.Length; ++i) { result[i] = ResolvedEvent.ForUnresolvedEvent(records[i].Event, records[i].CommitPosition); } } return(result); }
public MovieRequestEngine(IMovieDbApi movieApi, IRequestServiceMain requestService, IPrincipal user, INotificationHelper helper, IRuleEvaluator r, IMovieSender sender, ILogger <MovieRequestEngine> log, OmbiUserManager manager, IRepository <RequestLog> rl, ICacheService cache, ISettingsService <OmbiSettings> ombiSettings, IRepository <RequestSubscription> sub) : base(user, requestService, r, manager, cache, ombiSettings, sub) { MovieApi = movieApi; NotificationHelper = helper; Sender = sender; Logger = log; _requestLog = rl; }
/// <summary> /// Insert the relationship /// </summary> public override ActRelationship InsertInternal(DataContext context, ActRelationship data, IPrincipal principal) { // Ensure we haven't already persisted this if (data.TargetAct != null) { data.TargetAct = data.TargetAct.EnsureExists(context, principal) as Act; } data.TargetActKey = data.TargetAct?.Key ?? data.TargetActKey; data.RelationshipTypeKey = data.RelationshipType?.Key ?? data.RelationshipTypeKey; byte[] target = data.TargetActKey.Value.ToByteArray(), source = data.SourceEntityKey.Value.ToByteArray(), typeKey = data.RelationshipTypeKey.Value.ToByteArray(); //SqlStatement sql = new SqlStatement<DbActRelationship>().SelectFrom() // .Where<DbActRelationship>(o => o.SourceUuid == source) // .Limit(1).Build(); //IEnumerable<DbActRelationship> dbrelationships = context.TryGetData($"EX:{sql.ToString()}") as IEnumerable<DbActRelationship>; //if (dbrelationships == null) //{ // dbrelationships = context.Connection.Query<DbActRelationship>(sql.SQL, sql.Arguments.ToArray()).ToList(); // context.AddData($"EX{sql.ToString()}", dbrelationships); //} //var existing = dbrelationships.FirstOrDefault( // o => o.RelationshipTypeUuid == typeKey && // o.TargetUuid == target); //if (existing == null) //{ return(base.InsertInternal(context, data, principal)); // (dbrelationships as List<DbActRelationship>).Add(new DbActRelationship() // { // Uuid = retVal.Key.Value.ToByteArray(), // RelationshipTypeUuid = typeKey, // SourceUuid = source, // TargetUuid = target // }); // return retVal; //} //else //{ // data.Key = new Guid(existing.Uuid); // return data; //} }
private ResolvedEvent[] ResolveLinkToEvents(EventRecord[] records, bool resolveLinks, IPrincipal user) { var resolved = new ResolvedEvent[records.Length]; if (resolveLinks) { for (var i = 0; i < records.Length; i++) { var rec = ResolveLinkToEvent(records[i], user, null); if (rec == null) { return(null); } resolved[i] = rec.Value; } } else { for (int i = 0; i < records.Length; ++i) { resolved[i] = ResolvedEvent.ForUnresolvedEvent(records[i]); } } return(resolved); }
private string GetIdentityIdentifier(IPrincipal currentPrincipal) { NullGuard.NotNull(currentPrincipal, nameof(currentPrincipal)); return(GetIdentityIdentifier(currentPrincipal.Identity)); }
/// <summary> /// Get from source /// </summary> public IEnumerable GetFromSource(DataContext context, Guid id, decimal?versionSequenceId, IPrincipal principal) { int tr = 0; return(this.QueryInternal(context, base.BuildSourceQuery <ActRelationship>(id, versionSequenceId), Guid.Empty, 0, null, out tr, principal, false).ToList()); }
// ReSharper disable once RedundantAssignment public static IEnumerable <JObject> RunSingleTestBatch(this IDSFDataObject dataObject, string serviceName, IPrincipal userPrinciple, Guid workspaceGuid, Dev2JsonSerializer serializer, ITestCatalog catalog, ref DataListFormat formatter) { var allTests = catalog.Fetch(dataObject.ResourceID) ?? new List <IServiceTestModelTO>(); var taskList = new List <Task>(); var testResults = new List <IServiceTestModelTO>(); foreach (var test in allTests.Where(to => to.Enabled)) { var dataObjectClone = dataObject.Clone(); dataObjectClone.Environment = new ExecutionEnvironment(); dataObjectClone.TestName = test.TestName; var lastTask = ServiceTestExecutor.GetTaskForTestExecution(serviceName, userPrinciple, workspaceGuid, serializer, testResults, dataObjectClone); taskList.Add(lastTask); } Task.WaitAll(taskList.ToArray()); formatter = DataListFormat.CreateFormat("JSON", EmitionTypes.JSON, "application/json"); return((from testRunResult in testResults where testRunResult != null select testRunResult.BuildTestResultForWebRequest() ).ToList()); }
public bool IsAllowedOnBehalfOfAccount(IPrincipal currentPrincipal, User account) { return(PermissionsHelpers.IsRequirementSatisfied(AccountOnBehalfOfPermissionsRequirement, currentPrincipal, account)); }
public bool CanRevokeAccess(string userId, IPrincipal revokedBy) { return(revokedBy.IsSystemAdministrator()); }
private IPrincipal CreatePrincipal(string name, string[] roles) { return(testPrincipal = new GenericPrincipal(new GenericIdentity(name), roles)); }
public IUser GetCurrentUserWithHttpScopeCaching(IPrincipal user, bool userIsOnline) { return(_currentUser ?? (_currentUser = (user.Identity.Name.IsNullOrEmpty() ? IUser.Anonymous : GetUser(user.Identity.Name, userIsOnline) ?? IUser.Anonymous))); }
public override CommandResponse <IVoteRestriction> Evaluate(IPrincipal principal) { throw new NotImplementedException(); }
public Session(IPrincipal principal) { Principal = principal; }
public ComposizionePartenzaAvanzataAuthorizationQueryHandlerDecorator(IPrincipal currentUser) { this._currentUser = currentUser; }
public static DataListFormat RunMultipleTestBatches(this IDSFDataObject dataObject, IPrincipal userPrinciple, Guid workspaceGuid, Dev2JsonSerializer serializer, DataListFormat formatter, IResourceCatalog catalog, ITestCatalog testCatalog, ref string executePayload) { foreach (var testsResourceId in dataObject.TestsResourceIds) { var allTests = testCatalog.Fetch(testsResourceId); var taskList = new List <Task>(); var testResults = new List <IServiceTestModelTO>(); foreach (var test in allTests) { dataObject.ResourceID = testsResourceId; var dataObjectClone = dataObject.Clone(); dataObjectClone.Environment = new ExecutionEnvironment(); dataObjectClone.TestName = test.TestName; var res = catalog.GetResource(GlobalConstants.ServerWorkspaceID, testsResourceId); var resourcePath = res.GetResourcePath(GlobalConstants.ServerWorkspaceID).Replace("\\", "/"); var lastTask = ServiceTestExecutor.GetTaskForTestExecution(resourcePath, userPrinciple, workspaceGuid, serializer, testResults, dataObjectClone); taskList.Add(lastTask); } Task.WaitAll(taskList.ToArray()); formatter = DataListFormat.CreateFormat("JSON", EmitionTypes.JSON, "application/json"); var objArray = (from testRunResult in testResults where testRunResult != null select testRunResult.BuildTestResultForWebRequest() ).ToList(); executePayload = executePayload + Environment.NewLine + serializer.Serialize(objArray); } return(formatter); }
public CommentDataAccessStrategy(IPrincipal principal, IDataAccessStrategy <File> fileDataAccessStrategy) : base(principal) { this.fileDataAccessStrategy = fileDataAccessStrategy; }
//private readonly string ROOT = System.Configuration.ConfigurationManager.AppSettings["FOLDER_BROWSER_PATH"]; public FolderBrowserService(IPrincipal principal) : base(principal) { }
public static IReaderStrategy Create( string tag, int phase, IQuerySources sources, ITimeProvider timeProvider, bool stopOnEof, IPrincipal runAs) { if (!sources.AllStreams && !sources.HasCategories() && !sources.HasStreams()) { throw new InvalidOperationException("None of streams and categories are included"); } if (!sources.AllEvents && !sources.HasEvents()) { throw new InvalidOperationException("None of events are included"); } if (sources.HasStreams() && sources.HasCategories()) { throw new InvalidOperationException( "Streams and categories cannot be included in a filter at the same time"); } if (sources.AllStreams && (sources.HasCategories() || sources.HasStreams())) { throw new InvalidOperationException("Both FromAll and specific categories/streams cannot be set"); } if (sources.AllEvents && sources.HasEvents()) { throw new InvalidOperationException("Both AllEvents and specific event filters cannot be set"); } if (sources.ByStreams && sources.HasStreams()) { throw new InvalidOperationException( "foreachStream projections are not supported on stream based sources"); } if (sources.ReorderEventsOption) { if (sources.AllStreams) { throw new InvalidOperationException("Event reordering cannot be used with fromAll()"); } if (!(sources.HasStreams() && sources.Streams.Length > 1)) { throw new InvalidOperationException( "Event reordering is only available in fromStreams([]) projections"); } if (sources.ProcessingLagOption < 50) { throw new InvalidOperationException("Event reordering requires processing lag at least of 50ms"); } } if (sources.HandlesDeletedNotifications && !sources.ByStreams) { throw new InvalidOperationException( "Deleted stream notifications are only supported with foreachStream()"); } var readerStrategy = new ReaderStrategy( tag, phase, sources.AllStreams, sources.Categories, sources.Streams, sources.AllEvents, sources.IncludeLinksOption, sources.Events, sources.HandlesDeletedNotifications, sources.ProcessingLagOption, sources.ReorderEventsOption, runAs, timeProvider); return(readerStrategy); }
public CentroMappaMarkerAuthorizationQueryHandlerDecorator(IPrincipal currentUser) { this._currentUser = currentUser; }
public UserService(IAuthenticationService authSerice, ICryptographyService cryptographyService, IDataProvider dataProvider, IPrincipal principal) { _authenticationService = authSerice; _dataProvider = dataProvider; _cryptographyService = cryptographyService; _principal = principal; }
public static long GetUserId(IPrincipal user) { return(user.Identity.GetUserId <long>()); }
protected override async Task <long> ExecuteFlowStepsAsync(NewTodoItemInfo input, IPrincipal flowInitiator) { input.Owner = flowInitiator; return(await todoItemService.AddAsync(input)); }