using Longbow.Caching;
using Longbow.Caching.Configuration;
using Longbow.Data;
using Longbow.ExceptionManagement;
using Longbow.Security;
using Longbow.Security.Principal;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
namespace Bootstrap.DataAccess
{
///
/// 用户表相关操作类
///
public static class UserHelper
{
internal const string RetrieveUsersDataKey = "UserHelper-RetrieveUsers";
private const string RetrieveUsersByNameDataKey = "UserHelper-RetrieveUsersByName";
internal const string RetrieveUsersByRoleIDDataKey = "UserHelper-RetrieveUsersByRoleId";
internal const string RetrieveUsersByGroupIDDataKey = "UserHelper-RetrieveUsersByGroupId";
///
/// 查询所有用户
///
///
///
public static IEnumerable RetrieveUsers(string tId = null)
{
string sql = "select ID, UserName, DisplayName, RegisterTime, ApprovedTime from Users Where ApprovedTime is not null";
var ret = CacheManager.GetOrAdd(RetrieveUsersDataKey, CacheSection.RetrieveIntervalByKey(RetrieveUsersDataKey), key =>
{
List Users = new List();
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
try
{
using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
{
while (reader.Read())
{
Users.Add(new User()
{
ID = (int)reader[0],
UserName = (string)reader[1],
DisplayName = (string)reader[2],
RegisterTime = (DateTime)reader[3],
ApprovedTime = (DateTime)reader[4]
});
}
}
}
catch (Exception ex) { ExceptionManager.Publish(ex); }
return Users;
}, CacheSection.RetrieveDescByKey(RetrieveUsersDataKey));
return string.IsNullOrEmpty(tId) ? ret : ret.Where(t => tId.Equals(t.ID.ToString(), StringComparison.OrdinalIgnoreCase));
}
///
/// 根据用户名查询用户
///
///
///
public static User RetrieveUsersByName(string userName)
{
if (LgbPrincipal.IsAdmin(userName)) return new User() { DisplayName = "网站管理员", UserName = userName };
string key = string.Format("{0}-{1}", RetrieveUsersByNameDataKey, userName);
return CacheManager.GetOrAdd(key, CacheSection.RetrieveIntervalByKey(RetrieveUsersByNameDataKey), k =>
{
User user = null;
string sql = "select ID, UserName, [Password], PassSalt, DisplayName, RegisterTime, ApprovedTime from Users where ApprovedTime is not null and UserName = @UserName";
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
try
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@UserName", userName, ParameterDirection.Input));
using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
{
if (reader.Read())
{
user = new User()
{
ID = (int)reader[0],
UserName = (string)reader[1],
Password = (string)reader[2],
PassSalt = (string)reader[3],
DisplayName = (string)reader[4],
RegisterTime = (DateTime)reader[5],
ApprovedTime = (DateTime)reader[6]
};
}
}
}
catch (Exception ex) { ExceptionManager.Publish(ex); }
return user;
}, CacheSection.RetrieveDescByKey(RetrieveUsersByNameDataKey));
}
///
/// 删除用户
///
///
public static bool DeleteUser(string ids)
{
bool ret = false;
if (string.IsNullOrEmpty(ids) || ids.Contains("'")) return ret;
try
{
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.StoredProcedure, "Proc_DeleteUsers"))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@ids", ids, ParameterDirection.Input));
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd);
}
CacheCleanUtility.ClearCache(userIds: ids);
ret = true;
}
catch (Exception ex)
{
ExceptionManager.Publish(ex);
}
return ret;
}
///
/// 保存新建/更新的用户信息
///
///
///
public static bool SaveUser(User p)
{
if (p == null) throw new ArgumentNullException("p");
bool ret = false;
if (p.UserName.Length > 50)
p.UserName.Substring(0, 50);
p.PassSalt = LgbCryptography.GenerateSalt();
p.Password = LgbCryptography.ComputeHash(p.Password, p.PassSalt);
if (string.IsNullOrEmpty(p.Description))
p.Description=" ";
else if(p.Description.Length > 500)
p.Description.Substring(0, 500);
string sql = p.ID == 0 ?
"Insert Into Users (UserName, Password, PassSalt, DisplayName, RegisterTime, ApprovedTime,Description) Values (@UserName, @Password, @PassSalt, @DisplayName, GetDate(), @ApprovedTime,@Description)" :
"Update Users set UserName = @UserName, Password = @Password, PassSalt = @PassSalt, DisplayName = @DisplayName,Description=@Description where ID = @ID";
try
{
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@ID", p.ID, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@UserName", p.UserName, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@Password", p.Password, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@PassSalt", p.PassSalt, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@DisplayName", p.DisplayName, ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@ApprovedTime", DBAccess.ToDBValue(p.ApprovedTime), ParameterDirection.Input));
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@Description", p.Description, ParameterDirection.Input));
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd);
}
CacheCleanUtility.ClearCache(userIds: p.ID == 0 ? "" : p.ID.ToString());
ret = true;
}
catch (DbException ex)
{
ExceptionManager.Publish(ex);
}
return ret;
}
///
/// 验证用户登陆账号与密码正确
///
///
///
///
public static bool Authenticate(string userName, string password)
{
var user = RetrieveUsersByName(userName);
return user != null && user.Password == LgbCryptography.ComputeHash(password, user.PassSalt);
}
///
/// 通过roleId获取所有用户
///
///
///
public static IEnumerable RetrieveUsersByRoleId(int roleId)
{
string key = string.Format("{0}-{1}", RetrieveUsersByRoleIDDataKey, roleId);
return CacheManager.GetOrAdd(key, CacheSection.RetrieveIntervalByKey(RetrieveUsersByNameDataKey), k =>
{
List Users = new List();
string sql = "select u.ID, u.UserName, u.DisplayName, case ur.UserID when u.ID then 'checked' else '' end [status] from Users u left join UserRole ur on u.ID = ur.UserID and RoleID = @RoleID where u.ApprovedTime is not null";
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@RoleID", roleId, ParameterDirection.Input));
try
{
using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
{
while (reader.Read())
{
Users.Add(new User()
{
ID = (int)reader[0],
UserName = (string)reader[1],
DisplayName = (string)reader[2],
Checked = (string)reader[3]
});
}
}
}
catch (Exception ex) { ExceptionManager.Publish(ex); }
return Users;
}, CacheSection.RetrieveDescByKey(RetrieveUsersByRoleIDDataKey));
}
///
/// 通过角色ID保存当前授权用户(插入)
///
/// 角色ID
/// 用户ID数组
///
public static bool SaveUsersByRoleId(int id, string userIds)
{
bool ret = false;
DataTable dt = new DataTable();
dt.Columns.Add("RoleID", typeof(int));
dt.Columns.Add("UserID", typeof(int));
if (!string.IsNullOrEmpty(userIds)) userIds.Split(',').ToList().ForEach(userId => dt.Rows.Add(id, userId));
using (TransactionPackage transaction = DBAccessManager.SqlDBAccess.BeginTransaction())
{
try
{
//删除用户角色表该角色所有的用户
string sql = "delete from UserRole where RoleID=@RoleID";
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@RoleID", id, ParameterDirection.Input));
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd, transaction);
//批插入用户角色表
using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction))
{
bulk.DestinationTableName = "UserRole";
bulk.ColumnMappings.Add("RoleID", "RoleID");
bulk.ColumnMappings.Add("UserID", "UserID");
bulk.WriteToServer(dt);
transaction.CommitTransaction();
}
}
CacheCleanUtility.ClearCache(userIds: userIds, roleIds: id.ToString());
ret = true;
}
catch (Exception ex)
{
ExceptionManager.Publish(ex);
transaction.RollbackTransaction();
}
}
return ret;
}
///
/// 通过groupId获取所有用户
///
///
///
public static IEnumerable RetrieveUsersByGroupId(int groupId)
{
string key = string.Format("{0}-{1}", RetrieveUsersByGroupIDDataKey, groupId);
return CacheManager.GetOrAdd(key, CacheSection.RetrieveIntervalByKey(RetrieveUsersByGroupIDDataKey), k =>
{
List Users = new List();
string sql = "select u.ID, u.UserName, u.DisplayName, case ur.UserID when u.ID then 'checked' else '' end [status] from Users u left join UserGroup ur on u.ID = ur.UserID and GroupID =@groupId where u.ApprovedTime is not null";
DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql);
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@GroupID", groupId, ParameterDirection.Input));
try
{
using (DbDataReader reader = DBAccessManager.SqlDBAccess.ExecuteReader(cmd))
{
while (reader.Read())
{
Users.Add(new User()
{
ID = (int)reader[0],
UserName = (string)reader[1],
DisplayName = (string)reader[2],
Checked = (string)reader[3]
});
}
}
}
catch (Exception ex) { ExceptionManager.Publish(ex); }
return Users;
}, CacheSection.RetrieveDescByKey(RetrieveUsersByRoleIDDataKey));
}
///
/// 通过部门ID保存当前授权用户(插入)
///
/// GroupID
/// 用户ID数组
///
public static bool SaveUsersByGroupId(int id, string userIds)
{
bool ret = false;
DataTable dt = new DataTable();
dt.Columns.Add("UserID", typeof(int));
dt.Columns.Add("GroupID", typeof(int));
if (!string.IsNullOrEmpty(userIds)) userIds.Split(',').ToList().ForEach(userId => dt.Rows.Add(userId, id));
using (TransactionPackage transaction = DBAccessManager.SqlDBAccess.BeginTransaction())
{
try
{
//删除用户角色表该角色所有的用户
string sql = "delete from UserGroup where GroupID = @GroupID";
using (DbCommand cmd = DBAccessManager.SqlDBAccess.CreateCommand(CommandType.Text, sql))
{
cmd.Parameters.Add(DBAccessManager.SqlDBAccess.CreateParameter("@GroupID", id, ParameterDirection.Input));
DBAccessManager.SqlDBAccess.ExecuteNonQuery(cmd, transaction);
//批插入用户角色表
using (SqlBulkCopy bulk = new SqlBulkCopy((SqlConnection)transaction.Transaction.Connection, SqlBulkCopyOptions.Default, (SqlTransaction)transaction.Transaction))
{
bulk.DestinationTableName = "UserGroup";
bulk.ColumnMappings.Add("UserID", "UserID");
bulk.ColumnMappings.Add("GroupID", "GroupID");
bulk.WriteToServer(dt);
transaction.CommitTransaction();
}
}
CacheCleanUtility.ClearCache(userIds: userIds, groupIds: id.ToString());
ret = true;
}
catch (Exception ex)
{
ExceptionManager.Publish(ex);
transaction.RollbackTransaction();
}
}
return ret;
}
///
///
///
///
public static bool RegisterUser(string userName, string displayName, string password,string description)
{
//TODO:未完成并通知管理员组有新用户注册,需要批复。
if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(displayName) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(description))
return false;
return SaveUser(new User() { UserName = userName, DisplayName = displayName, Password = password,Description=description });
}
}
}