public async Task Invoke(HttpContext context, IAuthorizationService authorizationService) {
     if(context.Request.Path.StartsWithSegments(_path)) {
         if(await authorizationService.AuthorizeAsync(context.User, null, _policy)) {
             await _next(context);
         }
     }
 }
Example #2
0
        public async Task Invoke(HttpContext httpContext, 
                                 IAuthorizationService authorizationService)
        {
            if(httpContext.Request.Path.StartsWithSegments(_path))
            {
                var authorized = await authorizationService.AuthorizeAsync(
                                    httpContext.User, null, _policyName);
                if (!authorized)
                {
                    await httpContext.Authentication.ChallengeAsync();
                    return;
                }
            }

            await _next(httpContext);
        }
Example #3
0
        public async Task Invoke(HttpContext httpContext, IAuthorizationService authorizationService)
        {
            var middlewarePlugins = new List<IMiddlewarePlugin>();

            foreach (var record in _settings.Value.GlobalPath.OptIn)
            {
                foreach (var path in record.Paths)
                {
                    if (httpContext.Request.Path.StartsWithSegments(path))
                    {
                        // gotcha.
                        var authorized = await authorizationService.AuthorizeAsync(
                               httpContext.User, null, _policyName);
                        if (!authorized)
                        {
                            await httpContext.Authentication.ChallengeAsync();
                            return;
                        }
                    }
                }
            }
            await _next(httpContext);

        }
Example #4
0
        public async Task <SaveSiteAccountResponse> Save([FromBody] SaveSiteAccountRequest request)
        {
            SaveSiteAccountResponse response = new SaveSiteAccountResponse();

            if (response.InitializeFromModelStateIfInvalid(ModelState))
            {
                return(response);
            }



            if (request.ShouldUpdateAllProps)
            {
                await _siteAccountUpsert.ExecuteAsync(request.SiteAccount);
            }
            else
            {
                var existingSite = _siteAccountSearch.Execute(new SiteAccountSearchCriteria
                {
                    IncludedSiteAccounts = new List <Guid> {
                        request.SiteAccount.ID
                    }
                }).First();

                request.SiteAccount.CopyProperties(existingSite,
                                                   (propInfo, source, target) => request.PropsToUpdate.Contains(propInfo.Name));

                if (request.SiteAccountUserAccounts.Any(saua => saua.RoleID != Role.GuestRoleID ||
                                                        saua.IsActive))
                {
                    string      email = User.FindFirst(c => c.Type == ClaimTypes.Email)?.Value;
                    UserAccount user  = await _userAccountGetByEmail.ExecuteAsync(email, true);

                    AuthorizationResult authResult = await _authorizationService.AuthorizeAsync(User,
                                                                                                new SiteAccountUserAccountRoleModel { SiteAccountID = request.SiteAccount.ID, UserAccount = user },
                                                                                                new SiteAccountRoleRequirement(new Role[] { Role.AdminRole, Role.OwnerRole, Role.BasicRole }));

                    if (!authResult.Succeeded)
                    {
                        return new SaveSiteAccountResponse {
                                   ResponseError = new ResponseError {
                                       ErrorMessage = "Not Authed"
                                   }
                        }
                    }
                    ;
                }

                foreach (var saua in request.SiteAccountUserAccounts)
                {
                    saua.SiteAccountID = existingSite.ID;

                    var existingSiteUser = existingSite.SiteAccountUserAccounts.FirstOrDefault(user => user.UserAccountID == saua.UserAccountID);
                    if (existingSiteUser != null)
                    {
                        existingSite.SiteAccountUserAccounts.Remove(existingSiteUser);
                    }

                    existingSite.SiteAccountUserAccounts.Add(saua);
                }

                await _siteAccountUpsert.ExecuteAsync(existingSite);
            }

            return(response);
        }
    }
Example #5
0
        private async Task <IEnumerable <ContentTypeDefinition> > GetCreatableTypesAsync()
        {
            var creatable = new List <ContentTypeDefinition>();

            foreach (var ctd in _contentDefinitionManager.ListTypeDefinitions())
            {
                if (ctd.Settings.ToObject <ContentTypeSettings>().Creatable)
                {
                    var authorized = await _authorizationService.AuthorizeAsync(User, Permissions.EditContent, _contentManager.New(ctd.Name));

                    if (authorized)
                    {
                        creatable.Add(ctd);
                    }
                }
            }
            return(creatable);
        }
Example #6
0
        public async Task <ActionResult> Index()
        {
            var installThemes = await _authorizationService.AuthorizeAsync(User, StandardPermissions.SiteOwner); // only site owners

            if (!installThemes)
            {
                return(Forbid());
            }

            var currentSiteThemeExtensionInfo = await _siteThemeService.GetSiteThemeAsync();

            var currentAdminThemeExtensionInfo = await _adminThemeService.GetAdminThemeAsync();

            var currentAdminTheme = currentAdminThemeExtensionInfo != null ? new ThemeEntry(currentAdminThemeExtensionInfo) : default(ThemeEntry);
            var currentSiteTheme  = currentSiteThemeExtensionInfo != null ? new ThemeEntry(currentSiteThemeExtensionInfo) : default(ThemeEntry);
            var enabledFeatures   = await _shellFeaturesManager.GetEnabledFeaturesAsync();

            var themes = (await _shellFeaturesManager.GetAvailableFeaturesAsync())
                         .Where(f =>
            {
                if (!f.IsTheme())
                {
                    return(false);
                }

                var tags     = f.Extension.Manifest.Tags.ToArray();
                var isHidden = tags.Any(t => String.Equals(t, "hidden", StringComparison.OrdinalIgnoreCase));
                if (isHidden)
                {
                    return(false);
                }

                return(true);
            })
                         .Select(f =>
            {
                var isAdmin    = IsAdminTheme(f.Extension.Manifest);
                var themeId    = isAdmin ? currentAdminTheme?.Extension.Id : currentSiteTheme?.Extension.Id;
                var isCurrent  = f.Id == themeId;
                var isEnabled  = enabledFeatures.Any(e => e.Id == f.Id);
                var themeEntry = new ThemeEntry(f.Extension)
                {
                    Enabled      = isEnabled,
                    CanUninstall = installThemes,
                    IsAdmin      = isAdmin,
                    IsCurrent    = isCurrent
                };

                return(themeEntry);
            })
                         .OrderByDescending(t => t.IsCurrent);

            var model = new SelectThemesViewModel
            {
                CurrentSiteTheme  = currentSiteTheme,
                CurrentAdminTheme = currentAdminTheme,
                Themes            = themes
            };

            return(View(model));
        }
 public static async Task <bool> IsGrantedAsync(this IAuthorizationService authorizationService, object resource, IEnumerable <IAuthorizationRequirement> requirements)
 {
     return((await authorizationService.AuthorizeAsync(resource, requirements)).Succeeded);
 }
Example #8
0
 public async Task <bool> GetModifyAuthorization()
 {
     return((await _authorizationService.AuthorizeAsync(User, Authorizations.Administrator)).Succeeded);
 }
Example #9
0
        public async Task ShouldNotAllow_SesshinRead_WhenNotAccountant()
        {
            //Arrange

            //Act
            var allowed = await _authorizationService.AuthorizeAsync(_user, new Sesshin(), UserOperations.Read);

            // Assert
            Assert.False(allowed.Succeeded);
        }
Example #10
0
        public async Task <IActionResult> Pin(string id)
        {
            // Ensure we have a valid id
            var ok = int.TryParse(id, out var entityId);

            if (!ok)
            {
                return(NotFound());
            }

            var topic = await _entityStore.GetByIdAsync(entityId);

            // Ensure the topic exists
            if (topic == null)
            {
                return(NotFound());
            }

            // Ensure we have permission
            if (!await _authorizationService.AuthorizeAsync(User, topic.CategoryId, ModeratorPermissions.PinTopics))
            {
                return(Unauthorized());
            }

            var user = await _contextFacade.GetAuthenticatedUserAsync();

            // Update topic
            topic.ModifiedUserId = user?.Id ?? 0;
            topic.ModifiedDate   = DateTimeOffset.UtcNow;
            topic.IsPinned       = true;

            // Save changes and return results
            var result = await _topicManager.UpdateAsync(topic);

            if (result.Succeeded)
            {
                _alerter.Success(T["Topic Pinned Successfully"]);
            }
            else
            {
                _alerter.Danger(T["Could not remove topic from SPAM"]);
            }

            // Redirect back to topic
            return(Redirect(_contextFacade.GetRouteUrl(new RouteValueDictionary()
            {
                ["area"] = "Plato.Discuss",
                ["controller"] = "Home",
                ["action"] = "Display",
                ["opts.id"] = topic.Id,
                ["opts.alias"] = topic.Alias
            })));
        }
