public IActionResult Index(LoginViewModel model)
        {
            LoginCacheItem loginCacheItem = GetCachedLoginAttempt(true);

            if (!String.IsNullOrEmpty(loginCacheItem.CaptchaText))
            {
                if (!loginCacheItem.CaptchaText.Equals(model.CaptchaText))
                {
                    ModelState.AddModelError(String.Empty, "Invalid Validation Code");
                }
            }

            loginCacheItem.LoginAttempts++;

            model.ShowCaptchaImage = loginCacheItem.LoginAttempts >= _settings.CaptchaShowFailCount;

            UserLoginDetails loginDetails = new UserLoginDetails();

            switch (_loginProvider.Login(model.Username, model.Password, GetIpAddress(),
                                         loginCacheItem.LoginAttempts, ref loginDetails))
            {
            case LoginResult.Success:
                RemoveLoginAttempt();

                UserSession session = GetUserSession();

                if (session != null)
                {
                    session.Login(loginDetails.UserId, loginDetails.Username, loginDetails.Email);
                }

                if (model.RememberMe)
                {
                    CookieAdd(_settings.RememberMeCookieName, Encrypt(loginDetails.UserId.ToString(), _settings.EncryptionKey), _settings.LoginDays);
                }

                return(Redirect(model.ReturnUrl));

            case LoginResult.AccountLocked:
                return(RedirectToAction("AccountLocked", new { username = model.Username }));

            case LoginResult.PasswordChangeRequired:
                return(Redirect(_settings.ChangePasswordUrl));

            case LoginResult.InvalidCredentials:
                ModelState.AddModelError(String.Empty, "Invalid username or password");
                break;
            }

            if (model.ShowCaptchaImage)
            {
                loginCacheItem.CaptchaText = GetRandomWord(_settings.CaptchaWordLength, CaptchaCharacters);
            }

            return(View(model));
        }
        private async Task <bool> LoginUsingBasicAuth(UserSession userSession, HttpContext context,
                                                      IAuthenticationService authenticationService)
        {
            using (StopWatchTimer stopWatchTimer = StopWatchTimer.Initialise(_autoLoginBasicAuthLogin))
            {
                string authData = context.Request.Headers[SharedPluginFeatures.Constants.HeaderAuthorizationName];

                if (!authData.StartsWith("Basic ", StringComparison.InvariantCultureIgnoreCase))
                {
                    context.Response.StatusCode = 400;
                    return(false);
                }

                try
                {
                    authData = System.Text.Encoding.GetEncoding("ISO-8859-1").GetString(Convert.FromBase64String(authData.Substring(6)));
                }
                catch (FormatException)
                {
                    context.Response.StatusCode = 400;
                    return(false);
                }

                string[] authParts = authData.Split(':', StringSplitOptions.RemoveEmptyEntries);

                if (authParts.Length != 2)
                {
                    context.Response.StatusCode = 400;
                    return(false);
                }

                UserLoginDetails loginDetails = new UserLoginDetails();

                LoginResult loginResult = _loginProvider.Login(authParts[0], authParts[1],
                                                               GetIpAddress(context), 1, ref loginDetails);

                if (loginResult == LoginResult.Success)
                {
                    userSession.Login(loginDetails.UserId, loginDetails.Username, loginDetails.Email);
                    await authenticationService.SignInAsync(context,
                                                            _loginControllerSettings.AuthenticationScheme,
                                                            new ClaimsPrincipal(_claimsProvider.GetUserClaims(loginDetails.UserId)),
                                                            _claimsProvider.GetAuthenticationProperties());

                    return(true);
                }
                else
                {
                    context.Response.StatusCode = 401;
                    return(false);
                }
            }
        }
Пример #3
0
        public async Task <ActionResult> Login(User user)
        {
            _log4net.Info("User Login Initiated of name " + user.Username);

            try
            {
                var response1 = await _loginProvider.Login(user);

                if (!response1.IsSuccessStatusCode)
                {
                    ViewBag.message = "Invalid Login Credentials";
                    _log4net.Info("Invalid user details are given with name" + user.Username);
                    return(View(user));
                }

                string stringJWT = await response1.Content.ReadAsStringAsync();

                var jwt = JsonConvert.DeserializeObject <JWT>(stringJWT);

                _log4net.Info(user.Username + " successfully logged in");
                HttpContext.Session.SetString("token", jwt.Token);
                HttpContext.Session.SetString("user", JsonConvert.SerializeObject(user));
                HttpContext.Session.SetString("Username", user.Username);

                return(RedirectToAction("Index", "AuditCheckList"));
            }
            catch (Exception e)
            {
                _log4net.Error("Unexpected error occured in Login Controller with message -" + e.Message);
                return(View(user));
            }
        }
Пример #4
0
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (loginProvider.Login(model.UserName, model.Password))
                {
                    return(RedirectToUrl(returnUrl));
                }

                ModelState.AddModelError("", "Podana nazwa użytkownika lub hasło są nieprawidłowe.");
            }
            return(View());
        }
Пример #5
0
        public async Task Invoke(HttpContext context)
        {
            using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_loginTimings))
            {
                UserSession userSession = GetUserSession(context);

                if (userSession != null && String.IsNullOrEmpty(userSession.UserName) &&
                    CookieExists(context, _loginControllerSettings.RememberMeCookieName))
                {
                    using (StopWatchTimer stopwatchAutoLogin = StopWatchTimer.Initialise(_autoLoginTimings))
                    {
                        string cookieValue = CookieValue(context, _loginControllerSettings.RememberMeCookieName,
                                                         _loginControllerSettings.EncryptionKey, String.Empty);

                        if (Int64.TryParse(cookieValue, out long userId))
                        {
                            UserLoginDetails loginDetails = new UserLoginDetails(userId, true);

                            LoginResult loginResult = _loginProvider.Login(String.Empty, String.Empty,
                                                                           base.GetIpAddress(context), 1, ref loginDetails);

                            if (loginResult == LoginResult.Remembered)
                            {
                                userSession.Login(userId, loginDetails.Username, loginDetails.Email);
                                await _authenticationService.SignInAsync(context,
                                                                         _loginControllerSettings.AuthenticationScheme,
                                                                         new ClaimsPrincipal(_claimsProvider.GetUserClaims(loginDetails.UserId)),
                                                                         _claimsProvider.GetAuthenticationProperties());
                            }
                            else
                            {
                                CookieDelete(context, _loginControllerSettings.RememberMeCookieName);
                            }
                        }
                        else
                        {
                            CookieDelete(context, _loginControllerSettings.RememberMeCookieName);
                        }
                    }
                }
            }

            await _next(context);
        }
Пример #6
0
 public Task <bool> Login(string loginName, string password, bool persist = false)
 {
     return(_taskFactory.StartNew(() =>
     {
         try
         {
             _loginProvider.Login(loginName, password);
             UserContext.Current = new LocalUser
             {
                 Name = loginName,
                 LoginName = loginName
             };
             return true;
         }
         catch (Exception exception)
         {
             throw exception;
         }
     }));
 }
Пример #7
0
        public static User TryLogin(string username, string password)
        {
            LDAPResult result = loginProvider.Login(username, password);

            if (!result.Result)
            {
                return(null);
            }
            else
            {
                using (DatabaseContext db = new DatabaseContext())
                {
                    User user = db.Users.Where(u => u.UID == result.UID).FirstOrDefault();
                    if (user != null)
                    {
                        user.Name     = result.CN;
                        user.Category = GetCategoryByUID(result.DC);
                        user.Division = GetBranchAffiliateByUID(result.OU);
                    }
                    else
                    {
                        user = new User()
                        {
                            UID      = result.UID,
                            Name     = result.CN,
                            Roles    = { GetRoleByUID(DEFAULT_ROLE) },
                            Category = GetCategoryByUID(result.DC),
                            Division = GetBranchAffiliateByUID(result.OU)
                        };

                        db.Users.Add(user);
                    }

                    db.SaveChanges();
                    return(user);
                }
            }
        }
        public IActionResult Index(LoginViewModel model)
        {
            if (model == null)
            {
                throw new ArgumentNullException(nameof(model));
            }

            LoginCacheItem loginCacheItem = GetCachedLoginAttempt(true);

            if (!String.IsNullOrEmpty(loginCacheItem.CaptchaText))
            {
                if (!loginCacheItem.CaptchaText.Equals(model.CaptchaText))
                {
                    ModelState.AddModelError(String.Empty, Languages.LanguageStrings.CodeNotValid);
                }
            }

            loginCacheItem.LoginAttempts++;

            model.ShowCaptchaImage = loginCacheItem.LoginAttempts >= _settings.CaptchaShowFailCount;

            UserLoginDetails loginDetails = new UserLoginDetails();

            model.Breadcrumbs = GetBreadcrumbs();
            model.CartSummary = GetCartSummary();

            LoginResult loginResult = _loginProvider.Login(model.Username, model.Password, GetIpAddress(),
                                                           loginCacheItem.LoginAttempts, ref loginDetails);

            switch (loginResult)
            {
            case LoginResult.Success:
            case LoginResult.PasswordChangeRequired:
                RemoveLoginAttempt();

                UserSession session = GetUserSession();

                if (session != null)
                {
                    session.Login(loginDetails.UserId, loginDetails.Username, loginDetails.Email);
                }

                if (model.RememberMe)
                {
                    CookieAdd(_settings.RememberMeCookieName, Encrypt(loginDetails.UserId.ToString(),
                                                                      _settings.EncryptionKey), _settings.LoginDays);
                }


                GetAuthenticationService().SignInAsync(HttpContext,
                                                       _settings.AuthenticationScheme,
                                                       new ClaimsPrincipal(_claimsProvider.GetUserClaims(loginDetails.UserId)),
                                                       _claimsProvider.GetAuthenticationProperties());

                if (loginResult == LoginResult.PasswordChangeRequired)
                {
                    return(Redirect(_settings.ChangePasswordUrl));
                }

                return(Redirect(model.ReturnUrl));

            case LoginResult.AccountLocked:
                return(RedirectToAction(nameof(AccountLocked), new { username = model.Username }));

            case LoginResult.InvalidCredentials:
                ModelState.AddModelError(String.Empty, Languages.LanguageStrings.InvalidUsernameOrPassword);
                break;
            }

            if (model.ShowCaptchaImage)
            {
                loginCacheItem.CaptchaText = GetRandomWord(_settings.CaptchaWordLength, CaptchaCharacters);
            }

            return(View(model));
        }
Пример #9
0
 private async Task LoginInternal(string username, string password) => await ServiceRunner.RunAsync(() =>
 {
     _loginProvider.Login(username, password);
     UserContext.Current = new User(username);
 });
Пример #10
0
        private async Task LoginInternal(string username, string password)
        {
            await _loginProvider.Login(username, password);

            UserContext.Current = new User(username);
        }