Click here to Skip to main content
15,879,348 members
Articles / Security

Create Custom Permission in Object Level

Rate me:
Please Sign up or sign in to vote.
4.94/5 (12 votes)
11 Jun 2012CPOL3 min read 56.3K   3.8K   35   8
Custom permission in object level with out sign in and out to affect to users

Download CustomPermission.zip

Introduction

This is a Custom permission control in object level that controls users access to object in pages!
In this project I use Linq to EntityFramework. 

You just need to add permissions to Roles and add Roles To users ,

And in your pages just use this class, this is a code sample of how it works:

C#
btn1.Visible = PermissionControl.CheckPermission("Install");
btn2.Visible = PermissionControl.CheckPermission("UnInstall");

Custom Permission Tables:

Image 1

In Custom Permission DataBase we Have 5 Table: 

 1-Users: Store user info. 

 2-Roles : Store Roles.

 3-Permission: Store permissions and have 2two name for permission  first is Permission Title For Showing to The users and second is Constant name for Use in Coding Like preview code snippet. 

 4-Users Roles: Store The Roles Of users Because each user can have more than one Role.

 5-Role Permissions:Store Permissions For every Roles.   

Using the code

In this chapter I will Explain How It works:  

First Of All You Create two instance of these collections:

C#
private static readonly HttpSessionState Session = HttpContext.Current.Session;
private static readonly HttpApplicationState Application = HttpContext.Current.Application;

Session is for each user and application is for all current users.
We go forward and you will understand The reason of This code snippet.

Then you make a method Named CheckPermission that only you need to pass
PermissionConstantName of Permissions to this Method:

C#
public static bool CheckPermission(string PermissionConstantName)
<pre>{ 
    bool result = false; 
    // Is current visitor logged in?
    if (!HttpContext.Current.User.Identity.IsAuthenticated)
    { 
        return false;
    } 
    string Username = HttpContext.Current.User.Identity.Name; 
    //if in user permissions you make changes, you have to clear his permission list
    if (Application["AffectedUsers"] != null)
    { 
        var AffectedUsers = (List<string>) Application["AffectedUsers"];
        if (AffectedUsers.Contains(Username))
        {
            Session["PermissionList"] = null;
            AffectedUsers.Remove(Username);
            Application["AffectedUsers"] = AffectedUsers;
        } 
    } 
    Users CurrentUser = 
        (from user in DataContext.Context.Users where user.Username == Username select user).
            SingleOrDefault(); 
    //return True because SuperAdmin has all the permissions!
    if (CurrentUser.IsSuperAdmin)
    { 
        return true;
    } 
    if (Session["PermissionList"] == null)
    {
        List<string> PermissionList = (from p in DataContext.Context.Permissions
                                       join rp in DataContext.Context.RolePermissions on 
                                       p.PermissionID
                                           equals
                                           rp.PermissionID
                                       join r in DataContext.Context.Roles on rp.RoleID 
                                       equals r.RoleID
                                       join ur in DataContext.Context.UserRoles on r.RoleID 
                                           ur.RoleID
                                       where ur.UserID == CurrentUser.UserID
                                       select p.PermissionConstantName).Distinct().ToList(); 
        Session["PermissionList"] = PermissionList; 
        result = PermissionList.Contains(PermissionConstantName);
    } 
    else 
    { 
        var PermissionList = (List<string>) Session["PermissionList"]; 
        result = PermissionList.Contains(PermissionConstantName); 
    } 
    return result; 
} 


When You Call This Method in your Code , method use HttpContext to find Current User and check That user Has Permission or not.

Permissions for current user collect in a list into a session.

And Affected User list is for:

When you change Role Permissions means current user don't have permission to access that object any more, and if the user exist on that list , check permission return false.
and this is The good point of my Custom Permission Control That don't need to Sign out and sign in
again to affect the current user.

If user Is SuperAdmin this means Has access to All objects and don't need to check with permissions Table in DB so method returns true for Super Admins.

Manage Roles Permissions:

You just Need A gridview control To Show The Roles , And a checkbox list for permissions.

And I don't write code Here because I include it in project for download and its Enough clear to understand.

Manage Users:

You need A grid view to show User Details and some text box with some check box for existing Roles and add Roles To Users.
I Already Do it for You that include in my project.

How Can I Use This In My Current Project?

My User Table Isn't enough good because I focus Only on Permissions, You can improve My User table and use it in your Project and you Only need using this class and To Call CheckPermissionand pass a string to this method.

In this way use This Class:

ASP.NET
<asp:LinkButton ID="lbConfigure" runat="server" CommandName="Configure" CommandArgument='<%# Eval("AdminFilePath") %>' Visible='<%#PortalCommon.PermissionControl.CheckPermission("ModuleConfig") %>'>Install module</asp:LinkButton>    

Or in code behind:

C#
btn1.Visible = PermissionControl.CheckPermission("Install");
LinkButton1.Visible = PermissionControl.CheckPermission("UnInstall");

If you want to test my project , change the connection string and open cp.edmx in Model folder right click on white space between table and choose Generate database from model and execute the script in your database ,add permission with constname: Install and UnIstall in database , then use PermissionManager page to make new Roles ,then make user with roles and Use Login Form, Then Go to default.aspx page And see How Roles Affect Object on the Page!

I will include a Folder For Database For people who don't familiar whit Entity FrameWork.  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Iran (Islamic Republic of) Iran (Islamic Republic of)
Taha has started programming at the age of 16 and he has taken an avid interest in Microsoft technologies. He professionally works on ASP.NET and C#. Mainly, He lives for getting the world into codes and follows this aspiration in a third world country with lack of facility and support. He never gives up seeking success and competence.

Comments and Discussions

 
QuestionCreate Custom Permission in Object Level Pin
Iqbal Shah3-Jul-17 0:11
Iqbal Shah3-Jul-17 0:11 
Hello Sir
Can we use this methodology in WinForm Desktop application and the code of course?
QuestionWhich part manage the Permission? Pin
Ardiyan Bekti Santoso18-Feb-14 16:12
Ardiyan Bekti Santoso18-Feb-14 16:12 
AnswerRe: Which part manage the Permission? Pin
taha bahraminezhad Jooneghani11-Nov-14 20:21
taha bahraminezhad Jooneghani11-Nov-14 20:21 
Questiontanks Pin
rezaqanbari8-Jan-13 8:32
rezaqanbari8-Jan-13 8:32 
AnswerRe: tanks Pin
taha bahraminezhad Jooneghani11-Feb-13 11:44
taha bahraminezhad Jooneghani11-Feb-13 11:44 
GeneralMy vote of 5 Pin
parisa heidari12-Jun-12 2:49
parisa heidari12-Jun-12 2:49 
GeneralMy vote of 5 Pin
nairika vakili11-Jun-12 4:28
nairika vakili11-Jun-12 4:28 
GeneralRe: My vote of 5 Pin
taha bahraminezhad Jooneghani11-Jun-12 8:30
taha bahraminezhad Jooneghani11-Jun-12 8:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.