Guest User

Untitled

a guest
Jan 24th, 2018
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 20.80 KB | None | 0 0
  1. public class UserProvider : MembershipProvider
  2. {
  3. private int maxInvalidPasswordAttempts;
  4. private int passwordAttemptWindow;
  5. private int minRequiredNonalphanumericCharacters;
  6. private int minRequiredPasswordLength;
  7. private bool enablePasswordReset;
  8. private string passwordStrengthRegularExpression;
  9. private int minRequiredNonAlphanumericCharacters;
  10. private bool enablePasswordRetrieval;
  11. private bool requiresQuestionAndAnswer;
  12. private MembershipPasswordFormat passwordFormat;
  13. private bool requiresUniqueEmail;
  14.  
  15. public override void Initialize(string name, System.Collections.Specialized.NameValueCollection config)
  16. {
  17. if (config == null)
  18. throw new ArgumentNullException("config");
  19.  
  20.  
  21. ApplicationName = GetConfigValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
  22. maxInvalidPasswordAttempts = Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5"));
  23. passwordAttemptWindow = Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10"));
  24. minRequiredNonalphanumericCharacters = Convert.ToInt32(GetConfigValue(config["minRequiredNonalphanumericCharacters"], "1"));
  25. minRequiredPasswordLength = Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "6"));
  26. enablePasswordReset = Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true"));
  27. passwordStrengthRegularExpression = Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], ""));
  28.  
  29. base.Initialize(name, config);
  30. }
  31.  
  32. #region Overrides of MembershipProvider
  33.  
  34. #region Methods
  35.  
  36. /// <summary>
  37. /// Adds a new membership user to the data source.
  38. /// </summary>
  39. /// <returns>
  40. /// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the information for the newly created user.
  41. /// </returns>
  42. /// <param name="username">The user name for the new user. </param><param name="password">The password for the new user. </param><param name="email">The e-mail address for the new user.</param><param name="passwordQuestion">The password question for the new user.</param><param name="passwordAnswer">The password answer for the new user</param><param name="isApproved">Whether or not the new user is approved to be validated.</param><param name="providerUserKey">The unique identifier from the membership data source for the user.</param><param name="status">A <see cref="T:System.Web.Security.MembershipCreateStatus"/> enumeration value indicating whether the user was created successfully.</param>
  43. public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
  44. {
  45. return CreateUser(username, password, email, passwordQuestion, passwordAnswer, isApproved, Gender.Unknown, out status);
  46. }
  47.  
  48. public User CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, Gender gender, out MembershipCreateStatus status)
  49. {
  50. var args = new ValidatePasswordEventArgs(username, password, true);
  51. OnValidatingPassword(args);
  52.  
  53. if (args.Cancel)
  54. {
  55. status = MembershipCreateStatus.InvalidPassword;
  56. return null;
  57. }
  58.  
  59. if (requiresUniqueEmail && GetUserNameByEmail(email) != "")
  60. {
  61. status = MembershipCreateStatus.DuplicateEmail;
  62. return null;
  63. }
  64.  
  65. var user = new User(username, gender, password, email, passwordQuestion, isApproved, false);
  66.  
  67. using (var db = new DataContext())
  68. {
  69. try
  70. {
  71. db.Users.Add(user);
  72. status = db.SaveChanges() > 0
  73. ? MembershipCreateStatus.Success
  74. : MembershipCreateStatus.UserRejected;
  75. return user;
  76. }
  77. catch
  78. {
  79. status = MembershipCreateStatus.ProviderError;
  80. }
  81.  
  82. return null;
  83. }
  84. }
  85.  
  86. /// <summary>
  87. /// Processes a request to update the password question and answer for a membership user.
  88. /// </summary>
  89. /// <returns>
  90. /// true if the password question and answer are updated successfully; otherwise, false.
  91. /// </returns>
  92. /// <param name="username">The user to change the password question and answer for. </param><param name="password">The password for the specified user. </param><param name="newPasswordQuestion">The new password question for the specified user. </param><param name="newPasswordAnswer">The new password answer for the specified user. </param>
  93. public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
  94. {
  95. throw new NotImplementedException();
  96. }
  97.  
  98. /// <summary>
  99. /// Gets the password for the specified user name from the data source.
  100. /// </summary>
  101. /// <returns>
  102. /// The password for the specified user name.
  103. /// </returns>
  104. /// <param name="username">The user to retrieve the password for. </param><param name="answer">The password answer for the user. </param>
  105. public override string GetPassword(string username, string answer)
  106. {
  107. throw new NotImplementedException();
  108. }
  109.  
  110. /// <summary>
  111. /// Processes a request to update the password for a membership user.
  112. /// </summary>
  113. /// <returns>
  114. /// true if the password was updated successfully; otherwise, false.
  115. /// </returns>
  116. /// <param name="username">The user to update the password for. </param><param name="oldPassword">The current password for the specified user. </param><param name="newPassword">The new password for the specified user. </param>
  117. public override bool ChangePassword(string username, string oldPassword, string newPassword)
  118. {
  119. throw new NotImplementedException();
  120. }
  121.  
  122. /// <summary>
  123. /// Resets a user's password to a new, automatically generated password.
  124. /// </summary>
  125. /// <returns>
  126. /// The new password for the specified user.
  127. /// </returns>
  128. /// <param name="username">The user to reset the password for. </param><param name="answer">The password answer for the specified user. </param>
  129. public override string ResetPassword(string username, string answer)
  130. {
  131. throw new NotImplementedException();
  132. }
  133.  
  134. /// <summary>
  135. /// Updates information about a user in the data source.
  136. /// </summary>
  137. /// <param name="user">A <see cref="T:System.Web.Security.MembershipUser"/> object that represents the user to update and the updated information for the user. </param>
  138. public override void UpdateUser(MembershipUser user)
  139. {
  140. using (var db = new DataContext())
  141. {
  142. var userDB = (from u in db.Users
  143. where u.ProviderUserKey == user.ProviderUserKey
  144. select u).SingleOrDefault();
  145. userDB.IsApproved = user.IsApproved;
  146. userDB.LastLoginDate = user.LastLoginDate;
  147.  
  148. db.SaveChanges();
  149. }
  150. }
  151.  
  152. /// <summary>
  153. /// Verifies that the specified user name and password exist in the data source.
  154. /// </summary>
  155. /// <returns>
  156. /// true if the specified username and password are valid; otherwise, false.
  157. /// </returns>
  158. /// <param name="email">The email of the user to validate. </param>
  159. /// <param name="password">The password for the specified user. </param>
  160. public override bool ValidateUser(string email, string password)
  161. {
  162. using (var db = new DataContext())
  163. {
  164. var user = (from u in db.Users
  165. where u.Email == email && u.Password == password
  166. select u).SingleOrDefault();
  167.  
  168. return user != null && (user.IsApproved && !user.IsLockedOut);
  169. }
  170. }
  171.  
  172. /// <summary>
  173. /// Clears a lock so that the membership user can be validated.
  174. /// </summary>
  175. /// <returns>
  176. /// true if the membership user was successfully unlocked; otherwise, false.
  177. /// </returns>
  178. /// <param name="userName">The membership user whose lock status you want to clear.</param>
  179. public override bool UnlockUser(string userName)
  180. {
  181. throw new NotImplementedException();
  182. }
  183.  
  184. /// <summary>
  185. /// Gets user information from the data source based on the unique identifier for the membership user. Provides an option to update the last-activity date/time stamp for the user.
  186. /// </summary>
  187. /// <returns>
  188. /// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the specified user's information from the data source.
  189. /// </returns>
  190. /// <param name="providerUserKey">The unique identifier for the membership user to get information for.</param><param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user.</param>
  191. public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
  192. {
  193. return GetUser(providerUserKey);
  194. }
  195.  
  196. public User GetUser(object providerUserKey)
  197. {
  198. using (var db = new DataContext())
  199. {
  200. var user = (from u in db.Users
  201. where u.ProviderUserKey == providerUserKey
  202. select u).SingleOrDefault();
  203. return user;
  204. }
  205. }
  206.  
  207. /// <summary>
  208. /// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user.
  209. /// </summary>
  210. /// <returns>
  211. /// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the specified user's information from the data source.
  212. /// </returns>
  213. /// <param name="username">The name of the user to get information for. </param><param name="userIsOnline">true to update the last-activity date/time stamp for the user; false to return user information without updating the last-activity date/time stamp for the user. </param>
  214. public override MembershipUser GetUser(string username, bool userIsOnline)
  215. {
  216. using (var db = new DataContext())
  217. {
  218. var user = (from u in db.Users
  219. where u.UserName == username
  220. select u).SingleOrDefault();
  221. return user;
  222. }
  223. }
  224.  
  225. /// <summary>
  226. /// Gets information from the data source for a user. Provides an option to update the last-activity date/time stamp for the user.
  227. /// </summary>
  228. /// <returns>
  229. /// A <see cref="T:System.Web.Security.MembershipUser"/> object populated with the specified user's information from the data source.
  230. /// </returns>
  231. /// <param name="email">The email of the user to get information for. </param>
  232. public User GetUser(string email)
  233. {
  234. using (var db = new DataContext())
  235. {
  236. var user = (from u in db.Users
  237. where u.Email == email
  238. select u).SingleOrDefault();
  239. return user;
  240. }
  241. }
  242.  
  243. /// <summary>
  244. /// Gets the user name associated with the specified e-mail address.
  245. /// </summary>
  246. /// <returns>
  247. /// The user name associated with the specified e-mail address. If no match is found, return null.
  248. /// </returns>
  249. /// <param name="email">The e-mail address to search for. </param>
  250. public override string GetUserNameByEmail(string email)
  251. {
  252. using (var db = new DataContext())
  253. {
  254. return (from u in db.Users
  255. where u.Email == email
  256. select u.UserName).SingleOrDefault();
  257. }
  258. }
  259.  
  260. /// <summary>
  261. /// Removes a user from the membership data source.
  262. /// </summary>
  263. /// <returns>
  264. /// true if the user was successfully deleted; otherwise, false.
  265. /// </returns>
  266. /// <param name="username">The name of the user to delete.</param><param name="deleteAllRelatedData">true to delete data related to the user from the database; false to leave data related to the user in the database.</param>
  267. public override bool DeleteUser(string username, bool deleteAllRelatedData)
  268. {
  269. throw new NotImplementedException();
  270. }
  271.  
  272. /// <summary>
  273. /// Gets a collection of all the users in the data source in pages of data.
  274. /// </summary>
  275. /// <returns>
  276. /// A <see cref="T:System.Web.Security.MembershipUserCollection"/> collection that contains a page of <paramref name="pageSize"/><see cref="T:System.Web.Security.MembershipUser"/> objects beginning at the page specified by <paramref name="pageIndex"/>.
  277. /// </returns>
  278. /// <param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex"/> is zero-based.</param><param name="pageSize">The size of the page of results to return.</param><param name="totalRecords">The total number of matched users.</param>
  279. public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
  280. {
  281. using (var db = new DataContext())
  282. {
  283. var users = from u in db.Users
  284. select u;
  285.  
  286. var returnList = new MembershipUserCollection();
  287. foreach (var user in users)
  288. returnList.Add(user);
  289. totalRecords = returnList.Count;
  290. return returnList;
  291. }
  292. }
  293.  
  294. /// <summary>
  295. /// Gets the number of users currently accessing the application.
  296. /// </summary>
  297. /// <returns>
  298. /// The number of users currently accessing the application.
  299. /// </returns>
  300. public override int GetNumberOfUsersOnline()
  301. {
  302. throw new NotImplementedException();
  303. }
  304.  
  305. /// <summary>
  306. /// Gets a collection of membership users where the user name contains the specified user name to match.
  307. /// </summary>
  308. /// <returns>
  309. /// A <see cref="T:System.Web.Security.MembershipUserCollection"/> collection that contains a page of <paramref name="pageSize"/><see cref="T:System.Web.Security.MembershipUser"/> objects beginning at the page specified by <paramref name="pageIndex"/>.
  310. /// </returns>
  311. /// <param name="usernameToMatch">The user name to search for.</param><param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex"/> is zero-based.</param><param name="pageSize">The size of the page of results to return.</param><param name="totalRecords">The total number of matched users.</param>
  312. public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
  313. {
  314. using (var db = new DataContext())
  315. {
  316. var users = (from u in db.Users
  317. where u.UserName.Contains(usernameToMatch)
  318. select u).Skip(pageIndex).Take(pageSize);
  319.  
  320. var returnList = new MembershipUserCollection();
  321. foreach (var user in users)
  322. returnList.Add(user);
  323. totalRecords = returnList.Count;
  324. return returnList;
  325.  
  326. }
  327. }
  328.  
  329. /// <summary>
  330. /// Gets a collection of membership users where the e-mail address contains the specified e-mail address to match.
  331. /// </summary>
  332. /// <returns>
  333. /// A <see cref="T:System.Web.Security.MembershipUserCollection"/> collection that contains a page of <paramref name="pageSize"/><see cref="T:System.Web.Security.MembershipUser"/> objects beginning at the page specified by <paramref name="pageIndex"/>.
  334. /// </returns>
  335. /// <param name="emailToMatch">The e-mail address to search for.</param><param name="pageIndex">The index of the page of results to return. <paramref name="pageIndex"/> is zero-based.</param><param name="pageSize">The size of the page of results to return.</param><param name="totalRecords">The total number of matched users.</param>
  336. public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
  337. {
  338. using (var db = new DataContext())
  339. {
  340. var users = (from u in db.Users
  341. where u.Email.Contains(emailToMatch)
  342. select u).Skip(pageIndex).Take(pageSize).ToList();
  343. var msc = new MembershipUserCollection();
  344. foreach (var user in users)
  345. msc.Add(user);
  346. totalRecords = users.Count;
  347. return msc;
  348. }
  349.  
  350. }
  351.  
  352. #endregion
  353.  
  354. #region Properties
  355.  
  356. /// <summary>
  357. /// Indicates whether the membership provider is configured to allow users to retrieve their passwords.
  358. /// </summary>
  359. /// <returns>
  360. /// true if the membership provider is configured to support password retrieval; otherwise, false. The default is false.
  361. /// </returns>
  362. public override bool EnablePasswordRetrieval
  363. {
  364. get { return enablePasswordRetrieval; }
  365. }
  366.  
  367. /// <summary>
  368. /// Indicates whether the membership provider is configured to allow users to reset their passwords.
  369. /// </summary>
  370. /// <returns>
  371. /// true if the membership provider supports password reset; otherwise, false. The default is true.
  372. /// </returns>
  373. public override bool EnablePasswordReset
  374. {
  375. get { return enablePasswordReset; }
  376. }
  377.  
  378. /// <summary>
  379. /// Gets a value indicating whether the membership provider is configured to require the user to answer a password question for password reset and retrieval.
  380. /// </summary>
  381. /// <returns>
  382. /// true if a password answer is required for password reset and retrieval; otherwise, false. The default is true.
  383. /// </returns>
  384. public override bool RequiresQuestionAndAnswer
  385. {
  386. get { return requiresQuestionAndAnswer; }
  387. }
  388.  
  389. /// <summary>
  390. /// The name of the application using the custom membership provider.
  391. /// </summary>
  392. /// <returns>
  393. /// The name of the application using the custom membership provider.
  394. /// </returns>
  395. public override string ApplicationName { get; set; }
  396.  
  397. /// <summary>
  398. /// Gets the number of invalid password or password-answer attempts allowed before the membership user is locked out.
  399. /// </summary>
  400. /// <returns>
  401. /// The number of invalid password or password-answer attempts allowed before the membership user is locked out.
  402. /// </returns>
  403. public override int MaxInvalidPasswordAttempts { get { return maxInvalidPasswordAttempts; } }
  404.  
  405. /// <summary>
  406. /// Gets the number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.
  407. /// </summary>
  408. /// <returns>
  409. /// The number of minutes in which a maximum number of invalid password or password-answer attempts are allowed before the membership user is locked out.
  410. /// </returns>
  411. public override int PasswordAttemptWindow
  412. {
  413. get { return passwordAttemptWindow; }
  414. }
  415.  
  416. /// <summary>
  417. /// Gets a value indicating whether the membership provider is configured to require a unique e-mail address for each user name.
  418. /// </summary>
  419. /// <returns>
  420. /// true if the membership provider requires a unique e-mail address; otherwise, false. The default is true.
  421. /// </returns>
  422. public override bool RequiresUniqueEmail
  423. {
  424. get { return requiresUniqueEmail; }
  425. }
  426.  
  427. /// <summary>
  428. /// Gets a value indicating the format for storing passwords in the membership data store.
  429. /// </summary>
  430. /// <returns>
  431. /// One of the <see cref="T:System.Web.Security.MembershipPasswordFormat"/> values indicating the format for storing passwords in the data store.
  432. /// </returns>
  433. public override MembershipPasswordFormat PasswordFormat
  434. {
  435. get { return passwordFormat; }
  436. }
  437.  
  438. /// <summary>
  439. /// Gets the minimum length required for a password.
  440. /// </summary>
  441. /// <returns>
  442. /// The minimum length required for a password.
  443. /// </returns>
  444. public override int MinRequiredPasswordLength
  445. {
  446. get { return minRequiredPasswordLength; }
  447. }
  448.  
  449. /// <summary>
  450. /// Gets the minimum number of special characters that must be present in a valid password.
  451. /// </summary>
  452. /// <returns>
  453. /// The minimum number of special characters that must be present in a valid password.
  454. /// </returns>
  455. public override int MinRequiredNonAlphanumericCharacters
  456. {
  457. get { return minRequiredNonAlphanumericCharacters; }
  458. }
  459.  
  460. /// <summary>
  461. /// Gets the regular expression used to evaluate a password.
  462. /// </summary>
  463. /// <returns>
  464. /// A regular expression used to evaluate a password.
  465. /// </returns>
  466. public override string PasswordStrengthRegularExpression
  467. {
  468. get { return passwordStrengthRegularExpression; }
  469. }
  470.  
  471. #endregion
  472.  
  473. #endregion
  474.  
  475. private string GetConfigValue(string configValue, string defaultValue)
  476. {
  477. return string.IsNullOrEmpty(configValue) ? defaultValue : configValue;
  478. }
  479. }
Add Comment
Please, Sign In to add comment