PageRenderTime 55ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/IntellectShop.solution/IntellectShop.Web2.Hardware/Controllers/AccountController.cs

#
C# | 453 lines | 370 code | 51 blank | 32 comment | 44 complexity | 5c86842dc8be511f6aad97e28071b6f6 MD5 | raw file
Possible License(s): LGPL-3.0, GPL-2.0, CC-BY-SA-3.0
  1. namespace IntellectShop.Web2.Hardware.Controllers
  2. {
  3. using System;
  4. using System.Configuration;
  5. using System.Security.Principal;
  6. using System.Web.Mvc;
  7. using System.Web.Routing;
  8. using System.Web.Security;
  9. using IntellectShop.Web2.Hardware.Models;
  10. using IntellectShop.Web2.Hardware.ViewModels;
  11. using IntellectShop.Common;
  12. [IntellectShop.Web2.Hardware.Code.NoCache]
  13. [IntellectShop.Web2.Hardware.Code.HandleErrorWithELMAH]
  14. public class AccountController : Controller
  15. {
  16. public IFormsAuthenticationService FormsService { get; private set; }
  17. public IMembershipService MembershipService { get; private set; }
  18. public IRoleService RoleService { get; private set; }
  19. protected override void Initialize(RequestContext requestContext)
  20. {
  21. if (this.FormsService == null) { this.FormsService = new FormsAuthenticationService(); }
  22. if (this.MembershipService == null) { this.MembershipService = new AccountMembershipService(); }
  23. if (this.RoleService == null) { this.RoleService = new RoleService(); }
  24. base.Initialize(requestContext);
  25. }
  26. // **************************************
  27. // URL: /Account/LogOn
  28. // **************************************
  29. public ActionResult LogOn()
  30. {
  31. return View();
  32. }
  33. [HttpPost]
  34. public ActionResult LogOn(LogOnModel model, string returnUrl)
  35. {
  36. if (ModelState.IsValid)
  37. {
  38. if (this.MembershipService.ValidateUser(model.UserName, model.Password))
  39. {
  40. this.MigrateShoppingCart(model.UserName);
  41. this.FormsService.SignIn(model.UserName, model.RememberMe);
  42. if (!String.IsNullOrEmpty(returnUrl))
  43. {
  44. return Redirect(returnUrl);
  45. }
  46. else
  47. {
  48. return RedirectToAction("AboutCompany", "Home");
  49. }
  50. }
  51. else
  52. {
  53. ModelState.AddModelError("", "Имя пользователя или пароль некорректны.");
  54. }
  55. }
  56. // If we got this far, something failed, redisplay form
  57. return View(model);
  58. }
  59. // **************************************
  60. // URL: /Account/LogOff
  61. // **************************************
  62. public ActionResult LogOff()
  63. {
  64. this.FormsService.SignOut();
  65. return Redirect(Request.UrlReferrer.ToString());
  66. }
  67. // **************************************
  68. // URL: /Account/Register
  69. // **************************************
  70. public ActionResult Register()
  71. {
  72. ViewData["PasswordLength"] = this.MembershipService.MinPasswordLength;
  73. ViewData["NumNonAlphaNumerics"] = this.MembershipService.MinNonAplhaNumerics;
  74. return View();
  75. }
  76. [HttpPost]
  77. public ActionResult Register(RegisterModel model)
  78. {
  79. if (ModelState.IsValid)
  80. {
  81. // Attempt to register the user
  82. MembershipCreateStatus createStatus = this.MembershipService.CreateUser(model.UserName, model.Password, model.Email);
  83. if (createStatus == MembershipCreateStatus.Success)
  84. {
  85. this.PublishAdministratorRole(model.UserName);
  86. this.MigrateShoppingCart(model.UserName);
  87. this.FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
  88. return RedirectToAction("AboutCompany", "Home");
  89. }
  90. else
  91. {
  92. ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
  93. }
  94. }
  95. // If we got this far, something failed, redisplay form
  96. ViewData["PasswordLength"] = this.MembershipService.MinPasswordLength;
  97. ViewData["NumNonAlphaNumerics"] = this.MembershipService.MinNonAplhaNumerics;
  98. return View(model);
  99. }
  100. private void PublishAdministratorRole(string userName)
  101. {
  102. //тут надо создать роль Administrator, если ее нет
  103. if (!this.RoleService.RoleExists(Globals.AdministratorRoleName))
  104. {
  105. this.RoleService.CreateRole(Globals.AdministratorRoleName);
  106. }
  107. //проверим есть ли user в списке админови выдадим ему эту роль, если он там
  108. string administrators = ConfigurationManager.AppSettings["Administrators"];
  109. if (!String.IsNullOrEmpty(administrators))
  110. {
  111. foreach (var item in administrators.Split(' ', ','))
  112. {
  113. if (!String.IsNullOrEmpty(item))
  114. {
  115. if (item.Equals(userName, StringComparison.InvariantCultureIgnoreCase))
  116. {
  117. this.RoleService.AddUserToRole(userName, Globals.AdministratorRoleName);
  118. }
  119. }
  120. }
  121. }
  122. }
  123. private void MigrateShoppingCart(string UserName)
  124. {
  125. // Associate shopping cart items with logged-in user
  126. var cart = Common.Cart.CreateCart(this.HttpContext);
  127. cart.MigrateCart(UserName);
  128. Common.Globals.SetOwnerID(this.HttpContext, UserName);
  129. }
  130. // **************************************
  131. // URL: /Account/ChangePassword
  132. // **************************************
  133. [Authorize]
  134. public ActionResult ChangePassword()
  135. {
  136. ViewData["PasswordLength"] = this.MembershipService.MinPasswordLength;
  137. ViewData["NumNonAlphaNumerics"] = this.MembershipService.MinNonAplhaNumerics;
  138. return View();
  139. }
  140. [Authorize]
  141. [HttpPost]
  142. public ActionResult ChangePassword(ChangePasswordModel model)
  143. {
  144. if (ModelState.IsValid)
  145. {
  146. if (this.MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
  147. {
  148. return RedirectToAction("ChangePasswordSuccess");
  149. }
  150. else
  151. {
  152. ModelState.AddModelError("", "Текущий пароль неверный или новый пароль неправильный.");
  153. }
  154. }
  155. // If we got this far, something failed, redisplay form
  156. ViewData["PasswordLength"] = this.MembershipService.MinPasswordLength;
  157. ViewData["NumNonAlphaNumerics"] = this.MembershipService.MinNonAplhaNumerics;
  158. return View(model);
  159. }
  160. // **************************************
  161. // URL: /Account/ChangePasswordSuccess
  162. // **************************************
  163. public ActionResult ChangePasswordSuccess()
  164. {
  165. return View();
  166. }
  167. // ***************************************
  168. // Admin action
  169. // ***************************************
  170. [Authorize(Roles = Globals.AdministratorRoleName)]
  171. public ActionResult Admin()
  172. {
  173. AdminViewModel viewModel = new AdminViewModel
  174. {
  175. Users = this.MembershipService.GetAllUsers(),
  176. Roles = this.RoleService.GetAllRoles()
  177. };
  178. return View(viewModel);
  179. }
  180. [Authorize(Roles = Globals.AdministratorRoleName)]
  181. public ActionResult DeleteRole(string role)
  182. {
  183. if (RoleService.RoleExists(role))
  184. {
  185. // Cannot delete the Admin role
  186. //
  187. if (role == Globals.AdministratorRoleName)
  188. {
  189. TempData["RoleError"] = "Не могу удалить роль: '" + Globals.AdministratorRoleName + "'.";
  190. }
  191. else
  192. {
  193. // Remove the role from all users
  194. //
  195. try
  196. {
  197. string[] userNames = RoleService.GetUsersInRole(role);
  198. if (userNames != null && userNames.Length > 0)
  199. {
  200. RoleService.RemoveUsersFromRole(userNames, role);
  201. }
  202. // Delete the role
  203. //
  204. try
  205. {
  206. if (!RoleService.DeleteRole(role, true))
  207. {
  208. TempData["RoleError"] = "Не могу удалить роль.";
  209. }
  210. }
  211. catch (Exception)
  212. {
  213. TempData["RoleError"] = "Не могу удалить роль.";
  214. }
  215. }
  216. catch (Exception)
  217. {
  218. TempData["RoleError"] = "Не могу удалить пользователей из роли.";
  219. }
  220. }
  221. }
  222. return RedirectToAction("Admin");
  223. }
  224. [Authorize(Roles = Globals.AdministratorRoleName)]
  225. public ActionResult AddRole(string newRole)
  226. {
  227. if (String.IsNullOrEmpty(newRole))
  228. {
  229. TempData["RoleError"] = "Название роли пустое.";
  230. }
  231. else if (RoleService.RoleExists(newRole))
  232. {
  233. TempData["RoleError"] = "Роль уже существует.";
  234. }
  235. else
  236. {
  237. RoleService.CreateRole(newRole);
  238. }
  239. return RedirectToAction("Admin");
  240. }
  241. [Authorize(Roles = Globals.AdministratorRoleName)]
  242. public ActionResult ToggleRole(string role, string userName)
  243. {
  244. try
  245. {
  246. MembershipUser user = MembershipService.GetUser(userName, false);
  247. if (user != null)
  248. {
  249. if (RoleService.RoleExists(role))
  250. {
  251. if (role == Globals.AdministratorRoleName && userName == HttpContext.User.Identity.Name)
  252. {
  253. TempData["UserError"] = "Нельзя удалить себя из роли '" + Globals.AdministratorRoleName + "'.";
  254. }
  255. else
  256. {
  257. if (RoleService.IsUserInRole(userName, role))
  258. {
  259. try
  260. {
  261. RoleService.RemoveUserFromRole(userName, role);
  262. }
  263. catch (Exception)
  264. {
  265. TempData["UserError"] = "Не смог удалить пользователя из роли.";
  266. }
  267. }
  268. else
  269. {
  270. try
  271. {
  272. RoleService.AddUserToRole(userName, role);
  273. }
  274. catch (Exception)
  275. {
  276. TempData["UserError"] = "Не смог добавить пользователя в роль.";
  277. }
  278. }
  279. }
  280. }
  281. else
  282. {
  283. TempData["UserError"] = "Роль не существует.";
  284. }
  285. }
  286. }
  287. catch (Exception)
  288. {
  289. TempData["UserError"] = "Не нашел пользователя.";
  290. }
  291. return RedirectToAction("Admin");
  292. }
  293. [Authorize(Roles = Globals.AdministratorRoleName)]
  294. public ActionResult UnlockUser(string userName)
  295. {
  296. try
  297. {
  298. MembershipUser user = MembershipService.GetUser(userName, false);
  299. if (!user.UnlockUser())
  300. {
  301. TempData["UserError"] = "Не смог разблокировать пользователя.";
  302. }
  303. }
  304. catch (Exception)
  305. {
  306. TempData["UserError"] = "Не смог найти пользователя.";
  307. }
  308. return RedirectToAction("Admin");
  309. }
  310. [Authorize(Roles = Globals.AdministratorRoleName)]
  311. public ActionResult ToggleApproved(string userName)
  312. {
  313. if (userName == User.Identity.Name)
  314. {
  315. TempData["UserError"] = "Вы не можете деактивировать себя.";
  316. }
  317. else
  318. {
  319. try
  320. {
  321. MembershipUser user = MembershipService.GetUser(userName, false);
  322. user.IsApproved = !user.IsApproved;
  323. try
  324. {
  325. MembershipService.UpdateUser(user);
  326. }
  327. catch (Exception)
  328. {
  329. TempData["UserError"] = "Не могу изменить информацию о пользователе.";
  330. }
  331. }
  332. catch (Exception)
  333. {
  334. TempData["UserError"] = "Не нашел пользователя.";
  335. }
  336. }
  337. return RedirectToAction("Admin");
  338. }
  339. [Authorize(Roles = Globals.AdministratorRoleName)]
  340. public ActionResult ResetPassword(string userName)
  341. {
  342. try
  343. {
  344. string newPassword;
  345. MembershipService.ResetPassword(userName, out newPassword);
  346. try
  347. {
  348. string storeEmail = ConfigurationManager.AppSettings["StoreEmail"];
  349. string managerEmail = ConfigurationManager.AppSettings["ManagerEmail"];
  350. string forceUsePickupDirectory = ConfigurationManager.AppSettings["ForceUsePickupDirectory"];
  351. if (!String.IsNullOrEmpty(forceUsePickupDirectory))
  352. {
  353. forceUsePickupDirectory = Server.MapPath(forceUsePickupDirectory);
  354. }
  355. MailUtils.Send(
  356. storeEmail,
  357. MembershipService.GetUserEmail(userName),
  358. Server.MapPath("~/App_Data/MailTemplates/resetPasswordTemplate.htm"),
  359. "windows-1251",
  360. String.Format("Новый пароль: {0}", newPassword),
  361. userName,
  362. forceUsePickupDirectory,
  363. managerEmail);
  364. }
  365. catch(Exception)
  366. {
  367. TempData["UserError"] = "Не могу отправить email пользователю. Новый пароль пользователя: " + newPassword;
  368. }
  369. }
  370. catch (Exception)
  371. {
  372. TempData["UserError"] = "Не могу найти пользователя.";
  373. }
  374. return RedirectToAction("Admin");
  375. }
  376. [Authorize(Roles = Globals.AdministratorRoleName)]
  377. public ActionResult DeleteUser(string userName)
  378. {
  379. if (userName == User.Identity.Name)
  380. {
  381. TempData["UserError"] = "Вы не можете удалить себя.";
  382. }
  383. else
  384. {
  385. if (!MembershipService.DeleteUser(userName, true))
  386. {
  387. TempData["UserError"] = "Не могу удалить пользователя.";
  388. }
  389. }
  390. return RedirectToAction("Admin");
  391. }
  392. protected override void OnActionExecuting(ActionExecutingContext filterContext)
  393. {
  394. if (filterContext.HttpContext.User.Identity is WindowsIdentity)
  395. {
  396. throw new InvalidOperationException("Windows authentication is not supported.");
  397. }
  398. // Register activity for the user.
  399. Membership.GetUser(User.Identity.Name, true);
  400. }
  401. }
  402. }