Advertisement
Guest User

Untitled

a guest
May 28th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.75 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using System.Web.Routing;
  7. using System.Web.Security;
  8. using fitness.Models;
  9. using fitness.Services;
  10.  
  11. namespace fitness.Controllers
  12. {
  13.     public class AccountController : Controller
  14.     {
  15.         private readonly AccountRepository _repository = new AccountRepository();
  16.  
  17.         public ActionResult LogOn()
  18.         {
  19.             return View();
  20.         }
  21.  
  22.         [HttpPost]
  23.         public ActionResult LogOn(LogOnModel model, string returnUrl)
  24.         {
  25.             if (ModelState.IsValid)
  26.             {
  27.                 if ((from item in new fitnes1Entities().Clients
  28.                     where item.Login == model.UserName && item.Password == model.Password
  29.                     select item).Any())
  30.                 {
  31.                     FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
  32.                     if (!string.IsNullOrWhiteSpace(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
  33.                         && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
  34.                     {
  35.                         return Redirect(returnUrl);
  36.                     }
  37.                     else
  38.                     {
  39.                         return RedirectToAction("Index", "Home");
  40.                     }
  41.                 }
  42.                 else
  43.                 {
  44.                     ModelState.AddModelError("", "Имя пользователя или пароль указаны неверно.");
  45.                 }
  46.             }
  47.             return View(model);
  48.         }
  49.  
  50.         public ActionResult LogOff()
  51.         {
  52.             FormsAuthentication.SignOut();
  53.  
  54.             return RedirectToAction("Index", "Home");
  55.         }
  56.  
  57.         [Authorize]
  58.         public ActionResult Cabinet()
  59.         {
  60.             return View(_repository.GetAccount(User.Identity.Name));
  61.         }
  62.  
  63.         [HttpPost]
  64.         public ActionResult Register(RegisterModel model)
  65.         {
  66.             try
  67.             {
  68.                 if (ModelState.IsValid)
  69.                 {
  70.                     var entities = new fitnes1Entities();
  71.                     if (!(from item in entities.Clients where item.Login == model.UserName select item).Any())
  72.                     {
  73.                         _repository.Add(model);
  74.                         FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
  75.                         return RedirectToAction("Index", "Home");
  76.                     }
  77.                     else
  78.                     {
  79.                         ModelState.AddModelError("", ErrorCodeToString(MembershipCreateStatus.DuplicateUserName));
  80.                     }
  81.                 }
  82.             }
  83.             catch (Exception e)
  84.             {
  85.                 ModelState.AddModelError("", "При попытке регистрации возникла неизвестная ошибка.");
  86.                 return View();
  87.             }
  88.             return View(model);
  89.         }
  90.  
  91.         public ActionResult Register()
  92.         {
  93.             return View();
  94.         }
  95.  
  96.         [HttpPost]
  97.         [Authorize]
  98.         public ActionResult Edit(RegisterModel model)
  99.         {
  100.             try
  101.             {
  102.                 _repository.Edit(model, _repository.GetAccount(User.Identity.Name));
  103.             }
  104.             catch (Exception e)
  105.             {
  106.                 ModelState.AddModelError("", "При попытке применения изменений возникла неизвестная ошибка.");
  107.                 return View();
  108.             }
  109.             return RedirectToAction("Cabinet", "Account");
  110.         }
  111.  
  112.         [Authorize]
  113.         public ActionResult Edit()
  114.         {
  115.             return View(_repository.GetModelById(_repository.GetAccount(User.Identity.Name).IDClient));
  116.         }
  117.  
  118.         [Authorize]
  119.         public ActionResult ChangePassword()
  120.         {
  121.             return View();
  122.         }
  123.  
  124.         [Authorize]
  125.         [HttpPost]
  126.         public ActionResult ChangePassword(ChangePasswordModel model)
  127.         {
  128.             if (ModelState.IsValid)
  129.             {
  130.                 bool changePasswordSucceeded = false;
  131.                 try
  132.                 {
  133.                     var entities = new fitnes1Entities();
  134.                     var currentUser =
  135.                         (from item in entities.Clients
  136.                             where item.Login == User.Identity.Name && item.Password == model.OldPassword
  137.                             select item).FirstOrDefault();
  138.                     if (currentUser != null)
  139.                     {
  140.                         currentUser.Password = model.NewPassword;
  141.                         entities.SaveChanges();
  142.                         changePasswordSucceeded = true;
  143.                     }
  144.                 }
  145.                 catch (Exception)
  146.                 {
  147.                     changePasswordSucceeded = false;
  148.                 }
  149.  
  150.                 if (changePasswordSucceeded)
  151.                 {
  152.                     return RedirectToAction("ChangePasswordSuccess");
  153.                 }
  154.                 else
  155.                 {
  156.                     ModelState.AddModelError("", "Неправильный текущий пароль или недопустимый новый пароль.");
  157.                 }
  158.             }
  159.             return View(model);
  160.         }
  161.  
  162.         public ActionResult ChangePasswordSuccess()
  163.         {
  164.             return View();
  165.         }
  166.  
  167.         #region Status Codes
  168.  
  169.         private static string ErrorCodeToString(MembershipCreateStatus createStatus)
  170.         {
  171.             switch (createStatus)
  172.             {
  173.                 case MembershipCreateStatus.DuplicateUserName:
  174.                     return "Имя пользователя уже существует. Введите другое имя пользователя.";
  175.  
  176.                 case MembershipCreateStatus.DuplicateEmail:
  177.                     return
  178.                         "Имя пользователя для данного адреса электронной почты уже существует. Введите другой адрес электронной почты.";
  179.  
  180.                 case MembershipCreateStatus.InvalidPassword:
  181.                     return "Указан недопустимый пароль. Введите допустимое значение пароля.";
  182.  
  183.                 case MembershipCreateStatus.InvalidEmail:
  184.                     return "Указан недопустимый адрес электронной почты. Проверьте значение и повторите попытку.";
  185.  
  186.                 case MembershipCreateStatus.InvalidAnswer:
  187.                     return
  188.                         "Указан недопустимый ответ на вопрос для восстановления пароля. Проверьте значение и повторите попытку.";
  189.  
  190.                 case MembershipCreateStatus.InvalidQuestion:
  191.                     return
  192.                         "Указан недопустимый вопрос для восстановления пароля. Проверьте значение и повторите попытку.";
  193.  
  194.                 case MembershipCreateStatus.InvalidUserName:
  195.                     return "Указано недопустимое имя пользователя. Проверьте значение и повторите попытку.";
  196.  
  197.                 case MembershipCreateStatus.ProviderError:
  198.                     return
  199.                         "Поставщик проверки подлинности вернул ошибку. Проверьте введенное значение и повторите попытку. Если проблему устранить не удастся, обратитесь к системному администратору.";
  200.  
  201.                 case MembershipCreateStatus.UserRejected:
  202.                     return
  203.                         "Запрос создания пользователя был отменен. Проверьте введенное значение и повторите попытку. Если проблему устранить не удастся, обратитесь к системному администратору.";
  204.  
  205.                 default:
  206.                     return
  207.                         "Произошла неизвестная ошибка. Проверьте введенное значение и повторите попытку. Если проблему устранить не удастся, обратитесь к системному администратору.";
  208.             }
  209.         }
  210.  
  211.         #endregion
  212.     }
  213. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement