/*
Kooboo is a content management system based on ASP.NET MVC framework. Copyright 2009 Yardi Technology Limited.
This program is free software: you can redistribute it and/or modify it under the terms of the
GNU General Public License version 3 as published by the Free Software Foundation.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program.
If not, see http://www.kooboo.com/gpl3/.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
namespace Everest.Library.Security{
public class RoleAuthorizer
{
/// <summary>
/// Determines whether the specified denies is authorized.
/// </summary>
/// <param name="denies">The denies. string like:"?,*,Administrator "</param>
/// <param name="allows">The allows.string like:"?,*,Administrator"</param>
/// <param name="user">The user.</param>
/// <returns>
/// <c>true</c> if the specified denies is authorized; otherwise, <c>false</c>.
/// </returns>
public virtual bool IsAuthorized(string denies, string allows, IPrincipal user)
{
bool denied = false;
bool allowed = true;
denied = IsDenied(denies, user);
allowed = IsAllowed(allows, user);
return (!denied) && allowed;
}
/// <summary>
/// Determines whether the specified denies is denied.
/// </summary>
/// <param name="denies">The denies.</param>
/// <param name="user">The user.</param>
/// <returns>
/// <c>true</c> if the specified denies is denied; otherwise, <c>false</c>.
/// </returns>
private bool IsDenied(string denies, IPrincipal user)
{
if (string.IsNullOrEmpty(denies))
{
return false;
}
return IsInRoles(denies, user);
}
/// <summary>
/// Determines whether the specified allows is allowed.
/// </summary>
/// <param name="allows">The allows.</param>
/// <param name="user">The user.</param>
/// <returns>
/// <c>true</c> if the specified allows is allowed; otherwise, <c>false</c>.
/// </returns>
private bool IsAllowed(string allows, IPrincipal user)
{
if (string.IsNullOrEmpty(allows))
{
return true;
}
return IsInRoles(allows, user);
}
/// <summary>
/// Determines whether [is in roles] [the specified roles].
/// </summary>
/// <param name="roles">The roles.</param>
/// <param name="user">The user.</param>
/// <returns>
/// <c>true</c> if [is in roles] [the specified roles]; otherwise, <c>false</c>.
/// </returns>
private bool IsInRoles(string roles, IPrincipal user)
{
string[] roleArr = roles.Split(',');
if (!user.Identity.IsAuthenticated)
{
if (roleArr.Contains("?"))
{
return true;
}
}
else // Authenticated
{
if (roleArr.Contains("*"))
{
return true;
}
foreach (var role in roleArr.Where(s => s != "?" && s != "*"))
{
bool inRole = user.IsInRole(role);
if (inRole)
{
return inRole;
}
}
}
return false;
}
}
}
|