narsil/Tanshu.Accounts.SqlDAO/BusinessLayer/MembershipBI.cs

117 lines
3.8 KiB
C#

using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Data.SqlClient;
using Tanshu.Accounts.Contracts;
using Tanshu.Data.DAO;
using Tanshu.Accounts.SqlDAO;
using Tanshu.Accounts.Entities;
using Tanshu.Accounts.Entities.Auth;
using NHibernate.Criterion;
using NHibernate.Linq;
using NHibernate;
namespace Tanshu.Accounts.Repository
{
public class MembershipBI
{
public void AddUserToGroup(int userID, int groupID)
{
using (var session = SessionManager.Session)
{
var user = session.Get<User>(userID);
var group = session.Get<Group>(groupID);
var userGroup = session.CreateCriteria<UserGroup>()
.Add(Restrictions.Eq("UserID", userID))
.Add(Restrictions.Eq("GroupID", groupID))
.UniqueResult<UserGroup>();
if (userGroup == null)
session.Save(
new UserGroup()
{
User = user,
Group = group
}
);
}
}
public string[] GetAllRoles()
{
using (var session = SessionManager.Session)
{
var roleList = session.CreateCriteria<Role>().List<Role>();
string[] list = new string[roleList.Count];
for (int i = 0; i < list.Length; i++)
{
list[i] = roleList[i].Name;
}
return list;
}
}
public string[] GetRolesForUser(string username)
{
using (var session = SessionManager.Session)
{
var user = session.CreateCriteria<User>()
.Add(Restrictions.Eq("Name", username))
.UniqueResult<User>();
List<string> roles = new List<string>();
foreach (var group in user.Groups)
{
foreach (var item in group.RoleGroups)
{
roles.Add(item.Role.Name);
}
}
return roles.ToArray();
}
}
public bool IsUserInRole(string username, string roleName)
{
using (var session = SessionManager.Session)
{
var user = session.CreateCriteria<User>()
.Add(Restrictions.Eq("Name", username))
.UniqueResult<User>();
return IsUserInRole(user.UserID, roleName);
}
}
public bool IsUserInRole(int userID, string roleName)
{
string query = @"
SELECT COUNT(*) AS Role_Count FROM
Auth_UserGroups ug INNER JOIN Auth_RoleGroups rg ON ug.GroupID = rg.GroupID
INNER JOIN Auth_Roles r ON rg.RoleID = r.RoleID
WHERE ug.UserID = :UserID AND r.Name = :Role;";
using (var session = SessionManager.Session)
{
return session
.CreateSQLQuery(query)
.AddScalar("Role_Count",NHibernateUtil.Int32)
.SetInt32("UserID", userID)
.SetString("Role", roleName)
.UniqueResult<int>() > 0;
}
}
public void RemoveUserFromGroup(int userID, int groupID)
{
using (var session = SessionManager.Session)
{
var userGroup = session.CreateCriteria<UserGroup>()
.Add(Restrictions.Eq("UserID", userID))
.Add(Restrictions.Eq("GroupID", groupID))
.UniqueResult<UserGroup>();
if (userGroup != null)
session.Delete(userGroup);
}
}
}
}