📄 xmlmembershipprovider.cs
字号:
#region Using
using System;
using System.Xml;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration.Provider;
using System.Web.Security;
using System.Globalization;
using System.Web.Hosting;
using System.Web.Management;
using System.Security.Permissions;
using System.Web;
using System.Text;
using System.Security.Cryptography;
#endregion
namespace BlogEngine.Core.Providers
{
/// <summary>
///
/// </summary>
public class XmlMembershipProvider : MembershipProvider
{
private Dictionary<string, MembershipUser> _Users;
private string _XmlFileName;
#region Properties
// MembershipProvider Properties
/// <summary>
///
/// </summary>
public override string ApplicationName
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
/// <summary>
///
/// </summary>
public override bool EnablePasswordRetrieval
{
get { return false; }
}
/// <summary>
///
/// </summary>
public override bool EnablePasswordReset
{
get { return false; }
}
/// <summary>
///
/// </summary>
public override int MaxInvalidPasswordAttempts
{
get { return 5; }
}
/// <summary>
///
/// </summary>
public override int MinRequiredNonAlphanumericCharacters
{
get { return 0; }
}
/// <summary>
///
/// </summary>
public override int MinRequiredPasswordLength
{
get { return 8; }
}
/// <summary>
///
/// </summary>
public override int PasswordAttemptWindow
{
get { throw new NotSupportedException(); }
}
/// <summary>
///
/// </summary>
public override MembershipPasswordFormat PasswordFormat
{
get { return MembershipPasswordFormat.Clear; }
}
/// <summary>
///
/// </summary>
public override string PasswordStrengthRegularExpression
{
get { throw new NotSupportedException(); }
}
/// <summary>
///
/// </summary>
public override bool RequiresQuestionAndAnswer
{
get { return false; }
}
/// <summary>
///
/// </summary>
public override bool RequiresUniqueEmail
{
get { return false; }
}
#endregion
#region Supported methods
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <param name="config"></param>
public override void Initialize(string name, NameValueCollection config)
{
if (config == null)
throw new ArgumentNullException("config");
if (String.IsNullOrEmpty(name))
name = "XmlMembershipProvider";
if (string.IsNullOrEmpty(config["description"]))
{
config.Remove("description");
config.Add("description", "XML membership provider");
}
base.Initialize(name, config);
// Initialize _XmlFileName and make sure the path
// is app-relative
string path = config["xmlFileName"];
if (String.IsNullOrEmpty(path))
path = BlogSettings.Instance.StorageLocation + "users.xml";
if (!VirtualPathUtility.IsAppRelative(path))
throw new ArgumentException
("xmlFileName must be app-relative");
string fullyQualifiedPath = VirtualPathUtility.Combine
(VirtualPathUtility.AppendTrailingSlash
(HttpRuntime.AppDomainAppVirtualPath), path);
_XmlFileName = HostingEnvironment.MapPath(fullyQualifiedPath);
config.Remove("xmlFileName");
// Make sure we have permission to read the XML data source and
// throw an exception if we don't
FileIOPermission permission = new FileIOPermission(FileIOPermissionAccess.Write, _XmlFileName);
permission.Demand();
// Throw an exception if unrecognized attributes remain
if (config.Count > 0)
{
string attr = config.GetKey(0);
if (!String.IsNullOrEmpty(attr))
throw new ProviderException("Unrecognized attribute: " + attr);
}
}
/// <summary>
/// Returns true if the username and password match an exsisting user.
/// </summary>
public override bool ValidateUser(string username, string password)
{
if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password))
return false;
try
{
ReadMembershipDataStore();
// Validate the user name and password
MembershipUser user;
if (_Users.TryGetValue(username, out user))
{
if (user.Comment == password) // Case-sensitive
{
//user.LastLoginDate = DateTime.Now;
//UpdateUser(user);
return true;
}
}
return false;
}
catch (Exception)
{
return false;
}
}
/// <summary>
/// Retrieves a user based on his/hers username.
/// the userIsOnline parameter is ignored.
/// </summary>
public override MembershipUser GetUser(string username, bool userIsOnline)
{
if (String.IsNullOrEmpty(username))
return null;
ReadMembershipDataStore();
// Retrieve the user from the data source
MembershipUser user;
if (_Users.TryGetValue(username, out user))
return user;
return null;
}
/// <summary>
/// Retrieves a collection of all the users.
/// This implementation ignores pageIndex and pageSize,
/// and it doesn't sort the MembershipUser objects returned.
/// </summary>
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
ReadMembershipDataStore();
MembershipUserCollection users = new MembershipUserCollection();
foreach (KeyValuePair<string, MembershipUser> pair in _Users)
{
users.Add(pair.Value);
}
totalRecords = users.Count;
return users;
}
/// <summary>
/// Changes a users password.
/// </summary>
public override bool ChangePassword(string username, string oldPassword, string newPassword)
{
XmlDocument doc = new XmlDocument();
doc.Load(_XmlFileName);
XmlNodeList nodes = doc.GetElementsByTagName("User");
foreach (XmlNode node in nodes)
{
if (node["UserName"].InnerText.Equals(username, StringComparison.OrdinalIgnoreCase)
|| node["Password"].InnerText.Equals(oldPassword, StringComparison.OrdinalIgnoreCase))
{
node["Password"].InnerText = newPassword;
doc.Save(_XmlFileName);
return true;
}
}
return false;
}
/// <summary>
/// Creates a new user store he/she in the XML file
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -