Esempio n. 1
0
        public Task <SessionInfo> LoginAsync(UserLoginModel model)
        {
            var id   = SessionCookie.GetSessionId(Context);
            var auth = authManager.Authenticate(model.Username, model.Password);
            var user = gameData.GetUser(auth.UserId);

            if (user != null && user.Status >= 1)
            {
                return(Task.FromResult(new SessionInfo()
                {
                    Authenticated = false
                }));
            }

            return(sessionInfoProvider.SetAuthTokenAsync(id, auth));
        }
Esempio n. 2
0
 public AuthorizeRequestValidator(
     IdentityServerOptions options,
     IClientStore clients,
     ICustomRequestValidator customValidator,
     IRedirectUriValidator uriValidator,
     ScopeValidator scopeValidator,
     SessionCookie sessionCookie,
     ILogger <AuthorizeRequestValidator> logger)
 {
     _options         = options;
     _clients         = clients;
     _customValidator = customValidator;
     _uriValidator    = uriValidator;
     _scopeValidator  = scopeValidator;
     _sessionCookie   = sessionCookie;
     _logger          = logger;
 }
 public EndSessionEndpoint(
     ILogger <EndSessionEndpoint> logger,
     IdentityServerContext context,
     IEndSessionRequestValidator endSessionRequestValidator,
     IMessageStore <LogoutMessage> logoutMessageStore,
     SessionCookie sessionCookie,
     ClientListCookie clientListCookie,
     IClientStore clientStore)
 {
     _logger  = logger;
     _context = context;
     _endSessionRequestValidator = endSessionRequestValidator;
     _logoutMessageStore         = logoutMessageStore;
     _sessionCookie    = sessionCookie;
     _clientListCookie = clientListCookie;
     _clientStore      = clientStore;
 }
Esempio n. 4
0
        public override void OnPageHandlerSelected(PageHandlerSelectedContext filterContext)
        {
            ApplicationUser appUser       = _userManager.GetUserAsync(HttpContext.User).Result;
            SessionCookie   sessionCookie = _sessionCookieService.RetrieveSessionCookie(appUser.UserName);

            if (sessionCookie == null)
            {
                StringBuilder sb = new StringBuilder("[Enrollments][IndexModel][OnPageHandlerSelected] => SessionCookie for '");
                sb.Append(appUser.UserName);
                sb.Append("' NOT FOUND. Redirecting to Login page.");
                _logger.LogInformation(sb.ToString());

                filterContext.HttpContext.Response.Redirect("/Account/LoginPrep");

                return;
            }

            if (DateTime.Now > sessionCookie.LastAccessedOn.AddMinutes(30))
            {
                StringBuilder sb = new StringBuilder("[Enrollments][IndexModel][OnPageHandlerSelected] => SessionCookie for '");
                sb.Append(appUser.UserName);
                sb.Append("' HAS EXPIRED. It was last accessed on ");
                sb.Append(sessionCookie.LastAccessedOn);

                if (DateTime.Now > sessionCookie.LastAccessedOn.AddHours(2))
                {
                    sb.Append(". Redirecting to Login page.");
                    _logger.LogInformation(sb.ToString());
                    filterContext.HttpContext.Response.Redirect("/Account/LoginPrep");

                    return;
                }
                else
                {
                    sb.Append(". Redirecting to SessionTimeout page.");
                    _logger.LogInformation(sb.ToString());
                    filterContext.HttpContext.Response.Redirect("/Account/SessionTimeout");

                    return;
                }
            }

            _logger.LogInformation("[Enrollments][IndexModel][OnPageHandlerSelected] => Refreshing SessinCookie for '" + appUser.UserName + "'");
            _sessionCookieService.RefreshSessionCookie(appUser.UserName);
        }
Esempio n. 5
0
        public static void ProcessAgentResponse(SessionHostHeartbeatInfo heartBeat)
        {
            if (heartBeat.sessionConfig != null && !string.IsNullOrEmpty(heartBeat.sessionConfig.SessionCookie))
            {
                cookie = _jsonWrapper.DeserializeObject <SessionCookie>(heartBeat.sessionConfig.SessionCookie);
            }

            if (heartBeat.nextScheduledMaintenanceUtc != null)
            {
                if (OnMaintenance != null)
                {
                    OnMaintenance.Invoke(heartBeat.nextScheduledMaintenanceUtc);
                }
            }

            switch (heartBeat.operation)
            {
            case Operation.Continue:
                //No Action Required.
                break;

            case Operation.Active:
                //Transition Server State to Active.
                CurrentState.currentGameState = SessionHostStatus.Active;
                break;

            case Operation.Terminate:
                //Transition Server to a Termination state.
                CurrentState.currentGameState = SessionHostStatus.Terminating;
                if (OnShutDown != null)
                {
                    OnShutDown.Invoke();
                }
                break;

            default:
                Debug.LogWarning("Unknown operation received" + heartBeat.operation);
                break;
            }

            if (IsDebugging)
            {
                Debug.LogFormat("Operation: {0}, Maintenance:{1}, State: {2}", heartBeat.operation, heartBeat.nextScheduledMaintenanceUtc.ToString(), heartBeat.currentGameState);
            }
        }
Esempio n. 6
0
        public async Task OpenURL(string url, MethodEnum method = MethodEnum.GET, bool includeSessionCookie = false)
        {
            AM = DependencyService.Resolve <AppModel>();
            var client = new RestClient();

            if (includeSessionCookie)
            {
                var cookieJar = new CookieContainer();
                cookieJar.Add(new Uri(Constants.BASE_URI), new Cookie(AM.UserSessionCookie.Name, AM.UserSessionCookie.Value));
                client.CookieContainer = cookieJar;
            }

            var request = new RestRequest(url, (Method)method)
            {
                RequestFormat = DataFormat.Json
            };
            var cancellationTokenSource = new CancellationTokenSource();
            var response = await client.ExecuteTaskAsync(request, cancellationTokenSource.Token);

            if (response.Cookies.Count > 0)
            {
                foreach (var cookie in response.Cookies)
                {
                    if (cookie.Name == "_whitepaperbible_session")
                    {
                        UserSessionCookie = new SessionCookie
                        {
                            Name  = cookie.Name,
                            Value = cookie.Value
                        };
                    }
                }
            }

            ResponseText = response.Content;
            //			RemoveNetworkActivity (url);
            if (response.ResponseStatus == ResponseStatus.Error)
            {
                DispatchError();
            }
            else
            {
                DispatchComplete();
            }
        }
Esempio n. 7
0
        public async Task <bool> UpdateSessionAsync(LoginUpParty loginUpParty, SessionCookie session)
        {
            logger.ScopeTrace($"Update session, Route '{RouteBinding.Route}'.");

            var sessionEnabled = SessionEnabled(loginUpParty);
            var sessionValid   = SessionValid(loginUpParty, session);

            if (sessionEnabled && sessionValid)
            {
                session.LastUpdated = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
                await sessionCookieRepository.SaveAsync(session, GetPersistentCookieExpires(loginUpParty, session.CreateTime));

                logger.ScopeTrace($"Session updated, Session id '{session.SessionId}'.", new Dictionary <string, string> {
                    { "sessionId", session.SessionId }
                });
                return(true);
            }

            return(false);
        }
