Beispiel #1
0
        public async Task <IActionResult> Logout(LogoutInputModel model)
        {
            var vm = await _account.BuildLoggedOutViewModelAsync(model.LogoutId);

            if (vm.TriggerExternalSignout)
            {
                string url = Url.Action("Logout", new { logoutId = vm.LogoutId });
                try
                {
                    // hack: try/catch to handle social providers that throw
                    await HttpContext.Authentication.SignOutAsync(vm.ExternalAuthenticationScheme, new Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties {
                        RedirectUri = url
                    });
                }
                catch (NotSupportedException) // this is for the external providers that don't have signout
                {
                }
                catch (InvalidOperationException) // this is for Windows/Negotiate
                {
                }
            }

            var userName = HttpContext.User.Identity.Name;
            // Insert access log
            var accessLog = new ESEIM.Models.AdAccessLog();

            //accessLog.UserId = userName;
            //accessLog.Action = "Logout";
            //accessLog.AccessDate = DateTime.Now;
            //accessLog.IpAddress = HttpContext.Connection?.RemoteIpAddress?.ToString();
            //accessLog.Description = $"{userName} logout";
            //accessLog.AccessLogApplication = "Admin";
            //_context.AdAccessLogs.Add(accessLog);
            //await _context.SaveChangesAsync();
            foreach (var cookie in Request.Cookies.Keys)
            {
                HttpContext.Response.Cookies.Delete(cookie);
            }
            // delete local authentication cookie
            await HttpContext.Authentication.SignOutAsync();

            return(View("LoggedOut", vm));
        }
Beispiel #2
0
        public async Task <IActionResult> Login(LoginViewModel model, string returnUrl = null)
        {
            ViewData["ReturnUrl"] = returnUrl;
            if (ModelState.IsValid)
            {
                //model.ListCompany = _context.E_Companys.OrderBy(o => o.Id).Select(x => new SelectListItem
                //{
                //    Value = x.Company_Code,
                //    Text = x.Company_Name,
                //}).ToList();

                try
                {
                    var user = await _userManager.FindByNameAsync(model.Username);

                    if (user == null)
                    {
                        ModelState.AddModelError(string.Empty, "Username or Password incorrect.");
                    }
                    else if (user.Active == false)
                    {
                        ModelState.AddModelError(string.Empty, "Username is not active. Please contact to admin.");
                    }
                    else
                    {
                        var authenProps = new Microsoft.AspNetCore.Authentication.AuthenticationProperties
                        {
                            IsPersistent = model.RememberLogin,
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration)
                                           //ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(model.RememberLogin ? (15 * 24 * 60) : _parameterService.GetSessionTimeoutAdmin()),
                        };

                        if (model.AuthenProvider)
                        {
                            int            ldapPort    = _appSettings.ADConfigs.Port;
                            int            ldapVersion = LdapConnection.Ldap_V3;
                            string         ldapHost    = _appSettings.ADConfigs.Host;
                            string         loginDN     = _appSettings.ADConfigs.LoginDN;
                            string         password    = _appSettings.ADConfigs.Password;
                            string         objectDN    = _appSettings.ADConfigs.ObjectDN;
                            LdapConnection conn        = new LdapConnection();
                            try
                            {
                                conn.Connect(ldapHost, ldapPort);
                                conn.Bind(ldapVersion, loginDN, password);
                                var    entities = conn.Search(objectDN, LdapConnection.SCOPE_SUB, $"(sAMAccountName={model.Username})", new string[] { "sAMAccountName", "mail", "name", "givenName", "sn", "userAccountControl", "objectGUID" }, false);
                                string userDn = null, userAc = null;
                                while (entities.hasMore())
                                {
                                    var entity  = entities.next();
                                    var account = entity.getAttribute("sAMAccountName");
                                    //var email = entity.getAttribute("mail");
                                    //var name = entity.getAttribute("name");
                                    //var givenName = entity.getAttribute("givenName");
                                    //var familyName = entity.getAttribute("sn");
                                    var userAccountControl = entity.getAttribute("userAccountControl");
                                    if (account != null && account.StringValue.ToLower() == model.Username.ToLower())
                                    {
                                        userAc = userAccountControl.StringValue;
                                        userDn = entity.DN;
                                        break;
                                    }
                                }
                                if (string.IsNullOrWhiteSpace(userDn))
                                {
                                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                                    return(View(await _account.BuildLoginViewModelAsync(model)));
                                }
                                if (!string.IsNullOrEmpty(userAc) && userAc.Equals("514"))
                                {
                                    ModelState.AddModelError(string.Empty, "Username was disabled in AD. Please contact to AD admin.");
                                    return(View(await _account.BuildLoginViewModelAsync(model)));
                                }

                                conn.Bind(userDn, model.Password);
                                conn.Disconnect();

                                try
                                {
                                    await _signInManager.SignInAsync(user, authenProps);

                                    _logger.LogInformation(1, "User logged in.");
                                    // Insert access log
                                    var accessLog = new ESEIM.Models.AdAccessLog();
                                    accessLog.UserId      = model.Username;
                                    accessLog.Action      = "Login";
                                    accessLog.AccessDate  = DateTime.Now;
                                    accessLog.IpAddress   = HttpContext.Connection?.RemoteIpAddress?.ToString();
                                    accessLog.Description = $"{model.Username} login to system";
                                    //accessLog.Code = returnUrl;
                                    //accessLog.Application = Request.Headers["User-Agent"].ToString();
                                    accessLog.AccessLogApplication = "Admin";
                                    _context.AdAccessLogs.Add(accessLog);
                                    await _context.SaveChangesAsync();

                                    return(RedirectToLocal(returnUrl));
                                }
                                catch (Exception ex)
                                {
                                    ModelState.AddModelError(string.Empty, "Username or password incorrect.");
                                    return(View(await _account.BuildLoginViewModelAsync(model)));
                                }
                            }
                            catch (LdapException e)
                            {
                                //if (e.ResultCode == LdapException.NO_SUCH_OBJECT)
                                //{
                                //    ModelState.AddModelError(string.Empty, "No such entry");
                                //    return View(await _account.BuildLoginViewModelAsync(model));
                                //}
                                //else if (e.ResultCode == LdapException.NO_SUCH_ATTRIBUTE)
                                //{
                                //    ModelState.AddModelError(string.Empty, "No such attribute");
                                //    return View(await _account.BuildLoginViewModelAsync(model));
                                //}
                                //else
                                if (e.ResultCode == LdapException.INVALID_CREDENTIALS)
                                {
                                    ModelState.AddModelError(string.Empty, "Username or password incorrect.");
                                    return(View(await _account.BuildLoginViewModelAsync(model)));
                                }
                                else
                                {
                                    ModelState.AddModelError(string.Empty, "Login to AD failed.");
                                    return(View(await _account.BuildLoginViewModelAsync(model)));
                                }
                            }
                        }
                        else
                        {
                            var verify = await _signInManager.CheckPasswordSignInAsync(user, model.Password, false);

                            //var result = await _signInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberLogin, lockoutOnFailure: false);
                            if (verify.Succeeded)
                            {
                                await _signInManager.SignInAsync(user, authenProps);

                                //_logger.LogInformation(1, "User logged in.");
                                // Insert access log
                                //var accessLog = new ESEIM.Models.AdAccessLog();
                                //accessLog.UserId = model.Username;
                                //accessLog.Action = "Login";
                                //accessLog.AccessDate = DateTime.Now;
                                //accessLog.IpAddress = HttpContext.Connection?.RemoteIpAddress?.ToString();
                                //accessLog.Description = $"{model.Username} login to system";
                                ////accessLog.Resource = returnUrl;
                                ////accessLog.Application = Request.Headers["User-Agent"].ToString();
                                //accessLog.AccessLogApplication = "Admin";
                                //_context.AdAccessLogs.Add(accessLog);
                                //await _context.SaveChangesAsync();

                                return(RedirectToLocal(returnUrl));
                            }
                            if (verify.RequiresTwoFactor)
                            {
                                return(RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberLogin }));
                            }
                            if (verify.IsLockedOut)
                            {
                                _logger.LogWarning(2, "User account locked out.");
                                return(View("Lockout"));
                            }
                            else
                            {
                                ModelState.AddModelError(string.Empty, "Username or password incorrect.");
                                return(View(await _account.BuildLoginViewModelAsync(model)));
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    _logger.LogError(3, e.Message);
                    ModelState.AddModelError(string.Empty, "An error occurred while login.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(await _account.BuildLoginViewModelAsync(model)));
        }