Saturday, September 15, 2012

Authorization and Permission using Attribute in MVC3

Public enum PermissionType
{
permission1,
permission2,
permissiontype3
}
public class AuthorizePermissionAttribute : AuthorizeAttribute
{
private readonly IRolesService _rolesService;
private readonly IUserService _userService;
private string[] _rolesSplit;
private string[] _usersSplit;
public PermissionType[] PermissionName;
public AuthorizePermissionAttribute()
: this(new AspNetMembershipProviderWrapper(), new AspNetRoleProviderWrapper())
{
}
public AuthorizePermissionAttribute(IUserService userService, IRolesService rolesService)
{
_userService = userService;
_rolesService = rolesService;
}
public AuthorizePermissionAttribute(PermissionType[] PermissionName)
: this(new AspNetMembershipProviderWrapper(), new AspNetRoleProviderWrapper())
{
this.PermissionName = PermissionName;
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
try
{

var user = httpContext.User;
if (!user.Identity.IsAuthenticated)
return false;

if (_usersSplit == null)
_usersSplit = SplitString(Users);
if (_rolesSplit == null)
_rolesSplit = SplitString(Roles);

if (_usersSplit.Any() && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase))
return false;

//if (!_rolesService.Enabled || !_rolesSplit.Any())
// return true;

//return _rolesSplit.Any(user.IsInRole);

IEnumerable userroles = _rolesService.FindByUser(MySession.Current.User);


var roleids = _context.aspnet_Roles.Where(a => userroles.Contains(a.RoleName)).Select(a => a.RoleId);
var rpt = _context.Role_Permission_Trans.Where(a => roleids.Contains(a.RoleID)).Select(a => a.PID);
var pm = _context.PermissionMasters.Where(p => rpt.Contains(p.PID));
var permissions = PermissionName.ToString(",").ToLower().Split(",".ToCharArray());
var res = pm.Where(p => permissions.Contains(p.PermissionName.ToLower()));
if (res.IsNotNull() && res.Count() > 0)
{
return true;
}
else
{
return false;
}

}
catch (Exception)
{


}
return false;
//return base.AuthorizeCore(httpContext);

}
private static string[] SplitString(string original)
{
if (String.IsNullOrEmpty(original))
return new string[0];

var split = from piece in original.Split(',')
let trimmed = piece.Trim()
where !String.IsNullOrEmpty(trimmed)
select trimmed;
return split.ToArray();
}
}

public class LogonAuthorize : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!(filterContext.Controller is AccountController) && !(filterContext.Controller is HomeController))
base.OnAuthorization(filterContext);
}
}

Share This!


No comments:

Powered By Blogger · Designed By Seo Blogger Templates