📄 userutility.cs
字号:
namespace ASPNET.StarterKit.Communities {
using System;
using System.Collections;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Security.Principal;
using ASPNET.StarterKit.Communities;
//*********************************************************************
//
// UserUtility Class
//
// Contains static methods for working with community users.
//
//*********************************************************************
public class UserUtility {
//*********************************************************************
//
// GetAllRoles Method
//
// Retrieves a list of all user roles from the cache, if that
// failes, the roles are retrieved from the database.
//
//*********************************************************************
public static ArrayList GetAllRoles() {
ArrayList colRoles = new ArrayList();
DataTable dtblRoles = GetAllRolesFromDB().Tables[0];
foreach (DataRow roleRow in dtblRoles.Rows)
colRoles.Add((string)roleRow["Role_RoleName"]);
return colRoles;
}
//*********************************************************************
//
// GetAllRolesFromDB Method
//
// Retrieves a list of all user roles from the database.
//
//*********************************************************************
private static DataSet GetAllRolesFromDB() {
SqlDataAdapter dadGetRoles = new SqlDataAdapter( "Community_UsersGetAllRoles", CommunityGlobals.ConnectionString );
dadGetRoles.SelectCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
dadGetRoles.SelectCommand.Parameters.Add( "@communityID", CommunityGlobals.CommunityID );
DataSet dstRoles = new DataSet();
dadGetRoles.Fill( dstRoles );
return dstRoles;
}
//*********************************************************************
//
// GetAllUserRoles Method
//
// Retrieves a list of all user roles excluding system roles
// such as the Everyone and Authenticated roles.
//
//*********************************************************************
public static DataSet GetAllUserRoles() {
SqlDataAdapter dadGetRoles = new SqlDataAdapter( "Community_UsersGetAllUserRoles", CommunityGlobals.ConnectionString );
dadGetRoles.SelectCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
dadGetRoles.SelectCommand.Parameters.Add( "@communityID", CommunityGlobals.CommunityID );
DataSet dstRoles = new DataSet();
dadGetRoles.Fill( dstRoles );
return dstRoles;
}
//*********************************************************************
//
// AddRole Method
//
// Adds a new role to the database.
//
//*********************************************************************
public static void AddRole(string roleName, string description) {
SqlConnection conPortal = new SqlConnection(CommunityGlobals.ConnectionString);
SqlCommand cmdAdd = new SqlCommand("Community_UsersAddRole", conPortal);
cmdAdd.CommandType = CommandType.StoredProcedure;
cmdAdd.Parameters.Add("@communityID", CommunityGlobals.CommunityID);
cmdAdd.Parameters.Add("@roleName", roleName);
cmdAdd.Parameters.Add("@roleDescription", description);
conPortal.Open();
cmdAdd.ExecuteNonQuery();
conPortal.Close();
}
//*********************************************************************
//
// LoginUser Method
//
// Attempts to login a user with a certain username and password.
//
//*********************************************************************
public static int LoginUser(string username, string password) {
// Create Instance of Connection and Command Object
SqlConnection conPortal = new SqlConnection(CommunityGlobals.ConnectionString);
SqlCommand cmdLoginUser = new SqlCommand("Community_UsersLoginUser", conPortal);
// Mark the Command as a SPROC
cmdLoginUser.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
cmdLoginUser.Parameters.Add("@RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cmdLoginUser.Parameters.Add("@communityID", CommunityGlobals.CommunityID );
cmdLoginUser.Parameters.Add("@username", username );
cmdLoginUser.Parameters.Add("@password", password );
// Execute the command
conPortal.Open();
cmdLoginUser.ExecuteNonQuery();
int retVal = (int)(cmdLoginUser.Parameters["@RETURN_VALUE"].Value);
conPortal.Close();
return retVal;
}
//*********************************************************************
// GetUserRoles Method
//
//
// Connects to the user role's datasource, retrieves all the roles a given
// user belongs to, and add them to the curret IPrincipal. The roles are retrieved
// from the datasource or from an encrypted cookie.
//
//***********************************************************************
public static void GetUserRoles() {
HttpContext Context = HttpContext.Current;
string[] userRoles = null;
string formattedUserRoles;
// Is the request authenticated?
if (!Context.Request.IsAuthenticated)
return;
// Get the roles this user is in
string rolesCookie = "ASPNETCommunities" + CommunityGlobals.CommunityID;
if ((Context.Request.Cookies[rolesCookie] == null) || (Context.Request.Cookies[rolesCookie].Value == "")) {
userRoles = GetUserRolesFromDB(Context.User.Identity.Name);
// Format string array
formattedUserRoles = "";
foreach (string role in userRoles) {
formattedUserRoles += role;
formattedUserRoles += ";";
}
// Create authentication ticket
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // version
Context.User.Identity.Name, // user name
DateTime.Now, // issue time
DateTime.Now.AddHours(1), // expires every hour
false, // don't persist cookie
formattedUserRoles // roles
);
// Encrypt the ticket
String cookieStr = FormsAuthentication.Encrypt(ticket);
// Send the cookie to the client
Context.Response.Cookies[rolesCookie].Value = cookieStr;
//Context.Response.Cookies[rolesCookie].Path = CommunityGlobals.AppPath;
Context.Response.Cookies[rolesCookie].Expires = DateTime.Now.AddMinutes(5);
} else {
// Get roles from roles cookie
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[rolesCookie].Value);
//convert the string representation of the role data into a string array
ArrayList rolesArrayList = new ArrayList();
foreach (String role in ticket.UserData.Split( new char[] {';'} )) {
if (role != "")
rolesArrayList.Add(role);
}
userRoles = (String[]) rolesArrayList.ToArray(typeof(String));
}
// Add our own custom principal to the request containing the roles in the auth ticket
Context.User = new GenericPrincipal(Context.User.Identity, userRoles);
}
//*********************************************************************
//
// GetUserRolesFromDB Method
//
// Retrieves a list of roles for a particular user from the
// database.
//
//*********************************************************************
public static String[] GetUserRolesFromDB(string username) {
// Create Instance of Connection and Command Object
SqlConnection myConnection = new SqlConnection(CommunityGlobals.ConnectionString);
SqlCommand myCommand = new SqlCommand("Community_UsersGetRolesByUser", myConnection);
// Mark the Command as a SPROC
myCommand.CommandType = CommandType.StoredProcedure;
// Add Parameters to SPROC
myCommand.Parameters.Add("@communityID", CommunityGlobals.CommunityID);
myCommand.Parameters.Add("@username", SqlDbType.NVarChar, 50).Value = username;
// Open the database connection and execute the command
SqlDataReader dr;
myConnection.Open();
dr = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
// create a String array from the data
ArrayList userRoles = new ArrayList();
while (dr.Read()) {
userRoles.Add(dr["UserRoles_RoleName"]);
}
dr.Close();
// Return the String array of roles
return (string[]) userRoles.ToArray(typeof(String));
}
//*********************************************************************
//
// SignOut Method
//
// Logout a user by destroying the user cookie.
//
//*********************************************************************
public static void SignOut() {
HttpContext Context = HttpContext.Current;
// Sign Out
FormsAuthentication.SignOut();
// Invalidate roles token
string rolesCookie = "ASPNETCommunities" + CommunityGlobals.CommunityID;
Context.Response.Cookies[rolesCookie].Value = null;
Context.Response.Cookies[rolesCookie].Expires = new System.DateTime(1999, 10, 12);
}
//*********************************************************************
//
// UpdateUserRoles Method
//
// Modifies the roles associated with a user in the database.
//
//*********************************************************************
public static void UpdateUserRoles(string username, string[] roles) {
SqlConnection conPortal = new SqlConnection(CommunityGlobals.ConnectionString);
// initialize delete command
SqlCommand cmdDelete = new SqlCommand("Community_UsersDeleteUserRoles", conPortal);
cmdDelete.CommandType = CommandType.StoredProcedure;
cmdDelete.Parameters.Add("@communityID", CommunityGlobals.CommunityID);
cmdDelete.Parameters.Add("@username", username);
// initialize update command
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -