public static string AuthenticateMeAndSetCookies(int tenantId, Guid userId, MessageAction action, bool session = false)
        {
            bool       isSuccess      = true;
            var        cookies        = string.Empty;
            Func <int> funcLoginEvent = () => { return(GetLoginEventId(action)); };

            try
            {
                cookies = SecurityContext.AuthenticateMe(userId, funcLoginEvent);
            }
            catch (Exception)
            {
                isSuccess = false;
                throw;
            }
            finally
            {
                if (isSuccess)
                {
                    SetCookies(CookiesType.AuthKey, cookies, session);
                    DbLoginEventsManager.ResetCache(tenantId, userId);
                }
            }

            return(cookies);
        }
Beispiel #2
0
        private static void OutsideAuth()
        {
            var        action         = MessageAction.LoginSuccess;
            Func <int> funcLoginEvent = () => { return(CookiesManager.GetLoginEventId(action)); };
            var        cookie         = string.Empty;

            try
            {
                cookie = SecurityContext.AuthenticateMe(Constants.OutsideUser.ID, funcLoginEvent);
            }
            catch (Exception)
            {
                throw;
            }

            if (HttpContext.Current != null)
            {
                CookiesManager.SetCookies(CookiesType.AuthKey, cookie);
                DbLoginEventsManager.ResetCache();
            }
            else
            {
                SecurityContext.AuthenticateMe(cookie);
            }
        }
        public static void SetLifeTime(int lifeTime)
        {
            if (!CoreContext.UserManager.IsUserInGroup(SecurityContext.CurrentAccount.ID, Constants.GroupAdmin.ID))
            {
                throw new SecurityException();
            }

            var tenant   = TenantProvider.CurrentTenantID;
            var settings = TenantCookieSettings.GetForTenant(tenant);

            if (lifeTime > 0)
            {
                settings.Index    = settings.Index + 1;
                settings.LifeTime = lifeTime;
            }
            else
            {
                settings.LifeTime = 0;
            }

            TenantCookieSettings.SetForTenant(tenant, settings);

            if (lifeTime > 0)
            {
                DbLoginEventsManager.LogOutAllActiveConnectionsForTenant(tenant);
            }

            var userId = SecurityContext.CurrentAccount.ID;

            AuthenticateMeAndSetCookies(tenant, userId, MessageAction.LoginSuccess);
        }
Beispiel #4
0
        public object GetAllActiveConnections()
        {
            var user            = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
            var loginEvents     = DbLoginEventsManager.GetLoginEvents(user.Tenant, user.ID);
            var listLoginEvents = loginEvents.ConvertAll(Convert);
            var loginEventId    = GetLoginEventIdFromCookie();

            if (loginEventId != 0)
            {
                var loginEvent = listLoginEvents.FirstOrDefault(x => x.Id == loginEventId);
                if (loginEvent != null)
                {
                    listLoginEvents.Remove(loginEvent);
                    listLoginEvents.Insert(0, loginEvent);
                }
            }
            else
            {
                if (listLoginEvents.Count == 0)
                {
                    var request           = HttpContext.Current.Request;
                    var uaHeader          = MessageSettings.GetUAHeader(request);
                    var clientInfo        = MessageSettings.GetClientInfo(uaHeader);
                    var platformAndDevice = MessageSettings.GetPlatformAndDevice(clientInfo);
                    var browser           = MessageSettings.GetBrowser(clientInfo);
                    var ip = MessageSettings.GetIP(request);

                    var baseEvent = new CustomEvent
                    {
                        Id       = 0,
                        Platform = platformAndDevice,
                        Browser  = browser,
                        Date     = DateTime.Now,
                        IP       = ip
                    };

                    listLoginEvents.Add(Convert(baseEvent));
                }
            }

            var result = new
            {
                Items      = listLoginEvents,
                LoginEvent = loginEventId
            };

            return(result);
        }
        public static void ResetUserCookie(Guid?userId = null)
        {
            var currentUserId = SecurityContext.CurrentAccount.ID;
            var tenant        = TenantProvider.CurrentTenantID;
            var settings      = TenantCookieSettings.GetForUser(userId ?? currentUserId);

            settings.Index = settings.Index + 1;
            TenantCookieSettings.SetForUser(userId ?? currentUserId, settings);

            DbLoginEventsManager.LogOutAllActiveConnections(tenant, userId ?? currentUserId);

            if (!userId.HasValue)
            {
                AuthenticateMeAndSetCookies(tenant, currentUserId, MessageAction.LoginSuccess);
            }
        }
Beispiel #6
0
        public bool LogOutActiveConnection(int loginEventId)
        {
            try
            {
                var user     = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
                var userName = user.DisplayUserName(false);

                DbLoginEventsManager.LogOutEvent(loginEventId);

                MessageService.Send(Request, MessageAction.UserLogoutActiveConnection, userName);
                return(true);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return(false);
            }
        }
Beispiel #7
0
        public string LogOutAllExceptThisConnection()
        {
            try
            {
                var user                 = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
                var userName             = user.DisplayUserName(false);
                var loginEventFromCookie = GetLoginEventIdFromCookie();

                DbLoginEventsManager.LogOutAllActiveConnectionsExceptThis(loginEventFromCookie, user.Tenant, user.ID);

                MessageService.Send(Request, MessageAction.UserLogoutActiveConnections, userName);
                return(userName);
            }
            catch (Exception ex)
            {
                Log.Error(ex);
                return(null);
            }
        }
        public static void ResetTenantCookie()
        {
            var userId = SecurityContext.CurrentAccount.ID;

            if (!CoreContext.UserManager.IsUserInGroup(userId, Constants.GroupAdmin.ID))
            {
                throw new SecurityException();
            }

            var tenant   = TenantProvider.CurrentTenantID;
            var settings = TenantCookieSettings.GetForTenant(tenant);

            settings.Index = settings.Index + 1;
            TenantCookieSettings.SetForTenant(tenant, settings);

            DbLoginEventsManager.LogOutAllActiveConnectionsForTenant(tenant);

            AuthenticateMeAndSetCookies(tenant, userId, MessageAction.LoginSuccess);
        }
        public static void AuthenticateMeAndSetCookies(string login, string passwordHash, MessageAction action, bool session = false)
        {
            bool       isSuccess      = true;
            var        cookies        = string.Empty;
            Func <int> funcLoginEvent = () => { return(GetLoginEventId(action)); };

            try
            {
                cookies = SecurityContext.AuthenticateMe(login, passwordHash, funcLoginEvent);
            }
            catch (Exception)
            {
                isSuccess = false;
                throw;
            }
            finally
            {
                if (isSuccess)
                {
                    SetCookies(CookiesType.AuthKey, cookies, session);
                    DbLoginEventsManager.ResetCache();
                }
            }
        }
Beispiel #10
0
        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);

            if (!SecurityContext.IsAuthenticated)
            {
                if (CoreContext.Configuration.Personal)
                {
                    CheckSocialMedia();

                    SetLanguage();
                }

                var token = Request["asc_auth_key"];
                if (SecurityContext.AuthenticateMe(token))
                {
                    CookiesManager.SetCookies(CookiesType.AuthKey, token);

                    var refererURL = Request["refererURL"];
                    if (string.IsNullOrEmpty(refererURL))
                    {
                        refererURL = "~/Auth.aspx";
                    }

                    Response.Redirect(refererURL, true);
                }

                return;
            }

            if (IsLogout)
            {
                var cookie       = CookiesManager.GetCookies(CookiesType.AuthKey);
                int loginEventId = CookieStorage.GetLoginEventIdFromCookie(cookie);
                DbLoginEventsManager.LogOutEvent(loginEventId);

                var user      = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
                var loginName = user.DisplayUserName(false);
                MessageService.Send(HttpContext.Current.Request, loginName, MessageAction.Logout);

                ProcessLogout();

                if (!string.IsNullOrEmpty(user.SsoNameId))
                {
                    var settings = SsoSettingsV2.Load();

                    if (settings.EnableSso && !string.IsNullOrEmpty(settings.IdpSettings.SloUrl))
                    {
                        var logoutSsoUserData = Signature.Create(new LogoutSsoUserData
                        {
                            NameId    = user.SsoNameId,
                            SessionId = user.SsoSessionId
                        });

                        HttpContext.Current.Response.Redirect(SetupInfo.SsoSamlLogoutUrl + "?data=" + HttpUtility.UrlEncode(logoutSsoUserData), true);
                    }
                }

                Response.Redirect("~/Auth.aspx", true);
            }
            else
            {
                Response.Redirect(CommonLinkUtility.GetDefault(), true);
            }
        }
        public static bool AuthenticateMe(string cookie)
        {
            if (!string.IsNullOrEmpty(cookie))
            {
                int      tenant;
                Guid     userid;
                int      indexTenant;
                DateTime expire;
                int      indexUser;
                int      loginEventId;

                if (cookie.Equals("Bearer", StringComparison.InvariantCulture))
                {
                    var ipFrom  = string.Empty;
                    var address = string.Empty;
                    if (HttpContext.Current != null)
                    {
                        var request = HttpContext.Current.Request;
                        ipFrom  = "from " + (request.Headers["X-Forwarded-For"] ?? request.UserHostAddress);
                        address = "for " + request.GetUrlRewriter();
                    }
                    log.InfoFormat("Empty Bearer cookie: {0} {1}", ipFrom, address);
                }
                else if (CookieStorage.DecryptCookie(cookie, out tenant, out userid, out indexTenant, out expire, out indexUser, out loginEventId))
                {
                    if (tenant != CoreContext.TenantManager.GetCurrentTenant().TenantId)
                    {
                        return(false);
                    }

                    var settingsTenant = TenantCookieSettings.GetForTenant(tenant);
                    if (indexTenant != settingsTenant.Index)
                    {
                        return(false);
                    }

                    if (expire != DateTime.MaxValue && expire < DateTime.UtcNow)
                    {
                        return(false);
                    }

                    try
                    {
                        var settingsUser = TenantCookieSettings.GetForUser(userid);
                        if (indexUser != settingsUser.Index)
                        {
                            return(false);
                        }

                        var settingLoginEvents = DbLoginEventsManager.GetLoginEventIds(tenant, userid);
                        if (loginEventId != 0 && !settingLoginEvents.Contains(loginEventId))
                        {
                            return(false);
                        }

                        CurrentAccount = new UserAccount(new UserInfo {
                            ID = userid
                        }, tenant);
                        return(true);
                    }
                    catch (InvalidCredentialException ice)
                    {
                        log.DebugFormat("{0}: cookie {1}, tenant {2}, userid {3}",
                                        ice.Message, cookie, tenant, userid);
                    }
                    catch (SecurityException se)
                    {
                        log.DebugFormat("{0}: cookie {1}, tenant {2}, userid {3}",
                                        se.Message, cookie, tenant, userid);
                    }
                    catch (Exception err)
                    {
                        log.ErrorFormat("Authenticate error: cookie {0}, tenant {1}, userid {2}: {3}",
                                        cookie, tenant, userid, err);
                    }
                }
                else
                {
                    var ipFrom  = string.Empty;
                    var address = string.Empty;
                    if (HttpContext.Current != null)
                    {
                        var request = HttpContext.Current.Request;
                        address = "for " + request.GetUrlRewriter();
                        ipFrom  = "from " + (request.Headers["X-Forwarded-For"] ?? request.UserHostAddress);
                    }
                    log.WarnFormat("Can not decrypt cookie: {0} {1} {2}", cookie, ipFrom, address);
                }
            }
            return(false);
        }