More in this section
Categories
Bloggers
Blogs RSS feed

Trim the Search Results based on permissions / roles

by User Not Found
Edit: The code was updated to work correctly when Paging is enabled.

This blog post will guide you through the steps on how to trim the search results based on permissions or roles. Let's start with the use case: 
I've got a page which is visible only to authenticated users:
authenticatedUsers
Figure: This page is visible only to Authenticated users.

So, if you are not logged in in the front end you will not see the page in the navigation. Even if you manually type its URL in the address bar you will be first redirected to the login screen. So far so good.
Imagine now that an anonymous user performs a search that returns this particular page as a result. He would be able to see it in the search results and maybe even see some confidential information:


Figure: an Anonymous user performs a search which returns the page he's not supposed to see

Note: the unauthenticated user will not be able to open the page, but still be able to see its title, URL and some of the content.

The steps below will show you how to change the behaviour of the SearchResults widget so that it takes into account the permissions of the individual result items.

1. Create a class in your Visual Studio solution that inherit from the SearchResults class:

public class SearchResultsByPermissions : SearchResults
{
 
}

2. Override the InitializeControls method:

public class SearchResultsByPermissions : SearchResults
{
    protected override void InitializeControls(GenericContainer container)
    {           
        Label resultsStats = this.ResultsStats;
             
        //this is the original localized stats message. It shows all the results
        var resultsStatsMessage = resultsStats.Text;          
 
        base.InitializeControls(container);           
             
        if (string.IsNullOrEmpty(this.Query))
        {
            this.ResultsStats.Text = string.Empty;
            return;
        }
             
        int numberOfAllResults = 0;         
        SearchResults.ISearcher searcher = this.GetSearcher();
             
        //these are all the results (not filtered by permissions)
        var allResults = searcher.Search(this.Query, this.IndexCatalogue, 0, 0, out numberOfAllResults);
             
        if (allResults == null)
        {
            return;
        }
             
        //here we will store only the results we have permissions to see
        List<IDocument> securedResultSet = new List<IDocument>();
 
        foreach (var document in allResults)
        {
            var type = document.GetValue("ContentType");
 
            var ID = new Guid(document.GetValue("OriginalItemId"));
 
            if (TypeResolutionService.ResolveType(type) == typeof(PageNode))
            {
                var manager = PageManager.GetManager();
                 
                //suppress the security checks so the code can be executed even if
                //the current user doesn't have enough permissions
                manager.Provider.SuppressSecurityChecks = true;
 
                var page = manager.GetPageNode(ID);
 
                if (page != null)
                {
                    ISecuredObject securedObject = (ISecuredObject)page;
 
                    if (SecurityExtensions.IsSecurityActionTypeGranted(securedObject, SecurityActionTypes.View))
                    {
                        securedResultSet.Add(document);
                    }
                }
 
                manager.Provider.SuppressSecurityChecks = false;
            }               
        }
 
        var numberOfSecuredSearchResults = securedResultSet.Count;
 
        char[] chrArray = new char[] { '\"' };
        string str = this.Query.Trim(chrArray);
 
        resultsStats.Text = string.Format(resultsStatsMessage, numberOfSecuredSearchResults, HttpUtility.HtmlEncode(str));
             
        this.ConfigurePager(numberOfSecuredSearchResults);
 
        this.ResultsList.DataSource = null;
 
        int itemsToSkip = this.GetItemsToSkip();
        int itemsToTake = this.GetItemsToTake();
        ResultsList.DataSource = securedResultSet.Skip(itemsToSkip).Take(itemsToTake);
    }
 
    private int GetItemsToSkip()
    {
        if (this.AllowPaging)
        {
            int pageNumber = this.GetPageNumber(this.GetUrlEvaluationMode(), this.PageKey, 0, "PageNumber");
            if (pageNumber > 0)
            {
                return (pageNumber - 1) * this.ItemsPerPage;
            }
        }
        return 0;
    }
 
    private int GetItemsToTake()
    {
        if (!this.AllowPaging)
        {
            return 0;
        }
        return this.ItemsPerPage;
    }
}

Here is some explanation: we call the base InitializeControls method because it takes care of calling the search service and binding the results to the ResultsList repeater. The ResultsList repeater is part of the UI that shows the results. 
Remember, this results collection is not yet trimmed by permissions, so we need to alter it and include only the items that the current user is allowed to see.
To do that, we iterate through the collection and for each item we check its type. Based on the content type we invoke the appropriate manager and check if the View permission type is granted to the current user. If it is, then we add it to our securedResultSet collection.
At the end we bind the ResultsList repeater to the securedResultSet collection.
Note, you can use the same logic to perform checks on other content types like News, Documents, etc.

Finally, the message that shows the number of the returned results is updated, because the securedResultSet collection might contain less items than the original results collection. 

3. Build and Register the new widget using Thunder in the page's toolbox.

4. Drag the new widget to a page and start using it.

That's it. Now the anonymous users will not find the pages they are not supposed to see:


Figure: the search results do not include the page that is hidden for anonymous users

Thanks to Svetla Yankova for the best parts of the code.

Attached is the complete C# file: SearchResultsByPermissions

68 comments

Leave a comment
  1. Jimmy May 02, 2013
    Hi Vesselin,

    I have tried the Search Result by Permission widget.  Its implementation includes searching in pages only.  It only works when the search index searches through Static Html. It doesn’t ever get into the condition when the documents are News items or Events.

    Do you have a more complete sample code that can search through all other content types, such News, Events, Documents & Files, Lists, and Content blocks?

    Thanks,
    Jimmy
  2. Vesselin May 03, 2013
    Hey Jimmy,

    the above code works with Page nodes only, but you can apply the same approach with other content types as News, Events, etc.

    Just check the type of the item and then invoke the corresponding manager to find the item and check its permissions.
  3. Chanan May 17, 2013
    Just a word of caution: this works on search results afterbinding, so if your visitors' searches are likely to produce multiple results pages, this would present a problem. At least this is our experience.
  4. Chanan May 20, 2013
    Just been informed that this blog will be updated by the end of this month (May 2013) to fix the paging problem.
  5. Vesselin May 21, 2013
    The code was updated to include the paging scenarios. It will be live soon.
  6. Charlotte Hack Apr 02, 2018
    Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know.Charlotte Hack
  7. robert Apr 02, 2018
    Hello, I have browsed most of your posts. This post is probably where I got the most useful information for my research. Thanks for posting, maybe we can see more on this. Are you aware of any other websites on this subject.law school overview
  8. robert Apr 02, 2018
    I have bookmarked your blog, the articles are way better than other similar blogs.. thanks for a great blog!Best coffee shop Santa Monica
  9. robert Apr 02, 2018
    Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.Probate
  10. robert Apr 02, 2018
    I really loved reading your blog. It was very well authored and easy to undertand. Unlike additional blogs I have read which are really not tht good. I also found your posts very interesting. In fact after reading, I had to go show it to my friend and he ejoyed it as well!Torrington dentist CT
  11. robert Apr 02, 2018
    Great job for publishing such a beneficial web site. Your web log isn’t only useful but it is additionally really creative too. There tend to be not many people who can certainly write not so simple posts that artistically. Continue the nice writingbest cruises for singles
  12. robert Apr 02, 2018
    This is a great post. I like this topic.This site has lots of advantage.I found many interesting things from this site. It helps me in many ways.Thanks for posting this again.property maintenance service
  13. robert Apr 02, 2018
    This article gives the light in which we can observe the reality. This is very nice one and gives indepth information. Thanks for this nice article.Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include.motorcycle accident attorney
  14. robert Apr 02, 2018
    I really loved reading your blog. It was very well authored and easy to understand. Unlike other blogs I have read which are really not that good.Thanks alot!Retail Management Consultant in Los Angeles
  15. robert Apr 02, 2018
    it was a wonderful chance to visit this kind of site and I am happy to know. thank you so much for giving us a chance to have this opportunity..networking
  16. robert Apr 02, 2018
    I am happy to find this post Very useful for me, as it contains lot of information. I Always prefer to read The Quality and glad I found this thing in you post. Thanksdirect marketing nyc
  17. robert Apr 02, 2018
    Nice to be visiting your blog again, it has been months for me. Well this article that i’ve been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share.Military vacation loans
  18. robert Apr 02, 2018
    I really impressed after read this because of some quality work and informative thoughts . I just wanna say thanks for the writer and wish you all the best for coming!.over 40 fitness Walnut
  19. robert Apr 02, 2018
    I gotta  favorite this website   it seems  very helpful .Great knowledge, do anyone mind merely reference back to ittwo easy ways to $100 a day
  20. pest control Apr 03, 2018
    Η Alpha Αποφρακτική Service είναι μια επιχείρηση με αλματώδη ανάπτυξη στην καταπολέμηση όλων των ειδών των εντόμων και τρωκτικών. Η ιδιαιτερότητα και η δύναμη της βασίζεται στην υψηλή ποιότητα υπηρεσίας, στην υπεύθυνη εξυπηρέτηση των πελατών της σε συνδυασμό με τα προσιτά κοστολόγια και στα μοναδικά 'φάρμακα' που χρησιμοποιεί τα οποία είναι αβλαβή για ανθρώπους, παιδιά και κατοικίδια ζώα. Η Alpha Αποφρακτική Service καλύπτει με οργανωμένο και φιλικό τρόπο κάθε ανάγκη μας για απολύμανση και απομάκρυνση ανεπιθύμητων εντόμων. Στηρίζεται στην προσωπική γνωριμία που αναπτύσσει με κάθε έναν της πελάτη ξεχωριστά όπως βεβαίως και στις σύγχρονες τεχνολογίες που χρησιμοποιεί.apolimanseis
  21. thiết kế web giá rẻ quảng trị Apr 07, 2018
    You have a real ability for writing unique content. I like how you think and the way you represent your views in this article. I agree with your way of thinking. Thank you for sharing.thiết kế web giá rẻ quảng trị
  22. vpn Apr 07, 2018
    Nice to be visiting your blog again, it has been months for me. Well this article that i've been waited for so long. I need this article to complete my assignment in the college, and it has same topic with your article. Thanks, great share.vpn
  23. robo Apr 11, 2018
    Great post I would like to thank you for the efforts you have made in writing this interesting and knowledgeable article.DETECTIVES EN MADRID
  24. best financial advisor whittier Apr 11, 2018
    Most seminars are boring, two hour, pitch-fest with speakers who try to sell books, videos, and coaching kits. These people profit from your desire to secure a common sense retirement plan.best financial advisor whittier
  25. robo Apr 12, 2018
    Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know.soundproof fencing
  26. Workout Music Apr 12, 2018
    I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.Workout Music
  27. robo Apr 17, 2018
    Hi there! Nice post! Please tell us when I will see a follow up!AGENCIA DETECTIVES MADRID
  28. Gespoten kurk Apr 21, 2018
    Great post I would like to thank you for the efforts you have made in writing this interesting and knowledgeable article.Gespoten kurk
  29. highly recommended source Apr 21, 2018
    I have read your article, it is very informative and helpful for me.I admire the valuable information you offer in your articles. Thanks for posting it..highly recommended source
  30. Ora Apr 22, 2018
    I was cheerfull and happy enthousiastic when this blog was presented. Interesting stuff to read. Terrasoverkappingen | Pergola's | Zonwering
    | Zwembaden | Polypropyleen zwembad
    I was happy so enthousiastic with all the Interesting stuff to read hre. Zwembad aanleggen | Zwembad bouwen | Zonnescreens | Zwembad op maat | Polypropyleen zwembaden
    I found this a very interesting and entertaining blogarticle to read.  Zwembaden
  31. robo Apr 24, 2018
    That is the excellent mindset, nonetheless is just not help to make every sence whatsoever preaching about that mather. Virtually any method many thanks in addition to i had endeavor to promote your own article in to delicius nevertheless it is apparently a dilemma using your information sites can you please recheck the idea. thanks once more.DETECTIVE PRIVADO
  32. Soloya.be Apr 27, 2018
    I was really enthousiastic when this blog was presented. Of great interest to me to read. Zonnepanelen | Zonnepanelen kopen | Zonnepanelen installateur | Warmtepomp kopen | Airco | Airconditioning
  33. robo Apr 30, 2018
    Great! It sounds good. Thanks for sharing..AGENCIA DETECTIVES MADRID
  34. face depuffer May 01, 2018
    Superbly written article, if only all bloggers offered the same content as you, the internet would be a far better place..face depuffer
  35. sohail khatri May 01, 2018
    Hey, this day is too much good for me, since this time I am reading this enormous informative article here at my home. Thanks a lot for massive hard work. voyance qualité
  36. james jack May 02, 2018
    I encourage you to read this text it is fun     described ... Technology
  37. Luxenza.be May 03, 2018
    Thank you very much for this useful article. https://massagesalon-limburg.be/ likes it Erotische massage
    Howdy just wanted to give you a quick heads up Massage Limburg
    I am really glad I have found this information Striptease
    I like it what you formulated here. Erotische massages
  38. sami May 07, 2018
    Your website is really cool and this is a great inspiring article. Thank you so much.model staffing agency
  39. Wordpresswebdesign.be May 08, 2018
    Great read up. Is there more coming on this subject? Greetings from https://wordpresswebdesign.be Wordpress webdesign
    Great effort on this subject. Is there more following on this subject? https://wordpresswebdesign.be
    https://wordpresswebdesign.be really admires what you achieved in this article. Great read up. Is there more coming out?. Wordpress webdesigner
    https://wordpresswebdesign.be likes you efforts on this subject. Wordpress website laten bouwen
    https://wordpresswebdesign.be what you wrote down this subject. Wordpress website
    Great read up. Is there more coming on this subject. Greetings from https://wordpresswebdesign.be Webdesign
    Wordpresswebdesign.be likes what you wrote down this subject. Greetings from https://wordpresswebdesign.be Wordpress website bouwer
  40. domino qq online May 10, 2018
    Just admiring your work and wondering how you managed this blog so well. It’s so remarkable that I can't afford to not go through this valuable information whenever I surf the internet!domino qq online
  41. Zonnepanelen-centrale.be May 14, 2018
    I was lucky to have found this blog and I found this very interesting and entertaining to read. Thank you from www.soloya.be and https://zonnepanelen-centrale.be  Zonnepanelen | Warmtepompen | Warmtepompen 
  42. judi bandarq online May 15, 2018
    I felt very happy while reading this site. This was really very informative site for me. I really liked it. This was really a cordial post. Thanks a lot!.judi bandarq online
  43. robo May 15, 2018
    This is such a great resource that you are providing and you give it away for free. I love seeing websites that understand the value of providing a quality resource for free. It is the old what goes around comes around routine.bomberman switch
  44. sami May 16, 2018
    Your website is really cool and this is a great inspiring article. Thank you so much.DETECTIVES EN MADRID
  45. Sempris.be May 21, 2018
    Sempris.be really admires what you wrote down this subject.Webdesign
  46. wordpresswebdesign.be May 21, 2018
    Great read up. Is there more coming on this subject? Greetings from https://wordpresswebdesign.be Wordpress webdesign
  47. sami May 22, 2018
    Hi! Thanks for the great information you havr provided! You have touched on crucuial points!ganhar seguidores instagram
  48. robo May 24, 2018
    This is a brilliant blog! I'm very happy with the comments!..2018 Penny Box - 2018 D Penny Roll
  49. bandarq online tepercaya May 27, 2018
    Thanks for the valuable information and insights you have so provided here...bandarq online tepercaya
  50. sami May 30, 2018
    Someone Sometimes with visits your blog regularly and recommended it in my experience to read as well. The way of writing is excellent and also the content is top-notch. Thanks for that insight you provide the readers!Informáticos forenses Madrid

    Leave a comment