Esempio n. 8
0
 public void GetCountersFromPrinter(Uri printerCounterUri)
 {
     try
     {
         Task.Delay(1000);
         HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(printerCounterUri);
         myRequest.Method = "GET";
         myRequest.Headers.Add(HttpRequestHeader.Cookie, SessionCookie.ToString());
         WebResponse  myResponse = myRequest.GetResponse();
         StreamReader sr         = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
         // this.PrinterResponse = sr.ReadToEnd();
         this.PrinterResponseParser.PrinterResponse = sr.ReadToEnd();
         sr.Close();
         myResponse.Close();
     }
     catch (Exception e)
     {
         Console.WriteLine("Couldn't get response from printer " + printerCounterUri);
     }
 }
        public string DeterminePageRedirect(string userName, string tagName)
        {
            SessionCookie sessionCookie = this.RetrieveSessionCookie(userName);

            if (sessionCookie == null)
            {
                StringBuilder sb = new StringBuilder(tagName);
                sb.Append(" => SessionCookie for '");
                sb.Append(userName);
                sb.Append("' NOT FOUND. Redirecting to LoginPrep page.");
                _logger.LogInformation(sb.ToString());

                return("/Account/LoginPrep");
            }

            if (DateTime.Now > sessionCookie.LastAccessedOn.AddMinutes(30))
            {
                StringBuilder sb = new StringBuilder(tagName);
                sb.Append(" => SessionCookie for '");
                sb.Append(userName);
                sb.Append("' HAS EXPIRED. It was last accessed on ");
                sb.Append(sessionCookie.LastAccessedOn);

                if (DateTime.Now > sessionCookie.LastAccessedOn.AddHours(2))
                {
                    sb.Append(". Redirecting to LoginPrep page.");
                    _logger.LogInformation(sb.ToString());

                    return("/Account/LoginPrep");
                }
                else
                {
                    sb.Append(". Redirecting to SessionTimeout page.");
                    _logger.LogInformation(sb.ToString());

                    return("/Account/SessionTimeout");
                }
            }

            return(null);
        }
Esempio n. 10
0
        private bool ValidSession(LoginUpSequenceData sequenceData, SessionCookie session)
        {
            if (session == null)
            {
                return(false);
            }

            if (sequenceData.MaxAge.HasValue && DateTimeOffset.UtcNow.ToUnixTimeSeconds() - session.CreateTime > sequenceData.MaxAge.Value)
            {
                logger.ScopeTrace($"Session max age not accepted, Max age '{sequenceData.MaxAge}', Session created '{session.CreateTime}'.");
                return(false);
            }

            if (!sequenceData.UserId.IsNullOrWhiteSpace() && !session.UserId.Equals(sequenceData.UserId, StringComparison.OrdinalIgnoreCase))
            {
                logger.ScopeTrace("Session user and requested user do not match.");
                return(false);
            }

            return(true);
        }
Esempio n. 11
0
        protected bool ValidateLogin()
        {
            var cookie = Request.Cookies["Token"];

            if (cookie == null)
            {
                return(false);
            }

            cookie = Encoding.ASCII.GetString(
                cry.Decrypt(JsonSerializer.Deserialize <byte[]>(cookie), RSAEncryptionPadding.OaepSHA256));

            SessionCookie sessionCookie = JsonSerializer.Deserialize <SessionCookie>(cookie);
            Session       session       = _adminContext.Session.Find(sessionCookie.Id);

            if (session == null)
            {
                return(false);
            }

            if (session.Token != sessionCookie.Token)
            {
                _adminContext.Session.Remove(session);

                _adminContext.SaveChanges();

                return(false);
            }

            if (Session.CurrentTimestamp() - session.Lmd > 30 * 60 * 1000)
            {
                _adminContext.Session.Remove(session);

                _adminContext.SaveChanges();

                return(false);
            }

            return(true);
        }
Esempio n. 12
0
        public async Task CreateSessionAsync(LoginUpParty loginUpParty, User user, long authTime, List <string> authMethods, string sessionId)
        {
            if (SessionEnabled(loginUpParty))
            {
                logger.ScopeTrace($"Create session for User '{user.Email}', User id '{user.UserId}', Session id '{sessionId}', Route '{RouteBinding.Route}'.");

                var session = new SessionCookie
                {
                    Email     = user.Email,
                    UserId    = user.UserId,
                    SessionId = sessionId
                };
                session.CreateTime  = authTime;
                session.LastUpdated = authTime;
                session.AuthMethods = authMethods;
                await sessionCookieRepository.SaveAsync(session, GetPersistentCookieExpires(loginUpParty, session.CreateTime));

                logger.ScopeTrace($"Session created, Session id '{session.SessionId}'.", new Dictionary <string, string> {
                    { "sessionId", session.SessionId }
                });
            }
        }
        public void RemoveSessionCookie(string userName)
        {
            if (_logger.IsEnabled(LogLevel.Debug))
            {
                _logger.LogDebug("[SessionCookieService][RemoveSessionCookie] => Removing SessionCookie for '" + userName + "'");
            }

            SessionCookie sessionCookie = this.RetrieveSessionCookie(userName);

            if (sessionCookie == null)
            {
                StringBuilder sb = new StringBuilder("[SessionCookieService][RemoveSessionCookie] => SessionCookie for '");
                sb.Append(userName);
                sb.Append("' NOT FOUND! Throwing ApplicationException!");
                var errMsg = sb.ToString();

                _logger.LogError(errMsg);
                throw new ApplicationException(errMsg);
            }

            _sessionCookieRepo.Delete(sessionCookie);
        }
Esempio n. 14
0
        private bool SessionValid(LoginUpParty loginUpParty, SessionCookie session)
        {
            var created     = DateTimeOffset.FromUnixTimeSeconds(session.CreateTime);
            var lastUpdated = DateTimeOffset.FromUnixTimeSeconds(session.LastUpdated);
            var now         = DateTimeOffset.UtcNow;

            if (loginUpParty.PersistentSessionLifetimeUnlimited.Value)
            {
                return(true);
            }
            else if (created.AddSeconds(loginUpParty.PersistentSessionAbsoluteLifetime) >= now)
            {
                return(true);
            }
            else if (lastUpdated.AddSeconds(loginUpParty.SessionLifetime) >= now && created.AddSeconds(loginUpParty.SessionAbsoluteLifetime) >= now)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 15
0
        protected bool DoLogin(string username, string password)
        {
            var user = _adminContext.User.Where(user => user.Name == username).FirstOrDefault();

            if (user == null)
            {
                return(false);
            }

            if (Encoding.ASCII.GetString(cry.Decrypt(user.Pwd, RSAEncryptionPadding.OaepSHA256)) != password)
            {
                return(false);
            }

            Session session = new Session
            {
                UserId = user.Id,
                Token  = Session.GenerateToken(),
                Lmd    = Session.CurrentTimestamp()
            };

            _adminContext.Session.Add(session);

            _adminContext.SaveChanges();

            SessionCookie cookie = new SessionCookie
            {
                Id    = session.Id,
                Token = session.Token
            };

            Response.Cookies.Append("Token", JsonSerializer.Serialize(
                                        cry.Encrypt(Encoding.ASCII.GetBytes(JsonSerializer.Serialize(cookie)),
                                                    RSAEncryptionPadding.OaepSHA256)));

            return(true);
        }
Esempio n. 16
0
        public void OpenURL(string url, bool isPost, CookieContainer cookieJar = null)
        {
            var client = new RestClient();

            client.CookieContainer = cookieJar;

            var request = new RestRequest(url, isPost ? Method.POST : Method.GET)
            {
                RequestFormat = DataFormat.Json
            };

            AddNetworkActivity(url);

            client.ExecuteAsync(request, response => {
                if (response.Cookies.Count > 0)
                {
                    if (response.Cookies[0].Name == "_whitepaperbible_session")
                    {
                        UserSessionCookie = new SessionCookie {
                            Name  = response.Cookies[0].Name,
                            Value = response.Cookies[0].Value
                        };
                    }
                }

                ResponseText = response.Content;
                RemoveNetworkActivity(url);
                if (response.ResponseStatus == ResponseStatus.Error)
                {
                    DispatchError();
                }
                else
                {
                    DispatchComplete();
                }
            });
        }
Esempio n. 17
0
 public void Create(SessionCookie sessionCookie)
 {
     _dbContext.SessionCookies.Add(sessionCookie);
     _dbContext.SaveChanges();
 }
 public override string ToString()
 {
     return($"{ClientSessionInfo.ToString()}::SessionCookie={SessionCookie.ToString()};SessionKey=XXX;SessionIV=XXX");
 }
Esempio n. 19
0
 public void Update(SessionCookie sessionCookie)
 {
     _dbContext.SessionCookies.Update(sessionCookie);
     _dbContext.SaveChanges();
 }
Esempio n. 20
0
 public void Delete(SessionCookie sessionCookie)
 {
     _dbContext.SessionCookies.Remove(sessionCookie);
     _dbContext.SaveChanges();
 }
Esempio n. 21
0
        public async Task <string> Download(string url, CancellationTokenSource token = null, SessionCookie sessionCookie = null)
        {
            _currentToken = token ?? new CancellationTokenSource();

            var handler      = _modernModernHttpClient.GetNativeHandler();
            var outerHandler = new RetryHandler(handler, 3);
            var client       = _modernModernHttpClient.Get(outerHandler);

            if (sessionCookie != null)
            {
                var cookieJar = new CookieContainer();
                cookieJar.Add(new Uri(Constants.BASE_URI), new Cookie(sessionCookie.Name, sessionCookie.Value));
            }

            var msg = await client.GetAsync(url, _currentToken.Token);

            if (!msg.IsSuccessStatusCode)
            {
                return("Something derped");
            }

            var result = await msg.Content.ReadAsStringAsync();

            return(result);
        }
        public AuthorizeRequestValidator(IdentityServerOptions options, IClientStore clients, ICustomRequestValidator customValidator, IRedirectUriValidator uriValidator, ScopeValidator scopeValidator, SessionCookie sessionCookie)
        {
            _options         = options;
            _clients         = clients;
            _customValidator = customValidator;
            _uriValidator    = uriValidator;
            _scopeValidator  = scopeValidator;
            _sessionCookie   = sessionCookie;

            _validatedRequest = new ValidatedAuthorizeRequest
            {
                Options = _options,
            };
        }
Esempio n. 23
0
        private async Task <IActionResult> LoginResponse(LoginUpParty loginUpParty, User user, SessionCookie session = null)
        {
            var authTime    = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            var authMethods = new List <string>();

            authMethods.Add(IdentityConstants.AuthenticationMethodReferenceValues.Pwd);

            string sessionId = null;

            if (session != null && await sessionLogic.UpdateSessionAsync(loginUpParty, session))
            {
                sessionId = session.SessionId;
            }
            else
            {
                sessionId = RandomGenerator.Generate(24);
                await sessionLogic.CreateSessionAsync(loginUpParty, user, authTime, authMethods, sessionId);
            }

            return(await loginUpLogic.LoginResponseAsync(loginUpParty, user, authTime, authMethods, sessionId));
        }
Esempio n. 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EndSessionController"/> class.
 /// </summary>
 /// <param name="options">The options.</param>
 /// <param name="validator">The validator.</param>
 /// <param name="generator">The generator.</param>
 /// <param name="clientListCookie">The client list.</param>
 /// <param name="clientStore">The client store.</param>
 /// <param name="sessionCookie">The session cookie.</param>
 public EndSessionController(IdentityServerOptions options, EndSessionRequestValidator validator, EndSessionResponseGenerator generator, ClientListCookie clientListCookie, IClientStore clientStore, SessionCookie sessionCookie)
 {
     _options          = options;
     _validator        = validator;
     _generator        = generator;
     _clientListCookie = clientListCookie;
     _clientStore      = clientStore;
     _sessionCookie    = sessionCookie;
 }