Example #11
0
        public async Task <IActionResult> Index()
        {
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.ManageOwnMedia))
            {
                return(Unauthorized());
            }

            return(View());
        }
Example #12
0
        public override async Task <IViewProviderResult> BuildDisplayAsync(Topic topic, IViewProviderContext context)
        {
            var viewModel = context.Controller.HttpContext.Items[typeof(EntityViewModel <Topic, Reply>)] as EntityViewModel <Topic, Reply>;

            if (viewModel == null)
            {
                throw new Exception($"A view model of type {typeof(EntityViewModel<Topic, Reply>).ToString()} has not been registered on the HttpContext!");
            }

            // Get the entity we are viewing
            var entity = await _entityStore.GetByIdAsync(topic.Id);

            // Ensure we found the entity
            if (entity == null)
            {
                return(default(IViewProviderResult));
            }

            // Get search settings
            var searchSettings = await _searchSettingsStore.GetAsync();

            // Build keywords to search
            var keywordList = entity.Title
                              .ToDistinctList()
                              .StripCommonWords()
                              .ToList();

            // Configured search method
            var searchType = SearchTypes.Tsql;

            if (searchSettings != null)
            {
                searchType = searchSettings.SearchType;
            }

            // Default sort by
            var sort = SortBy.LastReply;

            if (searchType != SearchTypes.Tsql)
            {
                sort = SortBy.Rank;
            }

            // Get similar entities
            var entities = await _entityService
                           .ConfigureDb(o => { o.SearchType = searchType; })
                           .ConfigureQuery(async q =>
            {
                // Hide current entity
                q.Id.NotEqual(entity.Id);

                // Hide private?
                if (!await _authorizationService.AuthorizeAsync(context.Controller.HttpContext.User,
                                                                Permissions.ViewPrivateTopics))
                {
                    q.HidePrivate.True();
                }

                // Hide hidden?
                if (!await _authorizationService.AuthorizeAsync(context.Controller.HttpContext.User,
                                                                Permissions.ViewHiddenTopics))
                {
                    q.HideHidden.True();
                }

                // Hide spam?
                if (!await _authorizationService.AuthorizeAsync(context.Controller.HttpContext.User,
                                                                Permissions.ViewSpamTopics))
                {
                    q.HideSpam.True();
                }

                // Hide deleted?
                if (!await _authorizationService.AuthorizeAsync(context.Controller.HttpContext.User,
                                                                Permissions.ViewDeletedTopics))
                {
                    q.HideDeleted.True();
                }

                // Search for similar entities
                if (keywordList.Count > 0)
                {
                    var keywords = String.Join(" ", keywordList.ToArray());
                    q.Keywords.Like(keywords);
                }
            })
                           .GetResultsAsync(
                new EntityIndexOptions()
            {
                FeatureId = entity.FeatureId,
                Sort      = sort
            }, new PagerOptions()
            {
                Page = 1,
                Size = 10
            });

            // Build similar topics view model
            var similarEntitiesViewModel = new SimilarEntitiesViewModel()
            {
                Results = entities
            };

            // Return view
            return(Views(
                       View <SimilarEntitiesViewModel>("Topic.Similar.Display.Sidebar", model => similarEntitiesViewModel).Zone("sidebar").Order(6)
                       ));
        }
Example #13
0
        async Task <IEnumerable <IUser> > ReduceUsersAsync(IEnumerable <Follows.Models.Follow> follows, TEntityReply reply)
        {
            // We always need follows to process
            if (follows == null)
            {
                return(null);
            }

            // Get entity for reply
            var entity = await _entityStore.GetByIdAsync(reply.EntityId);

            // No need to send notifications if the entity is hidden
            if (entity.IsHidden())
            {
                return(null);
            }

            // Get all users following the entity
            // Exclude the author so they are not notified of there own posts
            var users = await _platoUserStore.QueryAsync()
                        .Select <UserQueryParams>(q =>
            {
                q.Id.IsIn(follows
                          .Select(f => f.CreatedUserId)
                          .ToArray());
            })
                        .ToList();

            // No users to further process
            if (users?.Data == null)
            {
                return(null);
            }

            // Build users reducing for permissions
            var result = new Dictionary <int, IUser>();

            foreach (var user in users.Data)
            {
                if (!result.ContainsKey(user.Id))
                {
                    result.Add(user.Id, user);
                }

                // If the entity is hidden but the user does
                // not have permission to view hidden entities
                if (reply.IsHidden)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Discuss.Permissions.ViewHiddenReplies))
                    {
                        result.Remove(user.Id);
                    }
                }

                // The entity has been flagged as SPAM but the user does
                // not have permission to view entities flagged as SPAM
                if (reply.IsSpam)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Discuss.Permissions.ViewSpamReplies))
                    {
                        result.Remove(user.Id);
                    }
                }

                // The entity is soft deleted but the user does
                // not have permission to view soft deleted entities
                if (reply.IsDeleted)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Discuss.Permissions.ViewDeletedReplies))
                    {
                        result.Remove(user.Id);
                    }
                }
            }

            return(result.Count > 0 ? result.Values : null);
        }
Example #14
0
        public async Task <ActionResult> Index()
        {
            var installThemes = await _authorizationService.AuthorizeAsync(User, StandardPermissions.SiteOwner); // only site owners

            if (!installThemes)
            {
                return(Forbid());
            }

            //&& _shellSettings.Name == ShellSettings.; // of the default tenant
            //&& _featureManager.GetEnabledFeatures().FirstOrDefault(f => f.Id == "PackagingServices") != null

            //var featuresThatNeedUpdate = _dataMigrationManager.GetFeaturesThatNeedUpdate();

            var currentSiteThemeExtensionInfo = await _siteThemeService.GetSiteThemeAsync();

            var currentAdminThemeExtensionInfo = await _adminThemeService.GetAdminThemeAsync();

            var currentAdminTheme = currentAdminThemeExtensionInfo != null ? new ThemeEntry(currentAdminThemeExtensionInfo) : default(ThemeEntry);
            var currentSiteTheme  = currentSiteThemeExtensionInfo != null ? new ThemeEntry(currentSiteThemeExtensionInfo) : default(ThemeEntry);
            var enabledFeatures   = await _shellFeaturesManager.GetEnabledFeaturesAsync();

            var themes = _extensionManager.GetExtensions().OfType <IThemeExtensionInfo>().Where(extensionDescriptor =>
            {
                var tags     = extensionDescriptor.Manifest.Tags.ToArray();
                var isHidden = tags.Any(x => string.Equals(x, "hidden", StringComparison.OrdinalIgnoreCase));

                // Is the theme allowed for this tenant?
                // allowed = _shellSettings.Themes.Length == 0 || _shellSettings.Themes.Contains(extensionDescriptor.Id);

                return(!isHidden);
            })
                         .Select(extensionDescriptor =>
            {
                var isAdmin    = IsAdminTheme(extensionDescriptor.Manifest);
                var themeId    = isAdmin ? currentAdminTheme?.Extension.Id : currentSiteTheme?.Extension.Id;
                var isCurrent  = extensionDescriptor.Id == themeId;
                var isEnabled  = enabledFeatures.Any(x => x.Extension.Id == extensionDescriptor.Id);
                var themeEntry = new ThemeEntry(extensionDescriptor)
                {
                    //NeedsUpdate = featuresThatNeedUpdate.Contains(extensionDescriptor.Id),
                    //IsRecentlyInstalled = _themeService.IsRecentlyInstalled(extensionDescriptor),
                    Enabled      = isEnabled,
                    CanUninstall = installThemes,
                    IsAdmin      = isAdmin,
                    IsCurrent    = isCurrent
                };

                //if (_extensionDisplayEventHandler != null)
                //{
                //    foreach (string notification in _extensionDisplayEventHandler.Displaying(themeEntry.Descriptor, ControllerContext.RequestContext))
                //    {
                //        themeEntry.Notifications.Add(notification);
                //    }
                //}

                return(themeEntry);
            })
                         .OrderByDescending(x => x.IsCurrent);

            var model = new SelectThemesViewModel
            {
                CurrentSiteTheme  = currentSiteTheme,
                CurrentAdminTheme = currentAdminTheme,
                Themes            = themes
            };

            return(View(model));
        }
Example #15
0
 private async Task <bool> CanUseInternalLightning()
 {
     return((await _settingsRepository.GetPolicies()).AllowLightningInternalNodeForAll ||
            (await _authorizationService.AuthorizeAsync(User, null,
                                                        new PolicyRequirement(Policies.CanUseInternalLightningNode))).Succeeded);
 }
        public async Task <IActionResult> Index()
        {
            ViewData["Title"] = sr["Content Settings"];

            var projectSettings = await projectService.GetCurrentProjectSettings();

            var model = new ContentSettingsViewModel();

            model.ChannelCategoriesCsv = projectSettings.ChannelCategoriesCsv;
            //model.ChannelRating = projectSettings.ChannelRating;
            //model.ChannelTimeToLive = projectSettings.ChannelTimeToLive;
            model.CommentNotificationEmail = projectSettings.CommentNotificationEmail;
            model.DaysToComment            = projectSettings.DaysToComment;
            model.Description = projectSettings.Description;
            model.IncludePubDateInPostUrls = projectSettings.IncludePubDateInPostUrls;
            model.LanguageCode             = projectSettings.LanguageCode;
            model.ManagingEditorEmail      = projectSettings.ManagingEditorEmail;
            model.ModerateComments         = projectSettings.ModerateComments;
            model.PostsPerPage             = projectSettings.PostsPerPage;
            model.PubDateFormat            = projectSettings.PubDateFormat;
            //model.RemoteFeedProcessorUseAgentFragment = projectSettings.RemoteFeedProcessorUseAgentFragment;
            model.RemoteFeedUrl = projectSettings.RemoteFeedUrl;
            model.ShowTitle     = projectSettings.ShowTitle;
            model.Title         = projectSettings.Title; //aka Blog Page Title
            //model.UseMetaDescriptionInFeed = projectSettings.UseMetaDescriptionInFeed;
            model.WebmasterEmail      = projectSettings.WebmasterEmail;
            model.Publisher           = projectSettings.Publisher;
            model.PublisherLogoUrl    = projectSettings.PublisherLogoUrl;
            model.PublisherLogoHeight = projectSettings.PublisherLogoHeight;
            model.PublisherLogoWidth  = projectSettings.PublisherLogoWidth;
            model.PublisherEntityType = projectSettings.PublisherEntityType;
            model.DisqusShortName     = projectSettings.DisqusShortName;
            model.PostsPerPage        = projectSettings.PostsPerPage;

            model.BlogMenuLinksToNewestPost      = projectSettings.BlogMenuLinksToNewestPost;
            model.DefaultPageSlug                = projectSettings.DefaultPageSlug;
            model.ShowRecentPostsOnDefaultPage   = projectSettings.ShowRecentPostsOnDefaultPage;
            model.ShowFeaturedPostsOnDefaultPage = projectSettings.ShowFeaturedPostsOnDefaultPage;

            model.AddBlogToPagesTree             = projectSettings.AddBlogToPagesTree;
            model.BlogPagePosition               = projectSettings.BlogPagePosition;
            model.BlogPageText                   = projectSettings.BlogPageText;
            model.BlogPageNavComponentVisibility = projectSettings.BlogPageNavComponentVisibility;
            model.LocalMediaVirtualPath          = projectSettings.LocalMediaVirtualPath;
            model.CdnUrl = projectSettings.CdnUrl;

            model.FacebookAppId      = projectSettings.FacebookAppId;
            model.SiteName           = projectSettings.SiteName;
            model.TwitterCreator     = projectSettings.TwitterCreator;
            model.TwitterPublisher   = projectSettings.TwitterPublisher;
            model.DefaultContentType = projectSettings.DefaultContentType;

            model.TeasersDisabled        = _teasersDisabled;
            model.TeaserMode             = projectSettings.TeaserMode;
            model.TeaserTruncationMode   = projectSettings.TeaserTruncationMode;
            model.TeaserTruncationLength = projectSettings.TeaserTruncationLength;

            model.DefaultFeedItems = projectSettings.DefaultFeedItems;
            model.MaxFeedItems     = projectSettings.MaxFeedItems;
            model.AboutContent     = projectSettings.AboutContent;
            model.AboutHeading     = projectSettings.AboutHeading;
            model.ShowAboutBox     = projectSettings.ShowAboutBox;
            model.ShowRelatedPosts = projectSettings.ShowRelatedPosts;

            bool canManageUsers = false;

            try
            {
                var result = await authorizationService.AuthorizeAsync(User, "UserManagementPolicy");

                canManageUsers = result.Succeeded;
            }
            catch (InvalidOperationException) { } // thrown if policy doesn't exist


            if (canManageUsers)
            {
                var contentEditors = await userQueries.GetUsersForClaim(
                    new Guid(projectSettings.Id),
                    ProjectConstants.ContentEditorClaimType,
                    projectSettings.Id
                    );

                if (contentEditors != null)
                {
                    model.Editors.AddRange(contentEditors);
                }

                var blogEditors = await userQueries.GetUsersForClaim(
                    new Guid(projectSettings.Id),
                    ProjectConstants.BlogEditorClaimType,
                    projectSettings.Id
                    );

                if (blogEditors != null)
                {
                    model.Editors.AddRange(blogEditors);
                }

                var pageEditors = await userQueries.GetUsersForClaim(
                    new Guid(projectSettings.Id),
                    ProjectConstants.PageEditorClaimType,
                    projectSettings.Id
                    );

                if (pageEditors != null)
                {
                    model.Editors.AddRange(pageEditors);
                }
            }


            return(View(model));
        }
Example #17
0
        public async Task <IEnumerable <ViewModels.Notification> > GetAsync(CancellationToken ct)
        {
            if (!(await _authorizationService.AuthorizeAsync(_user, null, new FullRightsRequirement())).Succeeded)
            {
                throw new ForbiddenException();
            }

            var items = await _context.Notifications.ToListAsync(ct);

            // Databases do not preserve DateTimeKind, so we need to add UTC kind
            items.ForEach(item => item.BroadcastTime = DateTime.SpecifyKind(item.BroadcastTime, DateTimeKind.Utc));
            return(_mapper.Map <IEnumerable <ViewModels.Notification> >(items));
        }
Example #18
0
        public async Task <ActionResult <ApplicationUserData> > CreateUser(CreateApplicationUserRequest request, CancellationToken cancellationToken = default)
        {
            if (request?.Email is null)
            {
                return(BadRequest(CreateValidationProblem(nameof(request.Email), "Email is missing")));
            }
            if (!Validation.EmailValidator.IsEmail(request.Email))
            {
                return(BadRequest(CreateValidationProblem(nameof(request.Email), "Invalid email")));
            }
            if (request?.Password is null)
            {
                return(BadRequest(CreateValidationProblem(nameof(request.Password), "Password is missing")));
            }
            var anyAdmin = (await _userManager.GetUsersInRoleAsync(Roles.ServerAdmin)).Any();
            var policies = await _settingsRepository.GetSettingAsync <PoliciesSettings>() ?? new PoliciesSettings();

            var isAuth = User.Identity.AuthenticationType == APIKeyConstants.AuthenticationType;

            // If registration are locked and that an admin exists, don't accept unauthenticated connection
            if (anyAdmin && policies.LockSubscription && !isAuth)
            {
                return(Unauthorized());
            }

            // Even if subscription are unlocked, it is forbidden to create admin unauthenticated
            if (anyAdmin && request.IsAdministrator is true && !isAuth)
            {
                return(Forbid(AuthenticationSchemes.Greenfield));
            }
            // You are de-facto admin if there is no other admin, else you need to be auth and pass policy requirements
            bool isAdmin = anyAdmin ? (await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.CanModifyServerSettings))).Succeeded &&
                           (await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.Unrestricted))).Succeeded &&
                           isAuth
                                    : true;

            // You need to be admin to create an admin
            if (request.IsAdministrator is true && !isAdmin)
            {
                return(Forbid(AuthenticationSchemes.Greenfield));
            }

            if (!isAdmin && policies.LockSubscription)
            {
                // If we are not admin and subscriptions are locked, we need to check the Policies.CanCreateUser.Key permission
                var canCreateUser = (await _authorizationService.AuthorizeAsync(User, null, new PolicyRequirement(Policies.CanCreateUser))).Succeeded;
                if (!isAuth || !canCreateUser)
                {
                    return(Forbid(AuthenticationSchemes.Greenfield));
                }
            }

            var user = new ApplicationUser
            {
                UserName = request.Email,
                Email    = request.Email,
                RequiresEmailConfirmation = policies.RequiresConfirmedEmail
            };
            var passwordValidation = await this._passwordValidator.ValidateAsync(_userManager, user, request.Password);

            if (!passwordValidation.Succeeded)
            {
                foreach (var error in passwordValidation.Errors)
                {
                    ModelState.AddModelError(nameof(request.Password), error.Description);
                }
                return(BadRequest(new ValidationProblemDetails(ModelState)));
            }
            if (!isAdmin)
            {
                if (!await _throttleService.Throttle(ZoneLimits.Register, this.HttpContext.Connection.RemoteIpAddress, cancellationToken))
                {
                    return(new TooManyRequestsResult(ZoneLimits.Register));
                }
            }
            var identityResult = await _userManager.CreateAsync(user, request.Password);

            if (!identityResult.Succeeded)
            {
                foreach (var error in identityResult.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
                return(BadRequest(new ValidationProblemDetails(ModelState)));
            }

            if (request.IsAdministrator is true)
            {
                if (!anyAdmin)
                {
                    await _roleManager.CreateAsync(new IdentityRole(Roles.ServerAdmin));
                }
                await _userManager.AddToRoleAsync(user, Roles.ServerAdmin);

                if (!anyAdmin)
                {
                    if (_options.DisableRegistration)
                    {
                        // automatically lock subscriptions now that we have our first admin
                        Logs.PayServer.LogInformation("First admin created, disabling subscription (disable-registration is set to true)");
                        policies.LockSubscription = true;
                        await _settingsRepository.UpdateSetting(policies);
                    }
                }
            }
            _eventAggregator.Publish(new UserRegisteredEvent()
            {
                Request = Request, User = user, Admin = request.IsAdministrator is true
            });
Example #19
0
        private async Task <bool> CheckPrivileges()
        {
            var authorizationResult = await _authorizationService.AuthorizeAsync(_identityService.GetUser(), Policies.PostOpClosedPolicy);

            return(authorizationResult.Succeeded);
        }
Example #20
0
        public async Task <IActionResult> Render()
        {
            if (!await _authorizationService.AuthorizeAsync(User, CommonPermissions.PreviewContent))
            {
                return(this.ChallengeOrForbid());
            }

            // Mark request as a `Preview` request so that drivers / handlers or underlying services can be aware of an active preview mode.
            HttpContext.Features.Set(new ContentPreviewFeature());

            var contentItemType = Request.Form["ContentItemType"];
            var contentItem     = await _contentManager.NewAsync(contentItemType);

            // Assign the ids from the currently edited item so that validation thinks
            // it's working on the same item. For instance if drivers are checking name unicity
            // they need to think this is the same existing item (AutoroutePart).

            var contentItemId        = Request.Form["PreviewContentItemId"];
            var contentItemVersionId = Request.Form["PreviewContentItemVersionId"];

            // Unique contentItem.Id that only Preview is using such that another
            // stored document can't have the same one in the IContentManagerSession index

            contentItem.Id                   = -1;
            contentItem.ContentItemId        = contentItemId;
            contentItem.ContentItemVersionId = contentItemVersionId;
            contentItem.CreatedUtc           = _clock.UtcNow;
            contentItem.ModifiedUtc          = _clock.UtcNow;
            contentItem.PublishedUtc         = _clock.UtcNow;
            contentItem.Published            = true;

            // TODO: we should probably get this value from the main editor as it might impact validators
            var model = await _contentItemDisplayManager.UpdateEditorAsync(contentItem, _updateModelAccessor.ModelUpdater, true);

            if (!ModelState.IsValid)
            {
                var errors = new List <string>();
                foreach (var modelState in ValidationHelpers.GetModelStateList(ViewData, false))
                {
                    for (var i = 0; i < modelState.Errors.Count; i++)
                    {
                        var modelError = modelState.Errors[i];
                        var errorText  = ValidationHelpers.GetModelErrorMessageOrDefault(modelError);
                        errors.Add(errorText);
                    }
                }

                return(StatusCode(500, new { errors = errors }));
            }

            var previewAspect = await _contentManager.PopulateAspectAsync(contentItem, new PreviewAspect());

            if (!String.IsNullOrEmpty(previewAspect.PreviewUrl))
            {
                // The PreviewPart is configured, we need to set the fake content item
                _contentManagerSession.Store(contentItem);

                if (!previewAspect.PreviewUrl.StartsWith('/'))
                {
                    previewAspect.PreviewUrl = "/" + previewAspect.PreviewUrl;
                }

                Request.HttpContext.Items["PreviewPath"] = previewAspect.PreviewUrl;

                return(Ok());
            }

            model = await _contentItemDisplayManager.BuildDisplayAsync(contentItem, _updateModelAccessor.ModelUpdater, "Detail");

            return(View(model));
        }
Example #21
0
        public async Task <IActionResult> VaultBridgeConnection(string cryptoCode = null,
                                                                [ModelBinder(typeof(WalletIdModelBinder))]
                                                                WalletId walletId = null)
        {
            if (!HttpContext.WebSockets.IsWebSocketRequest)
            {
                return(NotFound());
            }
            cryptoCode = cryptoCode ?? walletId.CryptoCode;
            bool versionChecked = false;

            using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(10)))
            {
                var cancellationToken = cts.Token;
                var network           = Networks.GetNetwork <BTCPayNetwork>(cryptoCode);
                if (network == null)
                {
                    return(NotFound());
                }
                var websocket = await HttpContext.WebSockets.AcceptWebSocketAsync();

                var hwi = new Hwi.HwiClient(network.NBitcoinNetwork)
                {
                    Transport = new HwiWebSocketTransport(websocket)
                };
                Hwi.HwiDeviceClient device      = null;
                HwiEnumerateEntry   deviceEntry = null;
                HDFingerprint?      fingerprint = null;
                string password        = null;
                var    websocketHelper = new WebSocketHelper(websocket);

                async Task <bool> RequireDeviceUnlocking()
                {
                    if (deviceEntry == null)
                    {
                        await websocketHelper.Send("{ \"error\": \"need-device\"}", cancellationToken);

                        return(true);
                    }
                    if (deviceEntry.Code is HwiErrorCode.DeviceNotInitialized)
                    {
                        await websocketHelper.Send("{ \"error\": \"need-initialized\"}", cancellationToken);

                        return(true);
                    }
                    if (deviceEntry.Code is HwiErrorCode.DeviceNotReady)
                    {
                        if (IsTrezorT(deviceEntry))
                        {
                            await websocketHelper.Send("{ \"error\": \"need-passphrase-on-device\"}", cancellationToken);

                            return(true);
                        }
                        else if (deviceEntry.NeedsPinSent is true)
                        {
                            await websocketHelper.Send("{ \"error\": \"need-pin\"}", cancellationToken);

                            return(true);
                        }
                        else if (deviceEntry.NeedsPassphraseSent is true && password is null)
                        {
                            await websocketHelper.Send("{ \"error\": \"need-passphrase\"}", cancellationToken);

                            return(true);
                        }
                    }
                    return(false);
                }

                JObject o = null;
                try
                {
                    while (true)
                    {
                        var command = await websocketHelper.NextMessageAsync(cancellationToken);

                        switch (command)
                        {
                        case "set-passphrase":
                            device.Password = await websocketHelper.NextMessageAsync(cancellationToken);

                            password = device.Password;
                            break;

                        case "ask-sign":
                            if (await RequireDeviceUnlocking())
                            {
                                continue;
                            }
                            if (walletId == null)
                            {
                                await websocketHelper.Send("{ \"error\": \"invalid-walletId\"}", cancellationToken);

                                continue;
                            }
                            if (fingerprint is null)
                            {
                                fingerprint = (await device.GetXPubAsync(new KeyPath("44'"), cancellationToken)).ExtPubKey.ParentFingerprint;
                            }
                            await websocketHelper.Send("{ \"info\": \"ready\"}", cancellationToken);

                            o = JObject.Parse(await websocketHelper.NextMessageAsync(cancellationToken));
                            var authorization = await _authorizationService.AuthorizeAsync(User, Policies.CanModifyStoreSettings);

                            if (!authorization.Succeeded)
                            {
                                await websocketHelper.Send("{ \"error\": \"not-authorized\"}", cancellationToken);

                                continue;
                            }
                            var psbt = PSBT.Parse(o["psbt"].Value <string>(), network.NBitcoinNetwork);
                            var derivationSettings = GetDerivationSchemeSettings(walletId);
                            derivationSettings.RebaseKeyPaths(psbt);
                            var signing = derivationSettings.GetSigningAccountKeySettings();
                            if (signing.GetRootedKeyPath()?.MasterFingerprint != fingerprint)
                            {
                                await websocketHelper.Send("{ \"error\": \"wrong-wallet\"}", cancellationToken);

                                continue;
                            }
                            var signableInputs = psbt.Inputs
                                                 .SelectMany(i => i.HDKeyPaths)
                                                 .Where(i => i.Value.MasterFingerprint == fingerprint)
                                                 .ToArray();
                            if (signableInputs.Length > 0)
                            {
                                var actualPubKey = (await device.GetXPubAsync(signableInputs[0].Value.KeyPath)).GetPublicKey();
                                if (actualPubKey != signableInputs[0].Key)
                                {
                                    await websocketHelper.Send("{ \"error\": \"wrong-keypath\"}", cancellationToken);

                                    continue;
                                }
                            }
                            try
                            {
                                psbt = await device.SignPSBTAsync(psbt, cancellationToken);
                            }
                            catch (Hwi.HwiException)
                            {
                                await websocketHelper.Send("{ \"error\": \"user-reject\"}", cancellationToken);

                                continue;
                            }
                            o = new JObject();
                            o.Add("psbt", psbt.ToBase64());
                            await websocketHelper.Send(o.ToString(), cancellationToken);

                            break;

                        case "display-address":
                            if (await RequireDeviceUnlocking())
                            {
                                continue;
                            }
                            var k = RootedKeyPath.Parse(await websocketHelper.NextMessageAsync(cancellationToken));
                            await device.DisplayAddressAsync(GetScriptPubKeyType(k), k.KeyPath, cancellationToken);

                            await websocketHelper.Send("{ \"info\": \"ok\"}", cancellationToken);

                            break;

                        case "ask-pin":
                            if (device == null)
                            {
                                await websocketHelper.Send("{ \"error\": \"need-device\"}", cancellationToken);

                                continue;
                            }
                            try
                            {
                                await device.PromptPinAsync(cancellationToken);
                            }
                            catch (HwiException ex) when(ex.ErrorCode == HwiErrorCode.DeviceAlreadyUnlocked)
                            {
                                await websocketHelper.Send("{ \"error\": \"device-already-unlocked\"}", cancellationToken);

                                continue;
                            }
                            await websocketHelper.Send("{ \"info\": \"prompted, please input the pin\"}", cancellationToken);

                            var pin = int.Parse(await websocketHelper.NextMessageAsync(cancellationToken), CultureInfo.InvariantCulture);
                            if (await device.SendPinAsync(pin, cancellationToken))
                            {
                                goto askdevice;
                            }
                            else
                            {
                                await websocketHelper.Send("{ \"error\": \"incorrect-pin\"}", cancellationToken);

                                continue;
                            }

                        case "ask-xpub":
                            if (await RequireDeviceUnlocking())
                            {
                                continue;
                            }
                            await websocketHelper.Send("{ \"info\": \"ok\"}", cancellationToken);

                            var     askedXpub     = JObject.Parse(await websocketHelper.NextMessageAsync(cancellationToken));
                            var     addressType   = askedXpub["addressType"].Value <string>();
                            var     accountNumber = askedXpub["accountNumber"].Value <int>();
                            JObject result        = new JObject();
                            var     factory       = network.NBXplorerNetwork.DerivationStrategyFactory;
                            if (fingerprint is null)
                            {
                                fingerprint = (await device.GetXPubAsync(new KeyPath("44'"), cancellationToken)).ExtPubKey.ParentFingerprint;
                            }
                            result["fingerprint"] = fingerprint.Value.ToString();

                            DerivationStrategyBase strategy = null;
                            KeyPath          keyPath        = null;
                            BitcoinExtPubKey xpub           = null;

                            if (!network.NBitcoinNetwork.Consensus.SupportSegwit && addressType != "legacy")
                            {
                                await websocketHelper.Send("{ \"error\": \"segwit-notsupported\"}", cancellationToken);

                                continue;
                            }

                            if (!network.NBitcoinNetwork.Consensus.SupportTaproot && addressType == "taproot")
                            {
                                await websocketHelper.Send("{ \"error\": \"taproot-notsupported\"}", cancellationToken);

                                continue;
                            }
                            if (addressType == "taproot")
                            {
                                keyPath = new KeyPath("86'").Derive(network.CoinType).Derive(accountNumber, true);
                                xpub    = await device.GetXPubAsync(keyPath);

                                strategy = factory.CreateDirectDerivationStrategy(xpub, new DerivationStrategyOptions()
                                {
                                    ScriptPubKeyType = ScriptPubKeyType.TaprootBIP86
                                });
                            }
                            else if (addressType == "segwit")
                            {
                                keyPath = new KeyPath("84'").Derive(network.CoinType).Derive(accountNumber, true);
                                xpub    = await device.GetXPubAsync(keyPath);

                                strategy = factory.CreateDirectDerivationStrategy(xpub, new DerivationStrategyOptions()
                                {
                                    ScriptPubKeyType = ScriptPubKeyType.Segwit
                                });
                            }
                            else if (addressType == "segwitWrapped")
                            {
                                keyPath = new KeyPath("49'").Derive(network.CoinType).Derive(accountNumber, true);
                                xpub    = await device.GetXPubAsync(keyPath);

                                strategy = factory.CreateDirectDerivationStrategy(xpub, new DerivationStrategyOptions()
                                {
                                    ScriptPubKeyType = ScriptPubKeyType.SegwitP2SH
                                });
                            }
                            else if (addressType == "legacy")
                            {
                                keyPath = new KeyPath("44'").Derive(network.CoinType).Derive(accountNumber, true);
                                xpub    = await device.GetXPubAsync(keyPath);

                                strategy = factory.CreateDirectDerivationStrategy(xpub, new DerivationStrategyOptions()
                                {
                                    ScriptPubKeyType = ScriptPubKeyType.Legacy
                                });
                            }
                            else
                            {
                                await websocketHelper.Send("{ \"error\": \"invalid-addresstype\"}", cancellationToken);

                                continue;
                            }
                            result.Add(new JProperty("strategy", strategy.ToString()));
                            result.Add(new JProperty("accountKey", xpub.ToString()));
                            result.Add(new JProperty("keyPath", keyPath.ToString()));
                            await websocketHelper.Send(result.ToString(), cancellationToken);

                            break;

                        case "ask-passphrase":
                            if (command == "ask-passphrase")
                            {
                                if (deviceEntry == null)
                                {
                                    await websocketHelper.Send("{ \"error\": \"need-device\"}", cancellationToken);

                                    continue;
                                }
                                // The make the trezor T ask for password
                                await device.GetXPubAsync(new KeyPath("44'"), cancellationToken);
                            }
                            goto askdevice;

                        case "ask-device":
askdevice:
                            if (!versionChecked)
                            {
                                var version = await hwi.GetVersionAsync(cancellationToken);

                                if (version.Major < 2)
                                {
                                    await websocketHelper.Send("{ \"error\": \"vault-outdated\"}", cancellationToken);

                                    continue;
                                }
                                versionChecked = true;
                            }
                            password    = null;
                            deviceEntry = null;
                            device      = null;
                            var entries = (await hwi.EnumerateEntriesAsync(cancellationToken)).ToList();
                            deviceEntry = entries.FirstOrDefault();
                            if (deviceEntry == null)
                            {
                                await websocketHelper.Send("{ \"error\": \"no-device\"}", cancellationToken);

                                continue;
                            }
                            device      = new HwiDeviceClient(hwi, deviceEntry.DeviceSelector, deviceEntry.Model, deviceEntry.Fingerprint);
                            fingerprint = device.Fingerprint;
                            JObject json = new JObject();
                            json.Add("model", device.Model);
                            json.Add("fingerprint", device.Fingerprint?.ToString());
                            await websocketHelper.Send(json.ToString(), cancellationToken);

                            break;
                        }
                    }
                }
                catch (FormatException ex)
                {
                    JObject obj = new JObject();
                    obj.Add("error", "invalid-network");
                    obj.Add("details", ex.ToString());
                    try
                    {
                        await websocketHelper.Send(obj.ToString(), cancellationToken);
                    }
                    catch { }
                }
                catch (Exception ex)
                {
                    JObject obj = new JObject();
                    obj.Add("error", "unknown-error");
                    obj.Add("message", ex.Message);
                    obj.Add("details", ex.ToString());
                    try
                    {
                        await websocketHelper.Send(obj.ToString(), cancellationToken);
                    }
                    catch { }
                }
                finally
                {
                    await websocketHelper.DisposeAsync(cancellationToken);
                }
            }
            return(new EmptyResult());
        }
Example #22
0
        // -----------------
        // Index
        // Displays a summary from StopForumSpam.
        // -----------------

        public async Task <IActionResult> Index(EntityOptions opts)
        {
            if (opts == null)
            {
                opts = new EntityOptions();
            }

            // We always need an entity Id
            if (opts.Id <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(opts.Id));
            }

            // We always need an entity
            var entity = await _entityStore.GetByIdAsync(opts.Id);

            if (entity == null)
            {
                return(NotFound());
            }

            // Ensure we have permission
            if (!await _authorizationService.AuthorizeAsync(User, entity.CategoryId, Permissions.ViewStopForumSpam))
            {
                return(Unauthorized());
            }

            // Get reply
            IEntityReply reply = null;

            if (opts.ReplyId > 0)
            {
                reply = await _entityReplyStore.GetByIdAsync(opts.ReplyId);

                if (reply == null)
                {
                    return(NotFound());
                }
            }

            // Get user to validate
            var user = reply != null
                ? await GetUserToValidateAsync(reply)
                : await GetUserToValidateAsync(entity);

            // Ensure we found the user
            if (user == null)
            {
                return(NotFound());
            }

            // Build view model
            var viewModel = new StopForumSpamViewModel()
            {
                Options = opts,
                Checker = await _spamChecker.CheckAsync(user)
            };

            // Return view
            return(View(viewModel));
        }
        public async Task <bool> IsAuthorized(ClaimsPrincipal user, string policyName)
        {
            var result = await _authorizationService.AuthorizeAsync(user, policyName);

            return(result.Succeeded);
        }
 public static async Task <bool> IsGrantedAsync(this IAuthorizationService authorizationService, AuthorizationPolicy policy)
 {
     return((await authorizationService.AuthorizeAsync(policy)).Succeeded);
 }
Example #25
0
        public async Task <IActionResult> ReviewEquipement(int id, int?roundSquadID)
        {
            var user = await GetUser();

            if (user == null)
            {
                return(Forbid());
            }

            var match = await _context.Matchs
                        .Include(m => m.Sides)
                        .Include(m => m.MatchTechnicalInfos)
                        .Include(m => m.Users).ThenInclude(u => u.User)
                        .Include(m => m.Rounds).ThenInclude(r => r.Sides).ThenInclude(s => s.Squads).ThenInclude(s => s.Slots).ThenInclude(s => s.AssignedUser).ThenInclude(u => u.User)
                        .Include(m => m.Rounds).ThenInclude(r => r.Sides).ThenInclude(s => s.Faction)
                        .FirstOrDefaultAsync(m => m.MatchID == id);

            if (match == null)
            {
                return(NotFound());
            }

            var matchUser = match.Users.FirstOrDefault(u => u.UserID == user.UserID);

            if (matchUser == null)
            {
                return(Forbid());
            }

            var squads = match.Rounds.SelectMany(r => r.Sides).SelectMany(s => s.Squads);

            RoundSquad squad;

            if (roundSquadID == null)
            {
                squad = squads.First(s => s.Slots.Any(s => s.AssignedUser == matchUser && s.Role >= Role.SquadLeader));
                if (squad == null)
                {
                    return(Forbid());
                }
            }
            else
            {
                if (!(await _auth.AuthorizeAsync(User, "Admin")).Succeeded)
                {
                    return(Forbid());
                }
                squad = match.Rounds.SelectMany(r => r.Sides).SelectMany(s => s.Squads).FirstOrDefault(s => s.RoundSquadID == roundSquadID);
                if (squad == null)
                {
                    return(NotFound());
                }
            }

            var backup = _persist.GetBackups().FirstOrDefault();

            var vm = new ReviewEquipementViewModel();

            vm.Match  = match;
            vm.Squad  = squad;
            vm.Backup = backup;
            await LoadTacMap(vm.Match);

            return(View(vm));
        }
 public static async Task <bool> IsGrantedAsync(this IAuthorizationService authorizationService, object resource, string policyName)
 {
     return((await authorizationService.AuthorizeAsync(resource, policyName)).Succeeded);
 }
Example #27
0
        public virtual async Task <IActionResult> RequesterInfo(int id)
        {
            var request    = _requestService.GetRequest(id);
            var authResult = await _authService.AuthorizeAsync(User, request, "CanEditRequest");

            if (!authResult.Succeeded)
            {
                return(new ForbidResult());
            }

            ViewData["request"] = request;
            return(View(request.RequestedFor));
        }
Example #28
0
        public async Task <IActionResult> Post()
        {
            // Ensure we have permission
            if (!await _authorizationService.AuthorizeAsync(User, Permissions.AddFiles))
            {
                return(Unauthorized());
            }

            // Get authenticated user
            var user = await base.GetAuthenticatedUserAsync();

            // We need to be authenticated
            if (user == null)
            {
                return(base.UnauthorizedException());
            }

            // Get current feature
            var feature = await _featureFacade.GetFeatureByIdAsync(ModuleId);

            // Ensure the feature exists
            if (feature == null)
            {
                throw new Exception($"A feature named \"{ModuleId}\" could not be found!");
            }

            // Validate & process multi-part request
            // -------------------

            var result = await _multiPartRequestHandler.ProcessAsync(Request);

            // Return any errors parsing the multi-part request
            if (!result.Succeeded)
            {
                foreach (var error in result.Errors)
                {
                    return(BadRequest(error));
                }
            }

            // Build file
            // -------------------

            var md5     = result.Response.ContentBytes?.ToMD5().ToHex() ?? string.Empty;
            var newFile = new File
            {
                FeatureId       = feature.Id,
                Name            = result.Response.Name,
                Extension       = result.Response.Extension,
                ContentType     = result.Response.ContentType,
                ContentLength   = result.Response.ContentLength,
                ContentBlob     = result.Response.ContentBytes,
                ContentCheckSum = md5,
                CreatedUserId   = user.Id,
                CreatedDate     = DateTimeOffset.Now
            };

            // Validate file
            // -------------------

            var output = new List <UploadResult>();

            var validationResult = await _fileValidator.ValidateAsync(newFile);

            if (validationResult.Succeeded)
            {
                // Create file
                var fileResult = await _fileManager.CreateAsync(newFile);

                // Build friendly results
                if (fileResult.Succeeded)
                {
                    output.Add(new UploadResult()
                    {
                        Id            = fileResult.Response.Id,
                        Name          = fileResult.Response.Name,
                        ContentType   = fileResult.Response.ContentType,
                        ContentLength = fileResult.Response.ContentLength,
                        FriendlySize  = fileResult.Response.ContentLength.ToFriendlyFileSize()
                    });
                }
                else
                {
                    foreach (var error in fileResult.Errors)
                    {
                        output.Add(new UploadResult()
                        {
                            Name  = result.Response.Name,
                            Error = error.Description
                        });
                    }
                }
            }
            else
            {
                foreach (var error in validationResult.Errors)
                {
                    output.Add(new UploadResult()
                    {
                        Name  = result.Response.Name,
                        Error = error.Description
                    });
                }
            }

            return(base.Result(output));
        }
Example #29
0
        public async Task <IActionResult> Index()
        {
            bool isAllowed = await authorizationService.AuthorizeAsync(User, "SetupSystemPolicy");

            if (!setupOptions.AllowAnonymous && !isAllowed)
            {
                log.LogInformation("returning 404 because allowAnonymous is false and user is either not authenticated or not allowed by policy");
                Response.StatusCode = 404;
                return(new EmptyResult());
            }


            //scriptTimeout = Server.ScriptTimeout;
            //Response.Cache.SetCacheability(HttpCacheability.ServerAndNoCache);
            //Response.BufferOutput = true;
            // Server.ScriptTimeout = int.MaxValue;

            startTime = DateTime.UtcNow;

            await WritePageHeader(HttpContext.Response);

            if (!setupOptions.AllowAnonymous && isAllowed)
            {
                await WritePageContent(Response,
                                       "RunningSetupForAllowedUser" //SetupResources.RunningSetupForAdminUser
                                       );
            }

            // SetupManager and ISetupTasks will use this function to write to the response
            Func <string, bool, Task> outputWriter = async(string message, bool showTime) =>
            {
                await WritePageContent(Response, message, showTime);
            };

            // this locking strategy did not work as expected perhaps because we are doing things async
            //int lockTimeoutMilliseconds = config.GetOrDefault("AppSetings:SetupLockTimeoutMilliseconds", 60000); // 1 minute

            //if(!Monitor.TryEnter(Lock, lockTimeoutMilliseconds))
            //{
            //    //throw new Exception("setup is already locked and runnning")

            //    await WritePageContent(Response,
            //            "SetupAlreadyInProgress" //SetupResources.SetupAlreadyInProgress
            //            );
            //}
            //else
            //{
            bool keepGoing;

            try
            {
                await setupManager.ProbeSystem(outputWriter);

                // the setup system must be bootstrapped first
                // to make sure mp_SchemaVersion table exists
                // which is used to keep track of script versions that have already been run
                bool needSetupUpdate = setupManager.NeedsUpgrade("cloudscribe-setup");
                if (needSetupUpdate)
                {
                    keepGoing = await setupManager.SetupCloudscribeSetup(outputWriter);
                }
                else
                {
                    keepGoing = true;
                }


                if (keepGoing)
                {
                    // this runs the scripts for other apps including cloudscribe-core,
                    // cloudscribe-logging, and any custom apps that use the setup system
                    keepGoing = await setupManager.SetupOtherApplications(outputWriter);
                }

                if (setupSteps != null)
                {
                    foreach (ISetupTask step in setupSteps)
                    {
                        try
                        {
                            await step.DoSetupStep(
                                outputWriter,
                                setupManager.NeedsUpgrade,
                                setupManager.GetSchemaVersion,
                                setupManager.GetCodeVersion
                                );
                        }
                        catch (Exception ex)
                        {
                            await WriteException(Response, ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                await WriteException(Response, ex);
            }
            finally
            {
                //ClearSetupLock();
                //Monitor.Exit(Lock);
            }

            if (setupOptions.ShowSchemaListOnSetupPage)
            {
                await WriteInstalledSchemaSummary(Response);
            }



            await WritePageFooter(Response);

            return(new EmptyResult());
        }
Example #30
0
        public async Task <IActionResult> Search(SearchIndexViewModel viewModel, PagerSlimParameters pagerParameters)
        {
            var permissionsProvider = _permissionProviders.FirstOrDefault(x => x.GetType().FullName == "OrchardCore.Lucene.Permissions");
            var permissions         = await permissionsProvider.GetPermissionsAsync();

            var siteSettings = await _siteService.GetSiteSettingsAsync();

            var searchSettings = siteSettings.As <LuceneSettings>();

            if (permissions.FirstOrDefault(x => x.Name == "QueryLucene" + searchSettings.SearchIndex + "Index") != null)
            {
                if (!await _authorizationService.AuthorizeAsync(User, permissions.FirstOrDefault(x => x.Name == "QueryLucene" + searchSettings.SearchIndex + "Index")))
                {
                    return(this.ChallengeOrForbid());
                }
            }
            else
            {
                _logger.LogInformation("Couldn't execute search. The search index doesn't exist.");
                return(BadRequest("Search is not configured."));
            }

            if (searchSettings.SearchIndex != null && !_luceneIndexProvider.Exists(searchSettings.SearchIndex))
            {
                _logger.LogInformation("Couldn't execute search. The search index doesn't exist.");
                return(BadRequest("Search is not configured."));
            }

            var luceneSettings = await _luceneIndexingService.GetLuceneSettingsAsync();

            if (luceneSettings == null || luceneSettings?.DefaultSearchFields == null)
            {
                _logger.LogInformation("Couldn't execute search. No Lucene settings was defined.");
                return(BadRequest("Search is not configured."));
            }

            var luceneIndexSettings = await _luceneIndexSettingsService.GetSettingsAsync(searchSettings.SearchIndex);

            if (luceneIndexSettings == null)
            {
                _logger.LogInformation($"Couldn't execute search. No Lucene index settings was defined for ({searchSettings.SearchIndex}) index.");
                return(BadRequest($"Search index ({searchSettings.SearchIndex}) is not configured."));
            }

            if (string.IsNullOrWhiteSpace(viewModel.Terms))
            {
                return(View(new SearchIndexViewModel
                {
                    SearchForm = new SearchFormViewModel("Search__Form")
                    {
                    },
                }));
            }

            var pager = new PagerSlim(pagerParameters, siteSettings.PageSize);

            // We Query Lucene index
            var analyzer    = _luceneAnalyzerManager.CreateAnalyzer(await _luceneIndexSettingsService.GetIndexAnalyzerAsync(luceneIndexSettings.IndexName));
            var queryParser = new MultiFieldQueryParser(LuceneSettings.DefaultVersion, luceneSettings.DefaultSearchFields, analyzer);
            var query       = queryParser.Parse(QueryParser.Escape(viewModel.Terms));

            // Fetch one more result than PageSize to generate "More" links
            var start = 0;
            var end   = pager.PageSize + 1;

            if (pagerParameters.Before != null)
            {
                start = Convert.ToInt32(pagerParameters.Before) - pager.PageSize - 1;
                end   = Convert.ToInt32(pagerParameters.Before);
            }
            else if (pagerParameters.After != null)
            {
                start = Convert.ToInt32(pagerParameters.After);
                end   = Convert.ToInt32(pagerParameters.After) + pager.PageSize + 1;
            }

            var contentItemIds = (await _searchQueryService.ExecuteQueryAsync(query, searchSettings.SearchIndex, start, end))
                                 .ToList();

            // We Query database to retrieve content items.
            IQuery <ContentItem> queryDb;

            if (luceneIndexSettings.IndexLatest)
            {
                queryDb = _session.Query <ContentItem, ContentItemIndex>()
                          .Where(x => x.ContentItemId.IsIn(contentItemIds) && x.Latest == true)
                          .Take(pager.PageSize + 1);
            }
            else
            {
                queryDb = _session.Query <ContentItem, ContentItemIndex>()
                          .Where(x => x.ContentItemId.IsIn(contentItemIds) && x.Published == true)
                          .Take(pager.PageSize + 1);
            }

            // Sort the content items by their rank in the search results returned by Lucene.
            var containedItems = (await queryDb.ListAsync()).OrderBy(x => contentItemIds.IndexOf(x.ContentItemId));

            // We set the PagerSlim before and after links
            if (pagerParameters.After != null || pagerParameters.Before != null)
            {
                if (start + 1 > 1)
                {
                    pager.Before = (start + 1).ToString();
                }
                else
                {
                    pager.Before = null;
                }
            }

            if (containedItems.Count() == pager.PageSize + 1)
            {
                pager.After = (end - 1).ToString();
            }
            else
            {
                pager.After = null;
            }

            var model = new SearchIndexViewModel
            {
                Terms      = viewModel.Terms,
                SearchForm = new SearchFormViewModel("Search__Form")
                {
                    Terms = viewModel.Terms
                },
                SearchResults = new SearchResultsViewModel("Search__Results")
                {
                    ContentItems = containedItems.Take(pager.PageSize)
                },
                Pager = (await New.PagerSlim(pager)).UrlParams(new Dictionary <string, string>()
                {
                    { "Terms", viewModel.Terms }
                })
            };

            return(View(model));
        }
Example #31
0
        async Task <IEnumerable <IUser> > ReduceUsersAsync(IEnumerable <Follows.Models.Follow> follows, TEntity entity)
        {
            // We always need follows to process
            if (follows == null)
            {
                return(null);
            }

            // Get all users from the label follows
            var users = await _platoUserStore.QueryAsync()
                        .Select <UserQueryParams>(q =>
            {
                q.Id.IsIn(follows
                          .Select(f => f.CreatedUserId)
                          .ToArray());
            })
                        .ToList();

            // No users to further process
            if (users?.Data == null)
            {
                return(null);
            }

            // Build users reducing for permissions
            var result = new Dictionary <int, IUser>();

            foreach (var user in users.Data)
            {
                // Ensure the user is only ever added once
                if (!result.ContainsKey(user.Id))
                {
                    result.Add(user.Id, user);
                }

                // If the entity is hidden but the user does
                // not have permission to view hidden entities
                if (entity.IsHidden)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Docs.Permissions.ViewHiddenDocs))
                    {
                        result.Remove(user.Id);
                    }
                }

                // If we are not the entity author and the entity is private
                // ensure we have permission to view private entities
                if (user.Id != entity.CreatedUserId && entity.IsPrivate)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Docs.Permissions.ViewPrivateDocs))
                    {
                        result.Remove(user.Id);
                    }
                }

                // The entity has been flagged as SPAM but the user does
                // not have permission to view entities flagged as SPAM
                if (entity.IsSpam)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Docs.Permissions.ViewSpamDocs))
                    {
                        result.Remove(user.Id);
                    }
                }

                // The entity is soft deleted but the user does
                // not have permission to view soft deleted entities
                if (entity.IsDeleted)
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);

                    if (!await _authorizationService.AuthorizeAsync(principal,
                                                                    entity.CategoryId, Docs.Permissions.ViewDeletedDocs))
                    {
                        result.Remove(user.Id);
                    }
                }
            }

            return(result.Count > 0 ? result.Values : null);
        }
        public async Task <IActionResult> GetRequestsAsync(
            [FromQuery] PagingOptions pagingOptions,
            [FromQuery] SortOptions <Request, RequestEntity> sortOptions,
            [FromQuery] SearchOptions <Request, RequestEntity> searchOptions,
            CancellationToken ct)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new ApiError(ModelState)));
            }

            pagingOptions.Offset = pagingOptions.Offset ?? _defaultPagingOptions.Offset;
            pagingOptions.Limit  = pagingOptions.Limit ?? _defaultPagingOptions.Limit;

            //  var collectionLink = Link.ToCollection(nameof(GetRequestsAsync));

            // Logic if user is Sales then only return theirs, else return all for Admin and Sign Shop
            if (User.Identity.IsAuthenticated)
            {
                var canSeeAll = await _authzService.AuthorizeAsync(
                    User, "ViewAllRequestsPolicy");

                if (canSeeAll.Succeeded) // User is Administrator or Sign Shop
                {
                    var requests = await _requestService.GetRequestsAsync(
                        pagingOptions,
                        sortOptions,
                        searchOptions,
                        ct);

                    var collection = PagedCollection <Request> .Create <RequestResponse>(
                        Link.ToCollection(nameof(GetRequestsAsync)),
                        requests.Items.ToArray(),
                        requests.TotalSize,
                        pagingOptions);

                    collection.RequestsQuery = FormMetadata.FromResource <Request>(
                        Link.ToForm(
                            nameof(GetRequestsAsync),
                            null,
                            Link.GetMethod,
                            Form.QueryRelation));

                    return(Ok(collection));
                }
                else // User is Sales (Could technically be any other authenticated user)
                {
                    // Build collection only with requests for the User
                    var currentUserId = await _userService.GetUserIdAsync(User);

                    var requests = await _requestService.GetUserRequestsAsync(
                        currentUserId,
                        pagingOptions,
                        sortOptions,
                        searchOptions,
                        ct);

                    var collection = PagedCollection <Request> .Create <RequestResponse>(
                        Link.ToCollection(nameof(GetRequestsAsync)),
                        requests.Items.ToArray(),
                        requests.TotalSize,
                        pagingOptions);

                    collection.RequestsQuery = FormMetadata.FromResource <Request>(
                        Link.ToForm(
                            nameof(GetRequestsAsync),
                            null,
                            Link.GetMethod,
                            Form.QueryRelation));

                    return(Ok(collection));
                }
            }

            // User is not authenticated.
            return(NotFound());
        }
Example #33
0
        public async Task <ActionResult> ListPOST(ContentOptionsViewModel options, IEnumerable <int> itemIds)
        {
            if (itemIds?.Count() > 0)
            {
                // Load items so that loading handlers are invoked.
                var checkedContentItems = await _session.Query <ContentItem, ContentItemIndex>().Where(x => x.DocumentId.IsIn(itemIds) && x.Latest).ListAsync(_contentManager);

                switch (options.BulkAction)
                {
                case ContentsBulkAction.None:
                    break;

                case ContentsBulkAction.PublishNow:
                    foreach (var item in checkedContentItems)
                    {
                        if (!await _authorizationService.AuthorizeAsync(User, CommonPermissions.PublishContent, item))
                        {
                            await _notifier.WarningAsync(H["Couldn't publish selected content."]);

                            await _session.CancelAsync();

                            return(Forbid());
                        }

                        await _contentManager.PublishAsync(item);
                    }
                    await _notifier.SuccessAsync(H["Content published successfully."]);

                    break;

                case ContentsBulkAction.Unpublish:
                    foreach (var item in checkedContentItems)
                    {
                        if (!await IsAuthorizedAsync(CommonPermissions.PublishContent, item))
                        {
                            await _notifier.WarningAsync(H["Couldn't unpublish selected content."]);

                            await _session.CancelAsync();

                            return(Forbid());
                        }

                        await _contentManager.UnpublishAsync(item);
                    }
                    await _notifier.SuccessAsync(H["Content unpublished successfully."]);

                    break;

                case ContentsBulkAction.Remove:
                    foreach (var item in checkedContentItems)
                    {
                        if (!await IsAuthorizedAsync(CommonPermissions.DeleteContent, item))
                        {
                            await _notifier.WarningAsync(H["Couldn't remove selected content."]);

                            await _session.CancelAsync();

                            return(Forbid());
                        }

                        await _contentManager.RemoveAsync(item);
                    }
                    await _notifier.SuccessAsync(H["Content removed successfully."]);

                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }

            return(RedirectToAction(nameof(List)));
        }