Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Globalization;
- using System.Linq;
- using System.Security.Claims;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Mvc;
- using Microsoft.AspNet.Identity;
- using Microsoft.AspNet.Identity.Owin;
- using Microsoft.Owin.Security;
- using my.kyivgaz.Models;
- using my.kyivgaz.DataInterface;
- using my.kyivgaz.Filter;
- using ExternalNotificationServises;
- using DataModels.Gasolina;
- using DataLibrary.Cabinet.Abstract;
- using DataLibrary.Cabinet;
- namespace my.kyivgaz.Controllers
- {
- //[NoCache]
- [FilterGasolinaSession]
- public class AccountController : BaseController
- {
- private readonly ICabinetRepository _cabinetRepository;
- private IEmailSender IEmailsender;
- ILogger _logger;
- public AccountController(ICabinetRepository cabinetRepository, IEmailSender _IEmailsender, ILogger logger)
- {
- IEmailsender = _IEmailsender;
- _cabinetRepository = cabinetRepository;
- _logger = logger;
- }
- #region оригинал контролера
- //private ApplicationUserManager _userManager;
- //public AccountController()
- //{
- //}
- //public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
- //{
- // UserManager = userManager;
- // SignInManager = signInManager;
- //}
- //public ApplicationUserManager UserManager
- //{
- // get
- // {
- // return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
- // }
- // private set
- // {
- // _userManager = value;
- // }
- //}
- //private ApplicationSignInManager _signInManager;
- //public ApplicationSignInManager SignInManager
- //{
- // get
- // {
- // return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
- // }
- // private set { _signInManager = value; }
- //}
- #endregion
- //
- // GET: /Account/Login
- [AllowAnonymous]
- public ActionResult Login(string returnUrl, string id, string num)
- {
- if (num != null) { Session["SiteType"] = num == "kievgas" ? num: "energy"; }
- ViewBag.PersonalAccount = (id == null) ? "" : id;
- ViewBag.ReturnUrl = returnUrl;
- ViewBag.SessionEnd = TempData["sessioend"];
- return View();
- }
- //private async Task SignInAsync(ApplicationUser user, bool isPersistent, string session_id)
- ////private async Task SignInAsync(ApplicationUser user, bool isPersistent)
- ////{
- //// AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
- //// //var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
- //// //identity.AddClaim(new Claim("session_id", session_id));
- //// //AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
- //// AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, await user.GenerateUserIdentityAsync(UserManager));
- ////}
- //
- // POST: /Account/Login
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
- // public ActionResult Login(LoginViewModel model, string returnUrl)
- {
- // LogService.Error("test {0}", model.PersonalAccount);
- // UserManager.RemovePassword(25279);
- // UserManager.AddPassword(25279, model.Password);
- // validCredentials = await UserManager.FindAsync(model.UserName, model.Password);
- if (!ModelState.IsValid)
- {
- return View(model);
- }
- //SignInStatus result = await SignInManager.PasswordSignInAsync(model.PersonalAccount, model.Password, model.RememberMe, shouldLockout: true);
- SignInStatus result;
- try
- {
- result = await SignInManager.PasswordSignInAsync(model.PersonalAccount, model.Password, isPersistent: false, shouldLockout: true);
- }
- catch (Exception ex)
- {
- throw;
- }
- switch (result)
- {
- case SignInStatus.Success:
- Abon abon = _cabinetRepository.Abons.FirstOrDefault(a => a.PersonAccount.Trim() == model.PersonalAccount.Trim());
- Payment lastPayment = _cabinetRepository.Payments
- .FirstOrDefault(p => p.KodR == abon.Kod
- && p.Datic == (_cabinetRepository.Payments.Where(x => x.KodR == abon.Kod).Max(x => x.Datic)));
- double writtenByUserLastPayment;
- Session["NewSessoinId"] = Guid.NewGuid();
- Session.Timeout = 18;
- //ApplicationUser user = await UserManager.FindByNameAsync(model.PersonalAccount);
- AspNetUsers user = _cabinetRepository.AspNetUsers.FirstOrDefault(a => a.UserName == model.PersonalAccount);
- bool successfulParsing = double.TryParse(user.parametrx, out writtenByUserLastPayment);
- if (lastPayment != null && (user.CreateDate.Date == user.LastLogInDate.GetValueOrDefault().Date && writtenByUserLastPayment != lastPayment.Sumic && successfulParsing))
- {
- WaitActivationViewModel model_wait = new WaitActivationViewModel
- {
- parametrx = user.parametrx
- };
- TempData["model_wait"] = model_wait;
- return RedirectToAction("WaitActivation", "Home");
- }
- //return RedirectToLocal(returnUrl);
- ViewBag.SessionSiteType = Session["SiteType"];
- return RedirectToAction("Index", "Client");
- case SignInStatus.LockedOut:
- return View("Lockout");
- case SignInStatus.RequiresVerification:
- return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
- case SignInStatus.Failure:
- default:
- ModelState.AddModelError("", "Невірна спроба входу");
- return View(model);
- }
- }
- //закомментировано после переходна на SQL Server
- //private async Task<SignInStatus> RegistrationUserAuto(LoginViewModel model, string sessiongasolina, SignInStatus result)
- //{
- // //закомментировано после переходна на SQL Server
- // //var user_info_object = Igasolina.GetUserInfo(model.PersonalAccount, sessiongasolina, ClientIP);
- // //GasolinaUserFullInfoModel user_info = new GasolinaUserFullInfoModel
- // //{
- // // user = user_info_object.Result.ResultObject as GasolinaUserModel
- // //};
- // //закомментировано после переходна на SQL Server
- // //var user = new ApplicationUser
- // //{
- // // UserName = model.PersonalAccount,
- // // //Email = user_info.user.data.email,
- // // //UserFio = user_info.user_fio,
- // // //PhoneNumber = user_info.user.data.mobile_phone,
- // // //LandingNumber = user_info.user.data.landing_phone,
- // // isGasolinaFirst = true,
- // // CreateDate = DateTime.Now,
- // // parametry = model.Password
- // //};
- // var user = new ApplicationUser
- // {
- // UserName = model.PersonalAccount,
- // isGasolinaFirst = true,
- // CreateDate = DateTime.Now,
- // parametry = model.Password
- // };
- // var result_create = await UserManager.CreateAsync(user, model.Password);
- // if (result_create.Succeeded)
- // {
- // await SignInAsync(user, model.RememberMe);
- // //закомментировано после переходна на SQL Server
- // //await SignInAsync(user, model.RememberMe, sessiongasolina);
- // //-------------------------это и было закомментировано-------------------
- // //await SignInManager.SignInAsync(user, isPersistent: model.RememberMe, rememberBrowser: model.RememberMe);
- // result = await SignInManager.PasswordSignInAsync(model.PersonalAccount, model.Password, model.RememberMe, shouldLockout: false);
- // await CreateConfirmEmail(user);
- // }
- // return result;
- //}
- private async Task CreateConfirmEmail(ApplicationUser user)
- {
- string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
- var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
- string messagebody = IEmailsender.GetEMailTemplate(Server.MapPath(@"~\App_Data\EmailTemplate\ConfirmEmail.html"));
- messagebody = messagebody.Replace("{0}", user.UserFio);
- messagebody = messagebody.Replace("{1}", callbackUrl);
- messagebody = messagebody.Replace("{2}", callbackUrl);
- messagebody = messagebody.Replace("{3}", user.UserName);
- //"Будь-ласка підтвердіть свій обліковий запис. Перейдіть за посиланням <a href=\"" + callbackUrl + "\"> сюди </a>"
- await UserManager.SendEmailAsync(user.Id, "КиївГазЕнерджи: Підтвердження облікового запису", messagebody);
- }
- //
- // GET: /Account/VerifyCode
- [AllowAnonymous]
- public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
- {
- // Require that the user has already logged in via username/password or external login
- if (!await SignInManager.HasBeenVerifiedAsync())
- {
- return View("Error");
- }
- var user = await UserManager.FindByIdAsync(await SignInManager.GetVerifiedUserIdAsync());
- if (user != null)
- {
- var code = await UserManager.GenerateTwoFactorTokenAsync(user.Id, provider);
- }
- return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
- }
- //
- // POST: /Account/VerifyCode
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
- {
- if (!ModelState.IsValid)
- {
- return View(model);
- }
- // The following code protects for brute force attacks against the two factor codes.
- // If a user enters incorrect codes for a specified amount of time then the user account
- // will be locked out for a specified amount of time.
- // You can configure the account lockout settings in IdentityConfig
- ////var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
- var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: false, rememberBrowser: model.RememberBrowser);
- switch (result)
- {
- case SignInStatus.Success:
- Session["NewSessoinId"] = Guid.NewGuid();
- Session.Timeout = 18;
- return RedirectToLocal(model.ReturnUrl);
- case SignInStatus.LockedOut:
- return View("Lockout");
- case SignInStatus.Failure:
- default:
- ModelState.AddModelError("", "Invalid code.");
- return View(model);
- }
- }
- [HttpPost]
- [AllowAnonymous]
- public async Task<JsonResult> checkregistrationparam(string paramname, string value)
- {
- switch (paramname.ToLower())
- {
- case "personalaccount":
- return Json(new { isempty = (await IsEmptyPersonalAccount(value)) });
- case "email":
- return Json(new { isempty = (await UserManager.FindByEmailAsync(value) == null) });
- //case "phone":
- // return Json(new { isempty = (await UserManager.FindByPhoneAsync(value) == null) });
- default:
- throw new Exception("Параметр перевірки не заданий");
- }
- }
- protected async Task<bool> IsEmptyPersonalAccount(string login)
- {
- bool result;
- string lastNumber = login[login.Length - 1].ToString();
- if (login.Length == 10 && lastNumber != "1")
- {
- result = await UserManager.FindByNameAsync(login) == null;
- ApplicationUser foundUser = await UserManager.FindByNameAsync(login);
- }
- else if (login.Length == 10 && lastNumber == "1")
- {
- string shorterLogin = login.Substring(0, login.Length - 1);
- ApplicationUser userWithOneNumber = await UserManager.FindByNameAsync(login);
- ApplicationUser userWithoutOneNumber = await UserManager.FindByNameAsync(shorterLogin);
- result = userWithOneNumber == null && userWithoutOneNumber == null;
- }
- else if (login.Length == 9)
- {
- string longerString = login + "1";
- ApplicationUser userWithOneNumber = await UserManager.FindByNameAsync(longerString);
- ApplicationUser userWithoutOneNumber = await UserManager.FindByNameAsync(login);
- result = userWithOneNumber == null && userWithoutOneNumber == null;
- }
- else
- {
- //throw new Exception()
- return false;
- }
- return result;
- }
- //
- // GET: /Account/Register
- [AllowAnonymous]
- public ActionResult Register()
- {
- return View();
- }
- //
- // POST: /Account/Register
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> Register(RegisterViewModel model)
- {
- if (ModelState.IsValid)
- {
- if (!await IsEmptyPersonalAccount(model.PersonalAccount))
- {
- ModelState.AddModelError("", "Користувач з таким особовим рахунком уже зареєстровано в системі.");
- return View(model);
- }
- ////закомментили как ненужное после переезда на SQL Server
- //RegisterViewModel reg_model = new RegisterViewModel
- //{
- // Password = model.Password,
- // PersonalAccount = model.PersonalAccount,
- // parametrx = model.parametrx,
- // Email = model.Email
- //};
- ////закомментили как ненужное после переезда на SQL Server
- ////регистрация пользователя в билинге
- //var rez_rez = await Igasolina.Registration(reg_model, ClientIP);
- //if (rez_rez.RequestResult == WebRequestResultEnum.Error)
- //{
- // ModelState.AddModelError("", rez_rez.errortext);
- // return View(model);
- //}
- var user = new ApplicationUser
- {
- UserName = model.PersonalAccount,
- CreateDate = DateTime.Now,
- Email = model.Email,
- parametrx = model.parametrx,
- parametry = model.Password,
- isGasolinaFirst = false
- };
- Abon abon = _cabinetRepository.Abons.FirstOrDefault(a => a.PersonAccount == model.PersonalAccount);
- if (abon == null)
- {
- if (model.PersonalAccount.Length == 9)
- {
- string searchString1 = model.PersonalAccount + "1";
- abon = _cabinetRepository.Abons.FirstOrDefault(a => a.PersonAccount == searchString1);
- }
- else if (model.PersonalAccount.Length == 10)
- {
- string searchString2 = model.PersonalAccount.Substring(0, 9);
- abon = _cabinetRepository.Abons.FirstOrDefault(a => a.PersonAccount == model.PersonalAccount + "1");
- }
- }
- if (abon != null)
- {
- if (abon.FirstName == null)
- user.UserFio = abon.Name.Trim();
- else if (abon.FirstName != null && abon.Patronymic == null)
- user.UserFio = string.Format("{0} {1}", abon.Name.Trim(), abon.FirstName.Trim());
- else if (abon.FirstName != null && abon.Patronymic != null)
- user.UserFio = string.Format("{0} {1} {2}", abon.Name.Trim(), abon.FirstName.Trim(), abon.Patronymic.Trim());
- AbonentPhone[] allAbonentPhones = _cabinetRepository.AbonentPhones
- .Where(ap => ap.KodR == abon.Kod).ToArray();
- AbonentPhone homePhone;
- if (allAbonentPhones.Any(x => x.Main.GetValueOrDefault(false) && x.PhoneTypeName == "home"))
- homePhone = allAbonentPhones.FirstOrDefault(x => x.Main.GetValueOrDefault(false) && x.PhoneTypeName == "home");
- else
- homePhone = allAbonentPhones.FirstOrDefault(x => x.PhoneTypeName == "home");
- if (homePhone != null)
- user.LandingNumber = homePhone.GetPhoneNumberWithRegionOrMobileCode();
- AbonentPhone mobilePhone;
- if (allAbonentPhones.Any(x => x.Main.GetValueOrDefault(false) && x.PhoneTypeName == "cell"))
- mobilePhone = allAbonentPhones.FirstOrDefault(x => x.Main.GetValueOrDefault(false) && x.PhoneTypeName == "cell");
- else
- mobilePhone = allAbonentPhones.FirstOrDefault(x => x.PhoneTypeName == "cell");
- if (mobilePhone != null)
- user.PhoneNumber = mobilePhone.GetPhoneNumberWithRegionOrMobileCode();
- if (!_cabinetRepository.Payments.Any(p => p.KodR == abon.Kod))
- {
- ModelState.AddModelError("", "Ви не можете зареєструватися, оскільки у Вас немає жодної оплати. Реєстрація стане доступною після першої оплати.");
- return View(model);
- }
- var LastSum = _cabinetRepository.Payments
- .Where(p => p.KodR == abon.Kod)
- .OrderByDescending(o => o.Datic)
- .Select(s => s.Sumic).FirstOrDefault();
- if(LastSum != 0.0)
- {
- string paramx = Convert.ToString(model.parametrx).Replace(".", ",");
- // string lastpay = Convert.ToString(LastSum);
- string lastpay = String.Format("{0:0.00}", LastSum);
- if (lastpay != paramx)
- {
- ModelState.AddModelError("", "Не вірна сума останнього платежу.");
- return View(model);
- }
- }
- }
- else
- {
- ModelState.AddModelError("", "Такого особового рахунку не існує.");
- return View(model);
- }
- var result = await UserManager.CreateAsync(user, model.Password);
- if (result.Succeeded)
- {
- await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
- Session["NewSessoinId"] = Guid.NewGuid();
- Session.Timeout = 18;
- // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
- // Send an email with this link
- await CreateConfirmEmail(user);
- // TempData["RegisterSuccess"] = model;
- ViewBag.Email = model.Email;
- AuthenticationManager.SignOut();
- return View("EmailSended");
- }
- AddErrors(result);
- }
- // If we got this far, something failed, redisplay form
- return View(model);
- }
- [HttpPost]
- //[AllowAnonymous]
- public async Task<JsonResult> VerifyEmail(string mail)
- {
- try
- {
- var m = new System.Net.Mail.MailAddress(mail);
- await UserManager.SetEmailAsync(UserInfo.Id, mail);
- ApplicationUser user = await UserManager.FindByIdAsync(UserInfo.Id);
- //закомментировано после переходна на SQL Server
- //await Igasolina.UpdateUserEmail(user.UserName, user.Email, GasolinaSessionID, ClientIP);
- await CreateConfirmEmail(user);
- return VerifyEmailSended(true);// RedirectToAction("VerifyEmailSended");
- }
- catch { VerifyEmailSended(false); }
- return VerifyEmailSended(false);
- }
- public JsonResult VerifyEmailSended(bool valid) { return Json(new { emailsended = valid }, JsonRequestBehavior.AllowGet); }
- // GET: /Account/ConfirmEmail
- [AllowAnonymous]
- public async Task<ActionResult> ConfirmEmail(int? userId, string code)
- {
- if (userId == null || code == null) { return View("Error"); }
- var result = await UserManager.ConfirmEmailAsync(userId.Value, code);
- if (result.Succeeded)
- {
- try
- {
- foreach (var err in result.Errors) { LogService.Error(err); }
- }
- catch (Exception ex) { LogService.Error(ex); }
- var user = await UserManager.FindByIdAsync(userId.Value);
- }
- return View(result.Succeeded ? "ConfirmEmail" : "Error");
- }
- //
- // GET: /Account/ForgotPassword
- [AllowAnonymous]
- public ActionResult ForgotPassword()
- {
- return View();
- }
- //
- // POST: /Account/ForgotPassword
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
- {
- if (ModelState.IsValid)
- {
- var user = await UserManager.FindByNameAsync(model.PersonalAccount);
- //if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
- //{
- // ModelState.AddModelError("", "Особовий рахунок не знайдено або електронна адреса не актуалізована");
- // // Don't reveal that the user does not exist or is not confirmed
- // return View("ForgotPassword", model);
- //}
- if (user == null)
- {
- ModelState.AddModelError("", "Особовий рахунок не знайдено");
- return View("ForgotPassword", model);
- }
- //For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
- //Send an email with this link
- string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
- var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
- //await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
- //return RedirectToAction("ForgotPasswordConfirmation", "Account");
- string messagebody = IEmailsender.GetEMailTemplate(Server.MapPath(@"~\App_Data\EmailTemplate\ForgotPassword.html"));
- messagebody = messagebody.Replace("{0}", user.UserFio);
- messagebody = messagebody.Replace("{1}", callbackUrl);
- messagebody = messagebody.Replace("{2}", callbackUrl);
- messagebody = messagebody.Replace("{3}", user.UserName);
- _logger.Info(model.PersonalAccount, "ForgotPassword", "ForgotPassword SEND EMAIL START", false, "");
- //"Будь-ласка підтвердіть свій обліковий запис. Перейдіть за посиланням <a href=\"" + callbackUrl + "\"> сюди </a>"
- await UserManager.SendEmailAsync(user.Id, "КиївГазЕнерджи: Зміна паролю", messagebody);
- int indexof = user.Email.IndexOf("@");
- if (indexof > 0)
- {
- var mail = user.Email.Substring(0, 1) + "**************";
- mail = mail + user.Email.Substring(indexof, user.Email.Length - indexof);
- TempData["ForgotPassword_Email"] = mail;
- }
- else { TempData["ForgotPassword_Email"] = string.Empty; }
- _logger.Info(model.PersonalAccount, "ForgotPassword", "ForgotPassword SEND EMAIL END", false, "");
- return RedirectToAction("ForgotPasswordConfirmation", "Account");
- }
- // If we got this far, something failed, redisplay form
- return View(model);
- }
- //
- // GET: /Account/ForgotPasswordConfirmation
- [AllowAnonymous]
- public ActionResult ForgotPasswordConfirmation()
- {
- ViewBag.Email = TempData["ForgotPassword_Email"];
- return View();
- }
- //
- // GET: /Account/ResetPassword
- [AllowAnonymous]
- public ActionResult ResetPassword(string code) { return code == null ? View("Error") : View(); }
- //
- // POST: /Account/ResetPassword
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
- {
- _logger.Info(model.PersonalAccount, "ResetPassword Start", "Start", true, "");
- if (!ModelState.IsValid) { return View(model); }
- var user = await UserManager.FindByNameAsync(model.PersonalAccount);
- if (user == null)
- {
- // Don't reveal that the user does not exist
- return RedirectToAction("ResetPasswordConfirmation", "Account");
- }
- var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
- if (result.Succeeded)
- {
- UserManager.ResetAccessFailedCount(user.Id);
- await UserManager.SetLockoutEndDateAsync(user.Id, DateTimeOffset.Now.AddYears(-2));
- //закомментировано после переходна на SQL Server
- #region MyRegion
- //using (ApplicationDbContext UsersContext = new ApplicationDbContext())
- //{
- // try
- // {
- // var user_edit = UsersContext.Users.Where(x => x.UserName == model.PersonalAccount).FirstOrDefault();
- // LoginViewModel lg = new LoginViewModel
- // {
- // PersonalAccount = model.PersonalAccount,
- // Password = user_edit.parametry
- // };
- // var rez = Igasolina.LogIn(lg, ClientIP);//Попытка логинится в газолине
- // if (rez.Result.RequestResult == WebRequestResultEnum.AutenficationSuccess && rez.Result.ResultObject.ToString().Length > 0)
- // {
- // //успешно , получить sessionid
- // GasolinaSessionID = rez.Result.ResultObject.ToString();
- // }
- // var rez_update = await Igasolina.UpdateUserData(model.PersonalAccount, user.parametry, model.Password, GasolinaSessionID, ClientIP);
- // if (rez_update.RequestResult != WebRequestResultEnum.Succes)
- // {
- // user_edit.parametry = model.Password;
- // await UsersContext.SaveChangesAsync();
- // }
- // }
- // catch (Exception er)
- // {
- // LogService.Error(er, "ResetPassword");
- // }
- //}
- #endregion
- using (ApplicationDbContext usersContext = new ApplicationDbContext())
- {
- try
- {
- var userForEditing = usersContext.Users.Where(x => x.UserName == model.PersonalAccount).FirstOrDefault();
- LoginViewModel lg = new LoginViewModel
- {
- PersonalAccount = model.PersonalAccount,
- Password = userForEditing.parametry
- };
- userForEditing.parametry = model.Password;
- await usersContext.SaveChangesAsync();
- _logger.Info(model.PersonalAccount, "ResetPassword End", string.Format("Succes new Password {0}", userForEditing.parametry), false, "");
- }
- catch (Exception er)
- {
- _logger.Info(model.PersonalAccount, "ResetPassword Change paramY", "Start", false, "");
- LogService.Error(er, "ResetPassword");
- }
- }
- return RedirectToAction("ResetPasswordConfirmation", "Account");
- }
- AddErrors(result);
- return View();
- }
- //
- // GET: /Account/ResetPasswordConfirmation
- [AllowAnonymous]
- public ActionResult ResetPasswordConfirmation() { return View(); }
- //
- // POST: /Account/ExternalLogin
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public ActionResult ExternalLogin(string provider, string returnUrl)
- {
- // Request a redirect to the external login provider
- return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
- }
- //
- // GET: /Account/SendCode
- [AllowAnonymous]
- public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
- {
- var userId = await SignInManager.GetVerifiedUserIdAsync();
- if (userId < 1) { return View("Error"); }
- var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
- var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
- return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
- }
- //
- // POST: /Account/SendCode
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> SendCode(SendCodeViewModel model)
- {
- if (!ModelState.IsValid) { return View(); }
- // Generate the token and send it
- if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider)) { return View("Error"); }
- return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
- }
- //
- // GET: /Account/ExternalLoginCallback
- [AllowAnonymous]
- public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
- {
- var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
- if (loginInfo == null) { return RedirectToAction("Login"); }
- // Sign in the user with this external login provider if the user already has a login
- var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
- switch (result)
- {
- case SignInStatus.Success:
- Session["NewSessoinId"] = Guid.NewGuid();
- Session.Timeout = 18;
- return RedirectToLocal(returnUrl);
- case SignInStatus.LockedOut:
- return View("Lockout");
- case SignInStatus.RequiresVerification:
- return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
- case SignInStatus.Failure:
- default:
- // If the user does not have an account, then prompt the user to create an account
- ViewBag.ReturnUrl = returnUrl;
- ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
- return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
- }
- }
- //
- // POST: /Account/ExternalLoginConfirmation
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
- {
- if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Manage"); }
- if (ModelState.IsValid)
- {
- // Get the information about the user from the external login provider
- var info = await AuthenticationManager.GetExternalLoginInfoAsync();
- if (info == null) { return View("ExternalLoginFailure"); }
- var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
- var result = await UserManager.CreateAsync(user);
- if (result.Succeeded)
- {
- result = await UserManager.AddLoginAsync(user.Id, info.Login);
- if (result.Succeeded)
- {
- await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
- Session["NewSessoinId"] = Guid.NewGuid();
- Session.Timeout = 18;
- return RedirectToLocal(returnUrl);
- }
- }
- AddErrors(result);
- }
- ViewBag.ReturnUrl = returnUrl;
- return View(model);
- }
- //
- // POST: /Account/LogOff
- [HttpPost]
- [ValidateAntiForgeryToken]
- [TrackLoginsFilter(true)]
- public ActionResult LogOff()
- {
- AuthenticationManager.SignOut();
- //Igasolina.LogOff(UserInfo.UserName, GasolinaSessionID, ClientIP);
- var fhfgh = Session["SiteType"];
- GasolinaSessionID = string.Empty;
- var fhfghere = Session["SiteType"];
- return RedirectToAction("Index", "Client");
- }
- //
- // GET: /Account/ExternalLoginFailure
- [AllowAnonymous]
- public ActionResult ExternalLoginFailure() { return View(); }
- #region Helpers
- // Used for XSRF protection when adding external logins
- private const string XsrfKey = "XsrfId";
- private IAuthenticationManager AuthenticationManager
- {
- get { return HttpContext.GetOwinContext().Authentication; }
- }
- private void AddErrors(IdentityResult result)
- {
- foreach (var error in result.Errors) { ModelState.AddModelError("", error); }
- }
- private ActionResult RedirectToLocal(string returnUrl)
- {
- if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); }
- return RedirectToAction("Index", "Client");
- }
- internal class ChallengeResult : HttpUnauthorizedResult
- {
- public ChallengeResult(string provider, string redirectUri)
- : this(provider, redirectUri, null)
- { }
- public ChallengeResult(string provider, string redirectUri, string userId)
- {
- LoginProvider = provider;
- RedirectUri = redirectUri;
- UserId = userId;
- }
- public string LoginProvider { get; set; }
- public string RedirectUri { get; set; }
- public string UserId { get; set; }
- public override void ExecuteResult(ControllerContext context)
- {
- var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
- if (UserId != null) { properties.Dictionary[XsrfKey] = UserId; }
- context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
- }
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement