Advertisement
Guest User

Untitled

a guest
Feb 2nd, 2016
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 18.28 KB | None | 0 0
  1. public class AuthorizationController : BaseController
  2. {
  3. public AuthorizationController()
  4. {
  5. ViewBag.IsDisplayTopMenu = false;
  6. ViewBag.IsNotAutorized = true;
  7. HtmlHelper.ClientValidationEnabled = true;
  8. HtmlHelper.UnobtrusiveJavaScriptEnabled = true;
  9. }
  10.  
  11. [HttpGet, ActionName("SignUp")]
  12. public ActionResult SignUpGet()
  13. {
  14. SignUpModel model = new SignUpModel();
  15.  
  16. var countries = GetCountrySelectList();
  17. ViewBag.Countries = countries;
  18. ViewBag.Cities = GetCitiesSelectList(Int32.Parse(countries.First().Value));
  19. //model.Birthday = DateTime.UtcNow;
  20.  
  21. return View(model);
  22. }
  23.  
  24. [HttpPost, ActionName("SignUp")]
  25. [ValidateAntiForgeryToken]
  26. public async Task<ActionResult> SignUpPost(SignUpModel model)
  27. {
  28. SelectList tempList;
  29.  
  30. // 1 - Валидация
  31. if (ModelState.IsValid)
  32. {
  33. // 2 - Проверяем на дублирование почты пользователя
  34. User user = _unitOfWork.UserRepository.Get(x => x.Email.Equals(model.Email) && !x.IsDeleted).SingleOrDefault();
  35.  
  36. if (user != null)
  37. {
  38. ModelState.AddModelError("user", "Пользователь с таким адресом электронной почты уже зарегистрирован.");
  39. model.Password = string.Empty;
  40. model.ConfirmPassword = string.Empty;
  41. tempList = GetCountrySelectList();
  42. ViewBag.Countries = tempList;
  43. ViewBag.Cities = GetCitiesSelectList(Int32.Parse(tempList.First().Value));
  44.  
  45. return View(model);
  46. }
  47.  
  48. //DateTime birthday;
  49. //var isDateValid = DateTime.TryParse(model.Birthday, out birthday);
  50. //if (!isDateValid) ModelState.AddModelError("Birthday", "Birthday needs to be a valid date.");
  51.  
  52.  
  53. // 3 - Валидация дня рождения
  54. DateTime currentDate = DateTime.UtcNow;
  55. if (model.Birthday < currentDate.AddYears(-100) || model.Birthday > currentDate.AddYears(-16))
  56. {
  57. ModelState.AddModelError("model.Birthday", "Допустимый возраст пользователей от 16 и старше.");
  58. model.Password = string.Empty;
  59. model.ConfirmPassword = string.Empty;
  60. tempList = GetCountrySelectList();
  61. ViewBag.Countries = tempList;
  62. ViewBag.Cities = GetCitiesSelectList(Int32.Parse(tempList.First().Value));
  63.  
  64. return View(model);
  65. }
  66.  
  67. // 4 - Шифруем пароль
  68. String hashedPassword = CryptographyHelper.HashPassword(model.Password);
  69.  
  70. // 5 - Генерируем ключ активации
  71. String activationToken = CryptographyHelper.GenerateActivationToken();
  72.  
  73. // 6 - Создаем пользователя и сохраняем его в БД
  74. User dataUser = new User
  75. {
  76. FirstName = model.FirstName,
  77. MiddleName = model.MiddleName,
  78. LastName = model.LastName,
  79. CountryId = model.CountryId,
  80. CityId = model.CityId,
  81. Birthday = model.Birthday,
  82. CreateDate = DateTime.UtcNow,
  83. Email = model.Email,
  84. ConfirmationToken = activationToken,
  85. UserPasswordHash = hashedPassword,
  86. Gender = (int)model.Gender,
  87. Growth = model.Growth,
  88. Weight = model.Weight,
  89. IsDeleted = false,
  90. LastVisitDate = DateTime.UtcNow,
  91. Phone = model.Phone
  92. };
  93. _unitOfWork.UserRepository.Insert(dataUser);
  94. await _unitOfWork.SaveAsync();
  95.  
  96. // 7 - Отправляем письмо для подтверждения регистрации
  97. if (HttpContext.Request.Url != null)
  98. {
  99. ConfirmRegistrationMailMessage mailMessage =
  100. new ConfirmRegistrationMailMessage(dataUser, HttpContext.Request.Url.AbsoluteUri);
  101. await Emailer.SendMailAsync(mailMessage);
  102. }
  103.  
  104. return RedirectToAction("RegistrationSuccess");
  105. }
  106.  
  107. tempList = GetCountrySelectList();
  108. ViewBag.Countries = tempList;
  109. ViewBag.Cities = GetCitiesSelectList(Int32.Parse(tempList.First().Value));
  110.  
  111. model.Password = string.Empty;
  112. model.ConfirmPassword = string.Empty;
  113. return View(model);
  114. }
  115.  
  116. public ActionResult RegistrationSuccess()
  117. {
  118. return View();
  119. }
  120.  
  121. [HttpGet, ActionName("SignIn")]
  122. public ActionResult SignInGet()
  123. {
  124. SignInModel model = new SignInModel();
  125.  
  126. return View(model);
  127. }
  128.  
  129. [HttpPost, ActionName("SignIn")]
  130. [ValidateAntiForgeryToken]
  131. public ActionResult SignInPost(SignInModel model)
  132. {
  133. if (ModelState.IsValid)
  134. {
  135. var users = _unitOfWork.UserRepository.Get(x => x.Email == model.Email && !x.IsDeleted);
  136. var user = users.FirstOrDefault();
  137. if (user == null)
  138. {
  139. ModelState.AddModelError("user", "Пользователь не найден.");
  140. model.Password = string.Empty;
  141. return View(model);
  142. }
  143. var password = CryptographyHelper.HashPassword(model.Password);
  144. if (user.UserPasswordHash == password)
  145. {
  146. FormsAuthentication.SetAuthCookie(user.Email, true);
  147. return RedirectToAction("Index", "HealthPanel");
  148. }
  149. else
  150. {
  151. if (user.UserPasswordHash != password)
  152. {
  153. model.Password = string.Empty;
  154. ModelState.AddModelError("user", "Неверный пароль");
  155. }
  156. }
  157. }
  158. model.Password = string.Empty;
  159. return View(model);
  160.  
  161. }
  162.  
  163. [HttpGet]
  164. public ActionResult SignOut()
  165. {
  166. FormsAuthentication.SignOut();
  167.  
  168. return Redirect("signin");
  169. }
  170. }
  171.  
  172. @model Project.Models.Authorization.SignInModel
  173.  
  174. @{
  175. ViewBag.Title = "SignIn";
  176. Layout = "~/Views/Shared/_DefaultLayoutForNonAuthorize.cshtml";
  177. }
  178. <script src="~/Content/scripts/sign-in.js"></script>
  179. <!-- Bootstrap core CSS -->
  180. <link href="~/Content/bootstrap.min.css" rel="stylesheet">
  181.  
  182. <!-- Custom styles for this template -->
  183. <link href="~/Content/Styles/page-enter.css" rel="stylesheet" />
  184. <link href="~/Content/Styles/sticky-footer.css" rel="stylesheet">
  185. <link href="~/Content/Styles/style.css" rel="stylesheet">
  186. <body class="page-enter-body">
  187.  
  188. <!-- Begin page content -->
  189. <header>
  190. <div class="page-top-thr-lv">
  191. <div class="container">
  192. <div class="top-3 page-enter-top-3">
  193. <div class="col-md-5 col-xs-6 page-enter-pull-right">
  194. <div class="col-md-6 col-md-offset-3 logo">
  195. <p class="text-center">text </p>
  196. </div>
  197. <div class="col-md-3 text-center">
  198. <a href="/" title=""><img src="~/Content/img/logo.png" alt="" /></a>
  199. </div>
  200. </div>
  201. </div>
  202.  
  203. </div>
  204. </div><!--/.page-top-thr-lv -->
  205. </header>
  206. <section class="main-content">
  207. <div class="container">
  208.  
  209. @using (Html.BeginForm("SignIn", "Authorization", FormMethod.Post))
  210. {
  211. <div class="col-md-4 padding0 feedback">
  212. @Html.AntiForgeryToken()
  213. @Html.ValidationSummary()
  214. <div class="form-group col-md-9 padding0">
  215. <label for="InputEmail">Эл. почта</label>
  216. @Html.TextBoxFor(x => x.Email, new { @class = "form-control", id = "InputEmail", placeholder = "example@mail.com" })
  217. @*<input type="email" class="form-control" id="email" placeholder="example@gmail.com" pattern="[^@]+@[^@]+.[a-zA-Z]{2,6}">*@
  218. </div>
  219.  
  220. <div class="form-group col-md-9 padding0">
  221. <label for="InputPassword">Пароль</label>
  222. @Html.PasswordFor(x => x.Password, new { @class = "form-control", id = "InputPassword" })
  223. </div>
  224. </div>
  225. <div class="clearfix"></div>
  226. <div class="col-md-4 marginleft105 padding0">
  227. <div class="col-md-12 padding0">
  228. <button type="submit" class="btn btn-send">Войти</button>
  229.  
  230.  
  231.  
  232. }
  233. @Html.ActionLink("Зарегистрироваться", "SignUp", "Authorization", new { @class = "btn btn-send" })
  234. </div>
  235. </div>
  236.  
  237. </div>
  238. </section><!--/.main-content -->
  239. <div class="bg"></div>
  240. <div id="footer">
  241. <div class="container">
  242. <p class="text-muted">© 2015</p>
  243. </div>
  244. </div>
  245.  
  246.  
  247. <!-- Bootstrap core JavaScript
  248. ================================================== -->
  249. <!-- Placed at the end of the document so the pages load faster -->
  250. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
  251. <script src="~/Content/scripts/bootstrap.min.js"></script>
  252. </body>
  253.  
  254. using ColorLongLife.Utilities
  255. @model ColorLongLife.Models.Authorization.SignUpModel
  256.  
  257. @{
  258. ViewBag.Title = "SignUp";
  259. Layout = "~/Views/Shared/_DefaultLayoutForNonAuthorize.cshtml";
  260. }
  261.  
  262. @section scripts
  263. {
  264. <script src="~/Content/scripts/sign-up.js"></script>
  265. @*<script src="~/Content/scripts/bootstrap-datepicker.js"></script>*@
  266. <script src="~/Content/scripts/edit-profile.js"></script>
  267. }
  268.  
  269. <section class="main-content">
  270. <div class="container">
  271. <div class="col-md-6 padding0">
  272. <h1>Регистрация</h1>
  273. <div class="intro-2">
  274. <p>Все поля обязательны к заполнению, так как играют важную роль при расшифровке диагностики.</p>
  275. </div>
  276. </div>
  277. <div class="clearfix"></div>
  278. @using (Html.BeginForm("SignUp", "Authorization", FormMethod.Post))
  279. {
  280. @Html.AntiForgeryToken()
  281. @Html.ValidationSummary()
  282. <div class="col-md-2 padding0 feedback">
  283. <div class="form-group col-md-12 padding0">
  284. <label for="InputFIO">Фамилия</label>
  285. @Html.TextBoxFor(x => x.LastName, new { @class = "form-control", id = "InputFIO", placeholder = "Зареченская", type = "text" })
  286. </div>
  287. <div class="form-group col-md-12 padding0">
  288. <label for="InputName">Имя</label>
  289. @Html.TextBoxFor(x => x.FirstName, new { @class = "form-control", id = "InputName", placeholder = "Анна", type = "text" })
  290. </div>
  291. <div class="form-group col-md-12 padding0">
  292. <label for="InputSecondName">Отчество</label>
  293. @Html.TextBoxFor(x => x.MiddleName, new { @class = "form-control", id = "InputSecondName", placeholder = "Ивановна", type = "text" })
  294. </div>
  295. <div class="form-group col-md-12 padding0">
  296. <label for="InputBirthday">Дата рождения</label>
  297. @Html.EditorFor(model => model.Birthday, new { htmlAttributes = new { @class = "form-control", id = "InputBirthday" } })
  298. @*@Html.TextBoxFor(x => x.Birthday, "{0:dd.MM.yyyy}", new { @class = "form-control", id = "InputBirthday" })*@
  299. </div>
  300. <div class="radio1">
  301. <p>Пол</p>
  302. @Html.RadioButtonFor(x => x.Gender, Gender.Male, new { name = "rbtnGender", id = "optionsRadios2" })
  303. <label><span class="cbxGender"></span> Мужской</label>
  304. @Html.RadioButtonFor(x => x.Gender, Gender.Female, new { name = "rbtnGender", id = "optionsRadios1" })
  305. <label><span class="cbxGender"></span>Женский</label>
  306. </div>
  307. <div class="form-group col-md-5 padding0">
  308. <label for="weight">Рост (см.)</label>
  309. @Html.TextBoxFor(x => x.Growth, new { @class = "form-control", id = "weight", placeholder = "176" })
  310. </div>
  311. <div class="form-group col-md-5 col-md-offset-2 padding0">
  312. <label for="height">Вес (кг.)</label>
  313. @Html.TextBoxFor(x => x.Weight, new { @class = "form-control", id = "height", placeholder = "69" })
  314. </div>
  315. <div class="form-group col-md-12 padding0">
  316. <label for="country">Страна проживания</label>
  317. @Html.DropDownListFor(x => x.CountryId, ViewBag.Countries as SelectList, "Выберите страну", new { @class = "form-control", id = "country", type = "text" })
  318. </div>
  319. <div class="form-group col-md-12 padding0">
  320. <label for="city">Город</label>
  321. @Html.DropDownListFor(x => x.CityId, ViewBag.Cities as SelectList, "Выберите город", new { @class = "form-control", id = "city", type = "text" })
  322. </div>
  323. <div class="form-group col-md-12 padding0">
  324. <label for="telephone">Телефон</label>
  325. @Html.TextBoxFor(x => x.Phone, new { @class = "form-control", id = "telephone", placeholder = "", type = "text" })
  326. <span><img src="~/Content/img/info.png" />для оперативной связи</span>
  327. </div>
  328. <div class="form-group col-md-12 padding0">
  329. <label for="email">Эл. почта</label>
  330. @Html.TextBoxFor(x => x.Email, new { @class = "form-control", id = "email", placeholder = "ekaterina@mail.com", type = "text" })
  331. @*<span><img src="~/Content/img/error.png" />Эл. почта не введена</span>*@
  332. </div>
  333. <div class="form-group col-md-12 padding0">
  334. <div>
  335. <label for="password">Пароль</label>
  336. @Html.TextBoxFor(x => x.Password, new { @class = "form-control", id = "password", type = "password" })
  337. </div>
  338.  
  339. <div>
  340. <label for="confirmPassword">Повторите пароль</label>
  341. @Html.TextBoxFor(x => x.ConfirmPassword, new { @class = "form-control", id = "confirmPassword", type = "password" })
  342. </div>
  343. </div>
  344. </div>
  345. <div class="col-md-4 dop paddingleft30">
  346. <p>Регистрация позволит вам воспользоваться всеми услугами персонального кабинета:</p>
  347. <ul class="list-unstyled">
  348. <li><span class="glyphicon glyphicon-ok-sign"> </span>Пройти бесплатное цветовое тестирование, выявляющие психологически проблемные области вашей жизни</li>
  349. <li><span class="glyphicon glyphicon-ok-sign"> </span>Ознакомиться с демо-расшифровками результатов тестирования и осмысленно выбрать нужный вид расшифровки для себя</li>
  350. <li><span class="glyphicon glyphicon-ok-sign"> </span>Воспользоваться платными сервисами, которые позволяют выявить влияние психологических проблем на здоровье</li>
  351. <li><span class="glyphicon glyphicon-ok-sign"> </span>Записаться на консультацию к клиническому психологу по результатам расшифровки теста</li>
  352. <li><span class="glyphicon glyphicon-ok-sign"> </span>Купить персональные курсы цветовой коррекции</li>
  353. <li>
  354. <span class="glyphicon glyphicon-ok-sign"> </span>Увидеть список полезных для вас биологически активных добавок, которые были подобраны по результатам теста и купить их.
  355. </li>
  356. </ul>
  357. <div class="secret">text.</div>
  358. </div>
  359. <div class="col-md-6">
  360. </div>
  361. <div class="clearfix"></div>
  362. <div class="checkbox1 col-md-8 padding0">
  363. <input type="checkbox" value="" checked>
  364. <label><span class="cbxUserAgreement"></span>Я прочитал и согласен с <a href="">Пользовательским соглашением</a></label>
  365. <input type="checkbox" value="" checked>
  366. <label><span class="cbxRegulationsPersonalData"></span>Я прочитал и согласен с <a href="">Положением о персональных данных</a> </label>
  367. <input type="checkbox" value="" checked>
  368. <label><span class="cbxLimitationPprofessionalLiability"></span>Я прочитал и согласен с <a href="">Ограничением профессиональной ответственности</a> </label>
  369. </div>
  370. <div class="clearfix"></div>
  371. <button type="submit" class="btn btn-send">Зарегистрироваться</button>
  372. }
  373. </div>
  374. </section><!--/.main-content -->
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement