Advertisement
Guest User

Untitled

a guest
Feb 27th, 2018
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 38.72 KB | None | 0 0
  1. using System;
  2. using System.Globalization;
  3. using System.Linq;
  4. using System.Security.Claims;
  5. using System.Threading.Tasks;
  6. using System.Web;
  7. using System.Web.Mvc;
  8. using Microsoft.AspNet.Identity;
  9. using Microsoft.AspNet.Identity.Owin;
  10. using Microsoft.Owin.Security;
  11. using my.kyivgaz.Models;
  12. using my.kyivgaz.DataInterface;
  13. using my.kyivgaz.Filter;
  14. using ExternalNotificationServises;
  15. using DataModels.Gasolina;
  16. using DataLibrary.Cabinet.Abstract;
  17. using DataLibrary.Cabinet;
  18.  
  19. namespace my.kyivgaz.Controllers
  20. {
  21. //[NoCache]
  22. [FilterGasolinaSession]
  23. public class AccountController : BaseController
  24. {
  25. private readonly ICabinetRepository _cabinetRepository;
  26. private IEmailSender IEmailsender;
  27. ILogger _logger;
  28. public AccountController(ICabinetRepository cabinetRepository, IEmailSender _IEmailsender, ILogger logger)
  29. {
  30. IEmailsender = _IEmailsender;
  31. _cabinetRepository = cabinetRepository;
  32. _logger = logger;
  33. }
  34.  
  35.  
  36. #region оригинал контролера
  37.  
  38.  
  39.  
  40. //private ApplicationUserManager _userManager;
  41.  
  42. //public AccountController()
  43. //{
  44. //}
  45.  
  46. //public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
  47. //{
  48. // UserManager = userManager;
  49. // SignInManager = signInManager;
  50. //}
  51.  
  52. //public ApplicationUserManager UserManager
  53. //{
  54. // get
  55. // {
  56. // return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
  57. // }
  58. // private set
  59. // {
  60. // _userManager = value;
  61. // }
  62. //}
  63.  
  64. //private ApplicationSignInManager _signInManager;
  65.  
  66. //public ApplicationSignInManager SignInManager
  67. //{
  68. // get
  69. // {
  70. // return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
  71. // }
  72. // private set { _signInManager = value; }
  73. //}
  74.  
  75. #endregion
  76.  
  77. //
  78. // GET: /Account/Login
  79. [AllowAnonymous]
  80. public ActionResult Login(string returnUrl, string id, string num)
  81. {
  82. if (num != null) { Session["SiteType"] = num == "kievgas" ? num: "energy"; }
  83.  
  84. ViewBag.PersonalAccount = (id == null) ? "" : id;
  85. ViewBag.ReturnUrl = returnUrl;
  86. ViewBag.SessionEnd = TempData["sessioend"];
  87. return View();
  88. }
  89.  
  90. //private async Task SignInAsync(ApplicationUser user, bool isPersistent, string session_id)
  91. ////private async Task SignInAsync(ApplicationUser user, bool isPersistent)
  92. ////{
  93. //// AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
  94.  
  95. //// //var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
  96. //// //identity.AddClaim(new Claim("session_id", session_id));
  97. //// //AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
  98. //// AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
  99. ////}
  100.  
  101. //
  102. // POST: /Account/Login
  103. [HttpPost]
  104. [AllowAnonymous]
  105. [ValidateAntiForgeryToken]
  106. public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
  107. // public ActionResult Login(LoginViewModel model, string returnUrl)
  108. {
  109. // LogService.Error("test {0}", model.PersonalAccount);
  110. // UserManager.RemovePassword(25279);
  111. // UserManager.AddPassword(25279, model.Password);
  112. // validCredentials = await UserManager.FindAsync(model.UserName, model.Password);
  113.  
  114. if (!ModelState.IsValid)
  115. {
  116. return View(model);
  117. }
  118. //SignInStatus result = await SignInManager.PasswordSignInAsync(model.PersonalAccount, model.Password, model.RememberMe, shouldLockout: true);
  119.  
  120. SignInStatus result;
  121.  
  122. try
  123. {
  124. result = await SignInManager.PasswordSignInAsync(model.PersonalAccount, model.Password, isPersistent: false, shouldLockout: true);
  125.  
  126. }
  127. catch (Exception ex)
  128. {
  129.  
  130. throw;
  131. }
  132.  
  133. switch (result)
  134. {
  135. case SignInStatus.Success:
  136. Abon abon = _cabinetRepository.Abons.FirstOrDefault(a => a.PersonAccount.Trim() == model.PersonalAccount.Trim());
  137. Payment lastPayment = _cabinetRepository.Payments
  138. .FirstOrDefault(p => p.KodR == abon.Kod
  139. && p.Datic == (_cabinetRepository.Payments.Where(x => x.KodR == abon.Kod).Max(x => x.Datic)));
  140. double writtenByUserLastPayment;
  141. Session["NewSessoinId"] = Guid.NewGuid();
  142. Session.Timeout = 18;
  143. //ApplicationUser user = await UserManager.FindByNameAsync(model.PersonalAccount);
  144. AspNetUsers user = _cabinetRepository.AspNetUsers.FirstOrDefault(a => a.UserName == model.PersonalAccount);
  145. bool successfulParsing = double.TryParse(user.parametrx, out writtenByUserLastPayment);
  146. if (lastPayment != null && (user.CreateDate.Date == user.LastLogInDate.GetValueOrDefault().Date && writtenByUserLastPayment != lastPayment.Sumic && successfulParsing))
  147. {
  148. WaitActivationViewModel model_wait = new WaitActivationViewModel
  149. {
  150. parametrx = user.parametrx
  151. };
  152. TempData["model_wait"] = model_wait;
  153. return RedirectToAction("WaitActivation", "Home");
  154. }
  155. //return RedirectToLocal(returnUrl);
  156.  
  157.  
  158.  
  159. ViewBag.SessionSiteType = Session["SiteType"];
  160.  
  161.  
  162. return RedirectToAction("Index", "Client");
  163. case SignInStatus.LockedOut:
  164. return View("Lockout");
  165. case SignInStatus.RequiresVerification:
  166. return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
  167. case SignInStatus.Failure:
  168. default:
  169. ModelState.AddModelError("", "Невірна спроба входу");
  170. return View(model);
  171. }
  172. }
  173.  
  174.  
  175. //закомментировано после переходна на SQL Server
  176. //private async Task<SignInStatus> RegistrationUserAuto(LoginViewModel model, string sessiongasolina, SignInStatus result)
  177. //{
  178. // //закомментировано после переходна на SQL Server
  179. // //var user_info_object = Igasolina.GetUserInfo(model.PersonalAccount, sessiongasolina, ClientIP);
  180. // //GasolinaUserFullInfoModel user_info = new GasolinaUserFullInfoModel
  181. // //{
  182. // // user = user_info_object.Result.ResultObject as GasolinaUserModel
  183. // //};
  184.  
  185. // //закомментировано после переходна на SQL Server
  186. // //var user = new ApplicationUser
  187. // //{
  188. // // UserName = model.PersonalAccount,
  189. // // //Email = user_info.user.data.email,
  190. // // //UserFio = user_info.user_fio,
  191. // // //PhoneNumber = user_info.user.data.mobile_phone,
  192. // // //LandingNumber = user_info.user.data.landing_phone,
  193. // // isGasolinaFirst = true,
  194. // // CreateDate = DateTime.Now,
  195. // // parametry = model.Password
  196. // //};
  197.  
  198. // var user = new ApplicationUser
  199. // {
  200. // UserName = model.PersonalAccount,
  201. // isGasolinaFirst = true,
  202. // CreateDate = DateTime.Now,
  203. // parametry = model.Password
  204. // };
  205. // var result_create = await UserManager.CreateAsync(user, model.Password);
  206. // if (result_create.Succeeded)
  207. // {
  208. // await SignInAsync(user, model.RememberMe);
  209. // //закомментировано после переходна на SQL Server
  210. // //await SignInAsync(user, model.RememberMe, sessiongasolina);
  211.  
  212. // //-------------------------это и было закомментировано-------------------
  213. // //await SignInManager.SignInAsync(user, isPersistent: model.RememberMe, rememberBrowser: model.RememberMe);
  214. // result = await SignInManager.PasswordSignInAsync(model.PersonalAccount, model.Password, model.RememberMe, shouldLockout: false);
  215. // await CreateConfirmEmail(user);
  216. // }
  217. // return result;
  218. //}
  219.  
  220. private async Task CreateConfirmEmail(ApplicationUser user)
  221. {
  222. string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
  223. var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
  224.  
  225. string messagebody = IEmailsender.GetEMailTemplate(Server.MapPath(@"~\App_Data\EmailTemplate\ConfirmEmail.html"));
  226. messagebody = messagebody.Replace("{0}", user.UserFio);
  227. messagebody = messagebody.Replace("{1}", callbackUrl);
  228. messagebody = messagebody.Replace("{2}", callbackUrl);
  229. messagebody = messagebody.Replace("{3}", user.UserName);
  230.  
  231.  
  232. //"Будь-ласка підтвердіть свій обліковий запис. Перейдіть за посиланням <a href=\"" + callbackUrl + "\"> сюди </a>"
  233. await UserManager.SendEmailAsync(user.Id, "КиївГазЕнерджи: Підтвердження облікового запису", messagebody);
  234. }
  235.  
  236. //
  237. // GET: /Account/VerifyCode
  238. [AllowAnonymous]
  239. public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
  240. {
  241. // Require that the user has already logged in via username/password or external login
  242. if (!await SignInManager.HasBeenVerifiedAsync())
  243. {
  244. return View("Error");
  245. }
  246. var user = await UserManager.FindByIdAsync(await SignInManager.GetVerifiedUserIdAsync());
  247. if (user != null)
  248. {
  249. var code = await UserManager.GenerateTwoFactorTokenAsync(user.Id, provider);
  250. }
  251. return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
  252. }
  253.  
  254. //
  255. // POST: /Account/VerifyCode
  256. [HttpPost]
  257. [AllowAnonymous]
  258. [ValidateAntiForgeryToken]
  259. public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
  260. {
  261. if (!ModelState.IsValid)
  262. {
  263. return View(model);
  264. }
  265.  
  266. // The following code protects for brute force attacks against the two factor codes.
  267. // If a user enters incorrect codes for a specified amount of time then the user account
  268. // will be locked out for a specified amount of time.
  269. // You can configure the account lockout settings in IdentityConfig
  270. ////var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
  271. var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: false, rememberBrowser: model.RememberBrowser);
  272. switch (result)
  273. {
  274. case SignInStatus.Success:
  275. Session["NewSessoinId"] = Guid.NewGuid();
  276. Session.Timeout = 18;
  277. return RedirectToLocal(model.ReturnUrl);
  278. case SignInStatus.LockedOut:
  279. return View("Lockout");
  280. case SignInStatus.Failure:
  281. default:
  282. ModelState.AddModelError("", "Invalid code.");
  283. return View(model);
  284. }
  285. }
  286.  
  287. [HttpPost]
  288. [AllowAnonymous]
  289. public async Task<JsonResult> checkregistrationparam(string paramname, string value)
  290. {
  291. switch (paramname.ToLower())
  292. {
  293. case "personalaccount":
  294. return Json(new { isempty = (await IsEmptyPersonalAccount(value)) });
  295. case "email":
  296. return Json(new { isempty = (await UserManager.FindByEmailAsync(value) == null) });
  297. //case "phone":
  298. // return Json(new { isempty = (await UserManager.FindByPhoneAsync(value) == null) });
  299. default:
  300. throw new Exception("Параметр перевірки не заданий");
  301. }
  302.  
  303. }
  304.  
  305. protected async Task<bool> IsEmptyPersonalAccount(string login)
  306. {
  307. bool result;
  308. string lastNumber = login[login.Length - 1].ToString();
  309. if (login.Length == 10 && lastNumber != "1")
  310. {
  311. result = await UserManager.FindByNameAsync(login) == null;
  312. ApplicationUser foundUser = await UserManager.FindByNameAsync(login);
  313. }
  314. else if (login.Length == 10 && lastNumber == "1")
  315. {
  316. string shorterLogin = login.Substring(0, login.Length - 1);
  317. ApplicationUser userWithOneNumber = await UserManager.FindByNameAsync(login);
  318. ApplicationUser userWithoutOneNumber = await UserManager.FindByNameAsync(shorterLogin);
  319. result = userWithOneNumber == null && userWithoutOneNumber == null;
  320. }
  321. else if (login.Length == 9)
  322. {
  323. string longerString = login + "1";
  324. ApplicationUser userWithOneNumber = await UserManager.FindByNameAsync(longerString);
  325. ApplicationUser userWithoutOneNumber = await UserManager.FindByNameAsync(login);
  326. result = userWithOneNumber == null && userWithoutOneNumber == null;
  327. }
  328. else
  329. {
  330. //throw new Exception()
  331. return false;
  332. }
  333. return result;
  334. }
  335.  
  336. //
  337. // GET: /Account/Register
  338. [AllowAnonymous]
  339. public ActionResult Register()
  340. {
  341. return View();
  342. }
  343.  
  344. //
  345. // POST: /Account/Register
  346. [HttpPost]
  347. [AllowAnonymous]
  348. [ValidateAntiForgeryToken]
  349. public async Task<ActionResult> Register(RegisterViewModel model)
  350. {
  351. if (ModelState.IsValid)
  352. {
  353. if (!await IsEmptyPersonalAccount(model.PersonalAccount))
  354. {
  355. ModelState.AddModelError("", "Користувач з таким особовим рахунком уже зареєстровано в системі.");
  356. return View(model);
  357. }
  358.  
  359. ////закомментили как ненужное после переезда на SQL Server
  360. //RegisterViewModel reg_model = new RegisterViewModel
  361. //{
  362. // Password = model.Password,
  363. // PersonalAccount = model.PersonalAccount,
  364. // parametrx = model.parametrx,
  365. // Email = model.Email
  366. //};
  367.  
  368.  
  369. ////закомментили как ненужное после переезда на SQL Server
  370. ////регистрация пользователя в билинге
  371. //var rez_rez = await Igasolina.Registration(reg_model, ClientIP);
  372. //if (rez_rez.RequestResult == WebRequestResultEnum.Error)
  373. //{
  374. // ModelState.AddModelError("", rez_rez.errortext);
  375. // return View(model);
  376. //}
  377.  
  378.  
  379. var user = new ApplicationUser
  380. {
  381. UserName = model.PersonalAccount,
  382. CreateDate = DateTime.Now,
  383. Email = model.Email,
  384. parametrx = model.parametrx,
  385. parametry = model.Password,
  386. isGasolinaFirst = false
  387. };
  388. Abon abon = _cabinetRepository.Abons.FirstOrDefault(a => a.PersonAccount == model.PersonalAccount);
  389. if (abon == null)
  390. {
  391. if (model.PersonalAccount.Length == 9)
  392. {
  393. string searchString1 = model.PersonalAccount + "1";
  394. abon = _cabinetRepository.Abons.FirstOrDefault(a => a.PersonAccount == searchString1);
  395. }
  396. else if (model.PersonalAccount.Length == 10)
  397. {
  398. string searchString2 = model.PersonalAccount.Substring(0, 9);
  399. abon = _cabinetRepository.Abons.FirstOrDefault(a => a.PersonAccount == model.PersonalAccount + "1");
  400. }
  401. }
  402. if (abon != null)
  403. {
  404. if (abon.FirstName == null)
  405. user.UserFio = abon.Name.Trim();
  406. else if (abon.FirstName != null && abon.Patronymic == null)
  407. user.UserFio = string.Format("{0} {1}", abon.Name.Trim(), abon.FirstName.Trim());
  408. else if (abon.FirstName != null && abon.Patronymic != null)
  409. user.UserFio = string.Format("{0} {1} {2}", abon.Name.Trim(), abon.FirstName.Trim(), abon.Patronymic.Trim());
  410. AbonentPhone[] allAbonentPhones = _cabinetRepository.AbonentPhones
  411. .Where(ap => ap.KodR == abon.Kod).ToArray();
  412. AbonentPhone homePhone;
  413. if (allAbonentPhones.Any(x => x.Main.GetValueOrDefault(false) && x.PhoneTypeName == "home"))
  414. homePhone = allAbonentPhones.FirstOrDefault(x => x.Main.GetValueOrDefault(false) && x.PhoneTypeName == "home");
  415. else
  416. homePhone = allAbonentPhones.FirstOrDefault(x => x.PhoneTypeName == "home");
  417. if (homePhone != null)
  418. user.LandingNumber = homePhone.GetPhoneNumberWithRegionOrMobileCode();
  419. AbonentPhone mobilePhone;
  420. if (allAbonentPhones.Any(x => x.Main.GetValueOrDefault(false) && x.PhoneTypeName == "cell"))
  421. mobilePhone = allAbonentPhones.FirstOrDefault(x => x.Main.GetValueOrDefault(false) && x.PhoneTypeName == "cell");
  422. else
  423. mobilePhone = allAbonentPhones.FirstOrDefault(x => x.PhoneTypeName == "cell");
  424. if (mobilePhone != null)
  425. user.PhoneNumber = mobilePhone.GetPhoneNumberWithRegionOrMobileCode();
  426.  
  427. if (!_cabinetRepository.Payments.Any(p => p.KodR == abon.Kod))
  428. {
  429. ModelState.AddModelError("", "Ви не можете зареєструватися, оскільки у Вас немає жодної оплати. Реєстрація стане доступною після першої оплати.");
  430. return View(model);
  431. }
  432.  
  433. var LastSum = _cabinetRepository.Payments
  434. .Where(p => p.KodR == abon.Kod)
  435. .OrderByDescending(o => o.Datic)
  436. .Select(s => s.Sumic).FirstOrDefault();
  437.  
  438. if(LastSum != 0.0)
  439. {
  440. string paramx = Convert.ToString(model.parametrx).Replace(".", ",");
  441. // string lastpay = Convert.ToString(LastSum);
  442. string lastpay = String.Format("{0:0.00}", LastSum);
  443. if (lastpay != paramx)
  444. {
  445. ModelState.AddModelError("", "Не вірна сума останнього платежу.");
  446. return View(model);
  447. }
  448. }
  449.  
  450. }
  451. else
  452. {
  453. ModelState.AddModelError("", "Такого особового рахунку не існує.");
  454. return View(model);
  455. }
  456.  
  457. var result = await UserManager.CreateAsync(user, model.Password);
  458. if (result.Succeeded)
  459. {
  460. await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
  461. Session["NewSessoinId"] = Guid.NewGuid();
  462. Session.Timeout = 18;
  463. // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
  464. // Send an email with this link
  465. await CreateConfirmEmail(user);
  466. // TempData["RegisterSuccess"] = model;
  467. ViewBag.Email = model.Email;
  468. AuthenticationManager.SignOut();
  469. return View("EmailSended");
  470. }
  471. AddErrors(result);
  472. }
  473.  
  474. // If we got this far, something failed, redisplay form
  475. return View(model);
  476. }
  477.  
  478. [HttpPost]
  479. //[AllowAnonymous]
  480. public async Task<JsonResult> VerifyEmail(string mail)
  481. {
  482. try
  483. {
  484. var m = new System.Net.Mail.MailAddress(mail);
  485. await UserManager.SetEmailAsync(UserInfo.Id, mail);
  486.  
  487. ApplicationUser user = await UserManager.FindByIdAsync(UserInfo.Id);
  488. //закомментировано после переходна на SQL Server
  489. //await Igasolina.UpdateUserEmail(user.UserName, user.Email, GasolinaSessionID, ClientIP);
  490.  
  491. await CreateConfirmEmail(user);
  492. return VerifyEmailSended(true);// RedirectToAction("VerifyEmailSended");
  493. }
  494. catch { VerifyEmailSended(false); }
  495.  
  496. return VerifyEmailSended(false);
  497. }
  498.  
  499. public JsonResult VerifyEmailSended(bool valid) { return Json(new { emailsended = valid }, JsonRequestBehavior.AllowGet); }
  500.  
  501. // GET: /Account/ConfirmEmail
  502. [AllowAnonymous]
  503. public async Task<ActionResult> ConfirmEmail(int? userId, string code)
  504. {
  505. if (userId == null || code == null) { return View("Error"); }
  506. var result = await UserManager.ConfirmEmailAsync(userId.Value, code);
  507.  
  508. if (result.Succeeded)
  509. {
  510. try
  511. {
  512. foreach (var err in result.Errors) { LogService.Error(err); }
  513. }
  514. catch (Exception ex) { LogService.Error(ex); }
  515. var user = await UserManager.FindByIdAsync(userId.Value);
  516. }
  517.  
  518. return View(result.Succeeded ? "ConfirmEmail" : "Error");
  519. }
  520.  
  521. //
  522. // GET: /Account/ForgotPassword
  523. [AllowAnonymous]
  524. public ActionResult ForgotPassword()
  525. {
  526. return View();
  527. }
  528.  
  529. //
  530. // POST: /Account/ForgotPassword
  531. [HttpPost]
  532. [AllowAnonymous]
  533. [ValidateAntiForgeryToken]
  534. public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
  535. {
  536. if (ModelState.IsValid)
  537. {
  538. var user = await UserManager.FindByNameAsync(model.PersonalAccount);
  539. //if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
  540. //{
  541. // ModelState.AddModelError("", "Особовий рахунок не знайдено або електронна адреса не актуалізована");
  542. // // Don't reveal that the user does not exist or is not confirmed
  543. // return View("ForgotPassword", model);
  544. //}
  545.  
  546. if (user == null)
  547. {
  548. ModelState.AddModelError("", "Особовий рахунок не знайдено");
  549. return View("ForgotPassword", model);
  550. }
  551.  
  552. //For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
  553. //Send an email with this link
  554. string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
  555. var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
  556. //await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
  557. //return RedirectToAction("ForgotPasswordConfirmation", "Account");
  558.  
  559. string messagebody = IEmailsender.GetEMailTemplate(Server.MapPath(@"~\App_Data\EmailTemplate\ForgotPassword.html"));
  560. messagebody = messagebody.Replace("{0}", user.UserFio);
  561. messagebody = messagebody.Replace("{1}", callbackUrl);
  562. messagebody = messagebody.Replace("{2}", callbackUrl);
  563. messagebody = messagebody.Replace("{3}", user.UserName);
  564.  
  565. _logger.Info(model.PersonalAccount, "ForgotPassword", "ForgotPassword SEND EMAIL START", false, "");
  566. //"Будь-ласка підтвердіть свій обліковий запис. Перейдіть за посиланням <a href=\"" + callbackUrl + "\"> сюди </a>"
  567. await UserManager.SendEmailAsync(user.Id, "КиївГазЕнерджи: Зміна паролю", messagebody);
  568.  
  569. int indexof = user.Email.IndexOf("@");
  570. if (indexof > 0)
  571. {
  572. var mail = user.Email.Substring(0, 1) + "**************";
  573. mail = mail + user.Email.Substring(indexof, user.Email.Length - indexof);
  574. TempData["ForgotPassword_Email"] = mail;
  575. }
  576. else { TempData["ForgotPassword_Email"] = string.Empty; }
  577.  
  578. _logger.Info(model.PersonalAccount, "ForgotPassword", "ForgotPassword SEND EMAIL END", false, "");
  579. return RedirectToAction("ForgotPasswordConfirmation", "Account");
  580. }
  581.  
  582. // If we got this far, something failed, redisplay form
  583. return View(model);
  584. }
  585.  
  586. //
  587. // GET: /Account/ForgotPasswordConfirmation
  588. [AllowAnonymous]
  589. public ActionResult ForgotPasswordConfirmation()
  590. {
  591. ViewBag.Email = TempData["ForgotPassword_Email"];
  592. return View();
  593. }
  594.  
  595. //
  596. // GET: /Account/ResetPassword
  597. [AllowAnonymous]
  598. public ActionResult ResetPassword(string code) { return code == null ? View("Error") : View(); }
  599.  
  600. //
  601. // POST: /Account/ResetPassword
  602. [HttpPost]
  603. [AllowAnonymous]
  604. [ValidateAntiForgeryToken]
  605. public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
  606. {
  607. _logger.Info(model.PersonalAccount, "ResetPassword Start", "Start", true, "");
  608.  
  609. if (!ModelState.IsValid) { return View(model); }
  610. var user = await UserManager.FindByNameAsync(model.PersonalAccount);
  611. if (user == null)
  612. {
  613. // Don't reveal that the user does not exist
  614. return RedirectToAction("ResetPasswordConfirmation", "Account");
  615. }
  616. var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
  617.  
  618. if (result.Succeeded)
  619. {
  620. UserManager.ResetAccessFailedCount(user.Id);
  621. await UserManager.SetLockoutEndDateAsync(user.Id, DateTimeOffset.Now.AddYears(-2));
  622. //закомментировано после переходна на SQL Server
  623. #region MyRegion
  624.  
  625.  
  626. //using (ApplicationDbContext UsersContext = new ApplicationDbContext())
  627. //{
  628. // try
  629. // {
  630. // var user_edit = UsersContext.Users.Where(x => x.UserName == model.PersonalAccount).FirstOrDefault();
  631.  
  632. // LoginViewModel lg = new LoginViewModel
  633. // {
  634. // PersonalAccount = model.PersonalAccount,
  635. // Password = user_edit.parametry
  636. // };
  637.  
  638.  
  639.  
  640. // var rez = Igasolina.LogIn(lg, ClientIP);//Попытка логинится в газолине
  641.  
  642. // if (rez.Result.RequestResult == WebRequestResultEnum.AutenficationSuccess && rez.Result.ResultObject.ToString().Length > 0)
  643. // {
  644. // //успешно , получить sessionid
  645. // GasolinaSessionID = rez.Result.ResultObject.ToString();
  646. // }
  647.  
  648. // var rez_update = await Igasolina.UpdateUserData(model.PersonalAccount, user.parametry, model.Password, GasolinaSessionID, ClientIP);
  649. // if (rez_update.RequestResult != WebRequestResultEnum.Succes)
  650. // {
  651. // user_edit.parametry = model.Password;
  652. // await UsersContext.SaveChangesAsync();
  653. // }
  654.  
  655.  
  656. // }
  657. // catch (Exception er)
  658. // {
  659. // LogService.Error(er, "ResetPassword");
  660. // }
  661.  
  662. //}
  663. #endregion
  664. using (ApplicationDbContext usersContext = new ApplicationDbContext())
  665. {
  666. try
  667. {
  668. var userForEditing = usersContext.Users.Where(x => x.UserName == model.PersonalAccount).FirstOrDefault();
  669. LoginViewModel lg = new LoginViewModel
  670. {
  671. PersonalAccount = model.PersonalAccount,
  672. Password = userForEditing.parametry
  673. };
  674. userForEditing.parametry = model.Password;
  675. await usersContext.SaveChangesAsync();
  676. _logger.Info(model.PersonalAccount, "ResetPassword End", string.Format("Succes new Password {0}", userForEditing.parametry), false, "");
  677. }
  678. catch (Exception er)
  679. {
  680. _logger.Info(model.PersonalAccount, "ResetPassword Change paramY", "Start", false, "");
  681. LogService.Error(er, "ResetPassword");
  682. }
  683. }
  684. return RedirectToAction("ResetPasswordConfirmation", "Account");
  685. }
  686. AddErrors(result);
  687. return View();
  688. }
  689.  
  690. //
  691. // GET: /Account/ResetPasswordConfirmation
  692. [AllowAnonymous]
  693. public ActionResult ResetPasswordConfirmation() { return View(); }
  694.  
  695. //
  696. // POST: /Account/ExternalLogin
  697. [HttpPost]
  698. [AllowAnonymous]
  699. [ValidateAntiForgeryToken]
  700. public ActionResult ExternalLogin(string provider, string returnUrl)
  701. {
  702. // Request a redirect to the external login provider
  703. return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
  704. }
  705.  
  706. //
  707. // GET: /Account/SendCode
  708. [AllowAnonymous]
  709. public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
  710. {
  711. var userId = await SignInManager.GetVerifiedUserIdAsync();
  712. if (userId < 1) { return View("Error"); }
  713. var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
  714. var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
  715. return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
  716. }
  717.  
  718. //
  719. // POST: /Account/SendCode
  720. [HttpPost]
  721. [AllowAnonymous]
  722. [ValidateAntiForgeryToken]
  723. public async Task<ActionResult> SendCode(SendCodeViewModel model)
  724. {
  725. if (!ModelState.IsValid) { return View(); }
  726.  
  727. // Generate the token and send it
  728. if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider)) { return View("Error"); }
  729. return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
  730. }
  731.  
  732. //
  733. // GET: /Account/ExternalLoginCallback
  734. [AllowAnonymous]
  735. public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
  736. {
  737. var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
  738. if (loginInfo == null) { return RedirectToAction("Login"); }
  739.  
  740. // Sign in the user with this external login provider if the user already has a login
  741. var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
  742. switch (result)
  743. {
  744. case SignInStatus.Success:
  745. Session["NewSessoinId"] = Guid.NewGuid();
  746. Session.Timeout = 18;
  747. return RedirectToLocal(returnUrl);
  748. case SignInStatus.LockedOut:
  749. return View("Lockout");
  750. case SignInStatus.RequiresVerification:
  751. return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
  752. case SignInStatus.Failure:
  753. default:
  754. // If the user does not have an account, then prompt the user to create an account
  755. ViewBag.ReturnUrl = returnUrl;
  756. ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
  757. return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
  758. }
  759. }
  760.  
  761. //
  762. // POST: /Account/ExternalLoginConfirmation
  763. [HttpPost]
  764. [AllowAnonymous]
  765. [ValidateAntiForgeryToken]
  766. public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
  767. {
  768. if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Manage"); }
  769.  
  770. if (ModelState.IsValid)
  771. {
  772. // Get the information about the user from the external login provider
  773. var info = await AuthenticationManager.GetExternalLoginInfoAsync();
  774. if (info == null) { return View("ExternalLoginFailure"); }
  775. var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
  776. var result = await UserManager.CreateAsync(user);
  777. if (result.Succeeded)
  778. {
  779. result = await UserManager.AddLoginAsync(user.Id, info.Login);
  780. if (result.Succeeded)
  781. {
  782. await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
  783. Session["NewSessoinId"] = Guid.NewGuid();
  784. Session.Timeout = 18;
  785. return RedirectToLocal(returnUrl);
  786. }
  787. }
  788. AddErrors(result);
  789. }
  790.  
  791. ViewBag.ReturnUrl = returnUrl;
  792. return View(model);
  793. }
  794.  
  795. //
  796. // POST: /Account/LogOff
  797. [HttpPost]
  798. [ValidateAntiForgeryToken]
  799. [TrackLoginsFilter(true)]
  800. public ActionResult LogOff()
  801. {
  802. AuthenticationManager.SignOut();
  803. //Igasolina.LogOff(UserInfo.UserName, GasolinaSessionID, ClientIP);
  804.  
  805. var fhfgh = Session["SiteType"];
  806. GasolinaSessionID = string.Empty;
  807.  
  808. var fhfghere = Session["SiteType"];
  809. return RedirectToAction("Index", "Client");
  810. }
  811.  
  812. //
  813. // GET: /Account/ExternalLoginFailure
  814. [AllowAnonymous]
  815. public ActionResult ExternalLoginFailure() { return View(); }
  816.  
  817. #region Helpers
  818. // Used for XSRF protection when adding external logins
  819. private const string XsrfKey = "XsrfId";
  820.  
  821. private IAuthenticationManager AuthenticationManager
  822. {
  823. get { return HttpContext.GetOwinContext().Authentication; }
  824. }
  825.  
  826. private void AddErrors(IdentityResult result)
  827. {
  828. foreach (var error in result.Errors) { ModelState.AddModelError("", error); }
  829. }
  830.  
  831. private ActionResult RedirectToLocal(string returnUrl)
  832. {
  833. if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); }
  834. return RedirectToAction("Index", "Client");
  835. }
  836.  
  837. internal class ChallengeResult : HttpUnauthorizedResult
  838. {
  839. public ChallengeResult(string provider, string redirectUri)
  840. : this(provider, redirectUri, null)
  841. { }
  842.  
  843. public ChallengeResult(string provider, string redirectUri, string userId)
  844. {
  845. LoginProvider = provider;
  846. RedirectUri = redirectUri;
  847. UserId = userId;
  848. }
  849.  
  850. public string LoginProvider { get; set; }
  851. public string RedirectUri { get; set; }
  852. public string UserId { get; set; }
  853.  
  854. public override void ExecuteResult(ControllerContext context)
  855. {
  856. var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
  857. if (UserId != null) { properties.Dictionary[XsrfKey] = UserId; }
  858. context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
  859. }
  860. }
  861. #endregion
  862. }
  863. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement