public async Task <IActionResult> LinkLoginCallback()
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var info = await _signInManager.GetExternalLoginInfoAsync(user.Id);

            if (info == null)
            {
                throw new ApplicationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'.");
            }

            var result = await _userManager.AddLoginAsync(user, info);

            if (!result.Succeeded)
            {
                throw new ApplicationException($"Unexpected error occurred adding external login for user with ID '{user.Id}'.");
            }

            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            StatusMessage = "Połączenie z zewnętrznym systemem zostało dodane.";
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(RedirectToAction(nameof(ExternalLogins)));
        }
Exemple #2
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            ValidationResult retval = new ValidationResult("");
            IPhoneModel      rvm    = (IPhoneModel)validationContext.ObjectInstance;

            if (string.IsNullOrEmpty(rvm.Phone))
            {
                retval.ErrorMessage += "Numer telefonu nie może być pusty.";
            }
            else
            {
                string values = rvm.Phone.Replace("+48", "");
                int    digit  = 0;
                foreach (char c in values)
                {
                    if (char.IsDigit(c))
                    {
                        digit++;
                    }
                }


                if (digit != 9)
                {
                    retval.ErrorMessage += "Numer telefonu składa się z 9 cyfr.";
                }
            }
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);

            return(string.IsNullOrEmpty(retval.ErrorMessage) ? ValidationResult.Success : retval);
        }
        public async Task <IActionResult> Index()
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Nie odnaleziono użytkownika o ID '{_userManager.GetUserId(User)}'.");
            }

            var model = new Models.ManageViewModels.IndexViewModel
            {
                Username         = user.UserName,
                Email            = user.Email,
                IsEmailConfirmed = user.EmailConfirmed,
                StatusMessage    = StatusMessage
            };

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);

            return(View(model));
        }
        public async Task <IActionResult> RemoveLogin(RemoveLoginViewModel model)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var result = await _userManager.RemoveLoginAsync(user, model.LoginProvider, model.ProviderKey);

            if (!result.Succeeded)
            {
                throw new ApplicationException($"Unexpected error occurred removing external login for user with ID '{user.Id}'.");
            }

            await _signInManager.SignInAsync(user, isPersistent : false);

            StatusMessage = "Połączenie z zewnętrznym systemem zostało usunięte.";
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(RedirectToAction(nameof(ExternalLogins)));
        }
        public async Task <IActionResult> Index(Models.ManageViewModels.IndexViewModel model)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Nie odnaleziono użytkownika o ID '{_userManager.GetUserId(User)}'.");
            }

            var email = user.Email;

            if (model.Email != email)
            {
                var setEmailResult = await _userManager.SetEmailAsync(user, model.Email);

                if (!setEmailResult.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
                }
            }

            StatusMessage = "Profil został zaktualizowany";

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(RedirectToAction(nameof(Index)));
        }
        public async Task <IActionResult> SetPassword()
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var hasPassword = await _userManager.HasPasswordAsync(user);

            if (hasPassword)
            {
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(RedirectToAction(nameof(ChangePassword)));
            }

            var model = new SetPasswordViewModel {
                StatusMessage = StatusMessage
            };

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(View(model));
        }
Exemple #7
0
        public IActionResult AllRepairs()
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            List <Repair>             repairs = dh.GetAllRepair();
            List <AddRepairViewModel> model   = new List <AddRepairViewModel>();
            int i = 0;

            foreach (Repair repair in repairs)
            {
                i++;
                AddRepairViewModel addRepair = createEmptyModel();
                addRepair.Client.Name              = repair.Device.Client.Name.Name + " " + repair.Device.Client.LastName.LastName;
                addRepair.Client.Phone             = repair.Device.Client.Phone;
                addRepair.Device.Brand             = repair.Device.Brand.Brand;
                addRepair.Device.ModelName         = repair.Device.Model.Model;
                addRepair.Repair.DamageDescription = repair.RepairDetail;
                addRepair.Repair.DateOfAcceptance  = repair.Acceptance;
                addRepair.Number = i;
                model.Add(addRepair);
            }
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(View(model));
        }
        public async Task <IActionResult> ExternalLogins()
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var model = new ExternalLoginsViewModel {
                CurrentLogins = await _userManager.GetLoginsAsync(user)
            };

            model.OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync())
                                .Where(auth => model.CurrentLogins.All(ul => auth.Name != ul.LoginProvider))
                                .ToList();
            model.ShowRemoveButton = await _userManager.HasPasswordAsync(user) || model.CurrentLogins.Count > 1;

            model.StatusMessage = StatusMessage;

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(View(model));
        }
Exemple #9
0
        public Task SendEmailAsync(string email, string subject, string message)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            var    fromAddress  = new MailAddress(SettingsController.MailAccessModel.Mail, SettingsController.AppName.Name);
            var    toAddress    = new MailAddress(email);
            string fromPassword = SettingsController.MailAccessModel.Password;
            string body         = message;

            var smtp = new SmtpClient
            {
                Host                  = SettingsController.MailAccessModel.Host,
                Port                  = int.Parse(SettingsController.MailAccessModel.Port),
                EnableSsl             = SettingsController.MailAccessModel.EnableSSL,
                DeliveryMethod        = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = false,
                Credentials           = new NetworkCredential(fromAddress.Address, fromPassword)
            };

            using (var mail = new MailMessage(fromAddress, toAddress)
            {
                Subject = subject,
                Body = body
            })
            {
                mail.IsBodyHtml = IsHtmlBody;
                smtp.Send(mail);
            }
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(Task.FromResult(0));
        }
        public async Task <IActionResult> SendVerificationEmail(Models.ManageViewModels.IndexViewModel model)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
            var email       = user.Email;
            await _emailSender.SendEmailConfirmationAsync(email, callbackUrl);

            StatusMessage = "Mail weryfikacyjny został wysłany. Sprawdź swojego maila.";
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(RedirectToAction(nameof(Index)));
        }
        public async Task <IActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            if (!ModelState.IsValid)
            {
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(View(model));
            }
            var user = await _userManager.FindByEmailAsync(model.Email);

            if (user == null)
            {
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(RedirectToAction(nameof(ResetPasswordConfirmation)));
            }
            var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password);

            if (result.Succeeded)
            {
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(RedirectToAction(nameof(ResetPasswordConfirmation)));
            }
            AddErrors(result);
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(View());
        }
        public async Task <IActionResult> GenerateRecoveryCodes()
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            if (!user.TwoFactorEnabled)
            {
                throw new ApplicationException($"Cannot generate recovery codes for user with ID '{user.Id}' as they do not have 2FA enabled.");
            }

            var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);

            _logger.LogInformation("User with ID {UserId} has generated new 2FA recovery codes.", user.Id);

            var model = new ShowRecoveryCodesViewModel {
                RecoveryCodes = recoveryCodes.ToArray()
            };

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(View(nameof(ShowRecoveryCodes), model));
        }
        public async Task <IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(model.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    s.Stop();
                    LoggerController.AddEndMethodLog(this.GetType().Name,
                                                     MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                    return(RedirectToAction(nameof(ForgotPasswordConfirmation)));
                }

                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                var callbackUrl = Url.ResetPasswordCallbackLink(user.Id, code, Request.Scheme);
                await _emailSender.SendEmailAsync(model.Email, "Przywracanie hasła",
                                                  $"Aby zresetować hasło proszę kliknąć w <a href='{callbackUrl}'>link</a>");

                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(RedirectToAction(nameof(ForgotPasswordConfirmation)));
            }

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(View(model));
        }
Exemple #14
0
        public Device GetDevice(string name, string phone, string brand, string model)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            string[] tmp       = name.Split(' ');
            string   _name     = tmp[0];
            string   _lastName = string.Empty;

            if (tmp.Length > 1)
            {
                _lastName = tmp[1];
            }
            Device device = _context.Device.Include(x => x.Client).
                            Include(x => x.Client.LastName).Include(x => x.Client.Name).
                            Include(x => x.Brand).Include(x => x.Model).
                            Where(d => d.Client.Name.Name.Equals(_name) &&
                                  d.Client.LastName.LastName.Equals(_lastName) &&
                                  d.Client.Phone.Equals(phone) &&
                                  d.Brand.Brand.Equals(brand) && d.Model.Model.Equals(model)).
                            FirstOrDefault();

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(device);
        }
Exemple #15
0
        public List <Values> GetAllNames()
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            List <Values> retval  = new List <Values>();
            List <Client> clients = _context.Client.Include(x => x.Name).Include(x => x.LastName).ToList();

            foreach (Client client in clients)
            {
                Values v = new Values()
                {
                    Value = client.Name.Name + " " + client.LastName.LastName,
                    ID    = client.ID
                };
                Values name = retval.Where(x => x.Value.Equals(v.Value)).FirstOrDefault();
                if (name == null)
                {
                    retval.Add(v);
                }
            }
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(retval);
        }
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(model.
                                                                      Email, model.Password, model.RememberMe, lockoutOnFailure : true);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    s.Stop();
                    LoggerController.AddEndMethodLog(this.GetType().Name,
                                                     MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                    return(RedirectToLocal(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    s.Stop();
                    LoggerController.AddEndMethodLog(this.GetType().Name,
                                                     MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                    return(RedirectToAction(nameof(LoginWith2fa), new
                    {
                        returnUrl,
                        model.RememberMe
                    }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    s.Stop();
                    LoggerController.AddEndMethodLog(this.GetType().Name, MethodBase.
                                                     GetCurrentMethod().Name, s.ElapsedMilliseconds);
                    return(RedirectToAction(nameof(Lockout)));
                }
                else
                {
                    ApplicationUser user = await _userManager.FindByEmailAsync(model.Email);

                    if (user != null)
                    {
                        await _userManager.AccessFailedAsync(user);
                    }
                    ModelState.AddModelError(string.Empty, "Niepoprawne dane logowania.");
                    s.Stop();
                    LoggerController.AddEndMethodLog(this.GetType().Name,
                                                     MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                    return(View(model));
                }
            }

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name, MethodBase.
                                             GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(View(model));
        }
        public async Task <IActionResult> LoginWith2fa(LoginWith2faViewModel model, bool rememberMe, string returnUrl = null)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            if (!ModelState.IsValid)
            {
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(View(model));
            }

            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();

            if (user == null)
            {
                throw new ApplicationException($"Nie udało sie odnaleźć użytkow" +
                                               $"nika o ID '{_userManager.GetUserId(User)}'.");
            }

            var authenticatorCode = model.TwoFactorCode.Replace(" ", string.
                                                                Empty).Replace("-", string.Empty);

            var result = await _signInManager.
                         TwoFactorAuthenticatorSignInAsync(authenticatorCode,
                                                           rememberMe, model.RememberMachine);

            if (result.Succeeded)
            {
                _logger.LogInformation("User with ID {UserId} logged in with 2f" +
                                       "a.", user.Id);
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(RedirectToLocal(returnUrl));
            }
            else if (result.IsLockedOut)
            {
                _logger.LogWarning("User with ID {UserId} account locked out.", user.Id);
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(RedirectToAction(nameof(Lockout)));
            }
            else
            {
                _logger.LogWarning("Invalid authenticator code entered for user" +
                                   " with ID {UserId}.", user.Id);
                ModelState.AddModelError(string.Empty, "Niepoprawne dane logowania.");
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(View());
            }
        }
        public async Task <IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            if (remoteError != null)
            {
                ErrorMessage = $"Error from external provider: {remoteError}";
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(RedirectToAction(nameof(Login)));
            }
            var info = await _signInManager.GetExternalLoginInfoAsync();

            if (info == null)
            {
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(RedirectToAction(nameof(Login)));
            }

            // Sign in the user with this external login provider if the user already has a login.
            var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent : false, bypassTwoFactor : true);

            if (result.Succeeded)
            {
                _logger.LogInformation("User logged in with {Name} provider.", info.LoginProvider);
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(RedirectToLocal(returnUrl));
            }
            if (result.IsLockedOut)
            {
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(RedirectToAction(nameof(Lockout)));
            }
            else
            {
                // If the user does not have an account, then ask the user to create an account.
                ViewData["ReturnUrl"]     = returnUrl;
                ViewData["LoginProvider"] = info.LoginProvider;
                var email = info.Principal.FindFirstValue(ClaimTypes.Email);
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(View("ExternalLogin", new ExternalLoginViewModel {
                    Email = email
                }));
            }
        }
        public async Task <IActionResult> Logout()
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            await _signInManager.SignOutAsync();

            _logger.LogInformation("User logged out.");
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(RedirectToAction(nameof(HomeController.Index), "Home"));
        }
Exemple #20
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            ValidationResult retval  = new ValidationResult("");
            ClientViewModel  rvm     = (ClientViewModel)validationContext.ObjectInstance;
            bool             isEmpty = string.IsNullOrEmpty(rvm.Name);
            bool             isSpace = false;
            int letterts             = 0;

            if (!isEmpty)
            {
                foreach (char c in rvm.Name)
                {
                    if (char.IsWhiteSpace(c))
                    {
                        isSpace = true;
                    }
                    else if (char.IsLetter(c))
                    {
                        letterts++;
                    }
                }
            }

            bool isLastNameEmpty = false;

            if (isSpace)
            {
                string[] tmp = rvm.Name.Split(' ');
                isLastNameEmpty = string.IsNullOrEmpty(tmp[1]);
            }


            if (isEmpty)
            {
                retval.ErrorMessage += "Imie i nazwisko nie może być puste.";
            }
            if ((!isSpace && !isEmpty) || isLastNameEmpty)
            {
                retval.ErrorMessage += "Nie podano nazwiska.";
            }
            if (letterts == 0)
            {
                retval.ErrorMessage += "Podany ciąg znaków nie jest ani imieniem ani nazwiskiem.";
            }

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);

            return(string.IsNullOrEmpty(retval.ErrorMessage) ? ValidationResult.Success : retval);
        }
        public async Task <IActionResult> Login(string returnUrl = null)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();

            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            ViewData["ReturnUrl"] = returnUrl;
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name, MethodBase.
                                             GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(View());
        }
        public IActionResult ExternalLogin(string provider, string returnUrl = null)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            // Request a redirect to the external login provider.
            var redirectUrl = Url.Action(nameof(ExternalLoginCallback), "Account", new { returnUrl });
            var properties  = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(Challenge(properties, provider));
        }
        public async Task <IActionResult> LoginWithRecoveryCode(LoginWithRecoveryCodeViewModel model, string returnUrl = null)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            if (!ModelState.IsValid)
            {
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(View(model));
            }

            var user = await _signInManager.GetTwoFactorAuthenticationUserAsync();

            if (user == null)
            {
                throw new ApplicationException($"Nie udało się odnaleźć użytkownika.");
            }

            var recoveryCode = model.RecoveryCode.Replace(" ", string.Empty);

            var result = await _signInManager.TwoFactorRecoveryCodeSignInAsync(recoveryCode);

            if (result.Succeeded)
            {
                _logger.LogInformation("User with ID {UserId} logged in with a " +
                                       "recovery code.", user.Id);
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(RedirectToLocal(returnUrl));
            }
            if (result.IsLockedOut)
            {
                _logger.LogWarning("User with ID {UserId} account locked out.", user.Id);
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(RedirectToAction(nameof(Lockout)));
            }
            else
            {
                _logger.LogWarning("Invalid recovery code entered for user with" +
                                   " ID {UserId}", user.Id);
                ModelState.AddModelError(string.Empty, "Niepoprawny kod bezpieczeństwa.");
                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(View());
            }
        }
        public async Task <IActionResult> EnableAuthenticator(EnableAuthenticatorViewModel model)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            if (!ModelState.IsValid)
            {
                await LoadSharedKeyAndQrCodeUriAsync(user, model);

                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(View(model));
            }

            // Strip spaces and hypens
            var verificationCode = model.Code.Replace(" ", string.Empty).Replace("-", string.Empty);

            var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync(
                user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode);

            if (!is2faTokenValid)
            {
                ModelState.AddModelError("Code", "Kod weryfikacyjny jest niepoprawny.");
                await LoadSharedKeyAndQrCodeUriAsync(user, model);

                s.Stop();
                LoggerController.AddEndMethodLog(this.GetType().Name,
                                                 MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                return(View(model));
            }

            await _userManager.SetTwoFactorEnabledAsync(user, true);

            _logger.LogInformation("User with ID {UserId} has enabled 2FA with an authenticator app.", user.Id);
            var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10);

            TempData[RecoveryCodesKey] = recoveryCodes.ToArray();

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);

            return(RedirectToAction(nameof(ShowRecoveryCodes)));
        }
Exemple #25
0
        public List <Values> GetAllBrandsByUserData(string name, string phone)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            string[] tmp       = name.Split(' ');
            string   _name     = tmp[0];
            string   _lastName = string.Empty;

            if (tmp.Length > 1)
            {
                _lastName = tmp[1];
            }
            List <Values> retval = new List <Values>();
            List <Device> names  = _context.Device.Include(x => x.Brand).
                                   Include(x => x.Client).Include(x => x.Client.Name).
                                   Include(x => x.Client.LastName).
                                   Where(d => d.Client.Name.Name.Equals(_name) &&
                                         d.Client.LastName.LastName.Equals(_lastName) &&
                                         d.Client.Phone.Equals(phone)).ToList();

            if (names.Count > 0)
            {
                foreach (Device device in names)
                {
                    Values v = new Values()
                    {
                        Value = device.Brand.Brand,
                        ID    = device.BrandId
                    };
                    retval.Add(v);
                }
            }
            else
            {
                names = _context.Device.Include(x => x.Brand).ToList();
                foreach (Device device in names)
                {
                    Values v = new Values()
                    {
                        Value = device.Brand.Brand,
                        ID    = device.BrandId
                    };
                    retval.Add(v);
                }
            }
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(retval);
        }
        public async Task <IActionResult> Register(RegisterViewModel model, string returnUrl = null)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await _userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);
                    await _emailSender.SendEmailConfirmationAsync(model.Email, callbackUrl);

                    await _signInManager.SignInAsync(user, isPersistent : false);

                    _logger.LogInformation("User created a new account with password.");
                    if (returnUrl == null)
                    {
                        IndexViewModel modelIndex = new IndexViewModel();
                        modelIndex.StatusMessage = "Konto zostało utworzone. Sprawdź maila, aby aktywować.";
                        s.Stop();
                        LoggerController.AddEndMethodLog(this.GetType().Name,
                                                         MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                        return(RedirectToAction("Index", "Home", modelIndex));
                    }
                    s.Stop();
                    LoggerController.AddEndMethodLog(this.GetType().Name,
                                                     MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
                    return(RedirectToLocal(returnUrl));
                }
                AddErrors(result);
            }
            else
            {
                return(View(model));
            }

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(View(model));
        }
Exemple #27
0
        public List <Repair> GetAllRepair()
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            List <Repair> repairs = _context.Repair.Include(x => x.Device).
                                    Include(x => x.Device.Brand).Include(x => x.Device.Model).
                                    Include(x => x.Device.Client).
                                    Include(x => x.Device.Client.LastName).
                                    Include(x => x.Device.Client.Name).ToList();

            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(repairs);
        }
Exemple #28
0
        public void AddRepair(AddRepairViewModel data)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            Repair repair = new Repair();

            repair.Acceptance            = data.Repair.DateOfAcceptance;
            repair.CreateTime            = DateTime.Now;
            repair.RepairDetail          = data.Repair.DamageDescription;
            repair.DeviceId              = getDeviceId(data);
            _context.Entry(repair).State = EntityState.Added;
            _context.SaveChanges();
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
        }
Exemple #29
0
        public string GetClientComment(string name, string phone)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            string retval = string.Empty;
            Client client = dh.GetClient(name, phone);

            if (client != null)
            {
                retval = client.Comment;
            }
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(retval);
        }
Exemple #30
0
        public string GetModels(string name, string phone, string brand)
        {
            LoggerController.AddBeginMethodLog(this.GetType().Name, MethodBase.GetCurrentMethod().Name);
            s.Restart();
            string        retval = string.Empty;
            List <Values> brands = dh.GetModels(name, phone, brand);

            if (brands.Count > 0)
            {
                retval = JsonConvert.SerializeObject(brands);
            }
            s.Stop();
            LoggerController.AddEndMethodLog(this.GetType().Name,
                                             MethodBase.GetCurrentMethod().Name, s.ElapsedMilliseconds);
            return(retval);
        }