예제 #1
0
 public static void RegisterUserSession(Guid identifier, string username)
 {
     sessionService.Add(new SessionModel()
     {
         Cookie   = identifier.ToString(),
         Username = username,
         Expire   = DateTime.UtcNow.AddSeconds(Config.sessionTimeout)
     });
 }
예제 #2
0
        public void Session_Service_Should_Add_Session_Successfully()
        {
            //Arrange
            var session    = ObjectMother.GetDefaultSession();
            var sessionCmd = ObjectMother.GetSessionAddCommand();

            _mockSessionRepository.Setup(r => r.Add(It.IsAny <Session>())).Returns(session);
            _mockMovieService.Setup(r => r.GetById(It.IsAny <long>())).Returns(ObjectMother.GetDefaultMovie());
            _mockLoungeService.Setup(r => r.GetById(It.IsAny <long>())).Returns(ObjectMother.GetDefaultLounge());
            _mockLoungeService.Setup(r => r.GetAll()).Returns(new List <Lounge>()
            {
                ObjectMother.GetDefaultLounge()
            }.AsQueryable());

            //Action
            var addedSession = _sessionService.Add(sessionCmd);

            //Assert
            _mockSessionRepository.Verify(r => r.Add(It.IsAny <Session>()), Times.Once);
            addedSession.Id.Should().Be(session.Id);
        }
예제 #3
0
        public ActionResult Create(SessionView session)
        {
            if (ModelState.IsValid)
            {
                _sessionService.Add(session);

                return(RedirectToAction("Index"));
            }
            else
            {
                return(View());
            }
        }
예제 #4
0
        private async Task <Result> Start(AppUserEntity appUser)
        {
            string impersonizerId = _identityUIUserInfoService.GetImpersonatorId();

            if (!string.IsNullOrEmpty(impersonizerId))
            {
                _logger.LogError($"User is already impersonating somebody");
                return(Result.Fail(ALREADY_IMPERSONATING));
            }

            string userId = _identityUIUserInfoService.GetUserId();

            if (userId == appUser.Id)
            {
                _logger.LogError($"Can not impersonate self");
                return(Result.Fail(CAN_NOT_IMPERSONATE_SELF));
            }

            appUser.SessionCode = Guid.NewGuid().ToString();

            Result addSessionResult = await _sessionService.Add(appUser.SessionCode, appUser.Id);

            if (addSessionResult.Failure)
            {
                return(Result.Fail(FAILED_TO_ADD_SESSION));
            }

            string loggedInUserId = _identityUIUserInfoService.GetUserId();

            appUser.ImpersonatorId = loggedInUserId;

            _logger.LogInformation($"User is starting to impersonate another user. ImpersnonazerId {loggedInUserId}, user to be impersonalized {appUser.Id}");

            await _signInManager.SignOutAsync();

            await _signInManager.SignInAsync(appUser, false);

            return(Result.Ok());
        }
예제 #5
0
        public string Add(ISession session)
        {
            var entity = _sessionService.Get(session.Id);

            if (entity != null)
            {
                //TODO: define bihaviour in case when session already exists
            }
            else
            {
                _sessionService.Add(session);
            }

            return("Я помогу вам следить за временем в игре. Для начала, давайте познакомимся. Кто будет первым игроком?");
        }
        public ActionResult Login(UserForLoginDto userForLoginDto)
        {
            var userToLogin = _authorizationService.Login(userForLoginDto);

            if (!userToLogin.Success)
            {
                return(BadRequest(userToLogin.Message));
            }

            var result = _authorizationService.CreateAccessToken(userToLogin.Data);

            if (!result.Success)
            {
                return(BadRequest(result.Message));
            }
            var endDate = (userForLoginDto.KeepSession) ? DateTime.Now.AddDays(7) : DateTime.Now.AddHours(12);
            var session = new Session {
                AccessToken = Guid.NewGuid().ToString(), RefreshToken = Guid.NewGuid().ToString(), CreatedDate = DateTime.Now, IsActive = true, UserId = userToLogin.Data.Id, SessionExpireDate = endDate
            };

            session.FillClientDetails(Request);
            var activeSessions = _sessionService.GetActiveSessions(userToLogin.Data.Id);

            if (activeSessions.Count() >= userForLoginDto.MaxSessionLimit)
            {
                return(Ok(new Result(ResultType.USER_MAX_SESSION_LIMIT)));
            }
            else
            {
                if (_sessionService.Add(session).Success)
                {
                    return(Ok(result.Data));
                }
                else
                {
                    return(BadRequest(new Result(ResultType.BAD_REQUEST)));
                }
            }
        }
예제 #7
0
        public async Task <SignInResult> Login(string ip, string sessionCode, LoginRequest login)
        {
            ValidationResult validationResult = _loginValidator.Validate(login);

            if (!validationResult.IsValid)
            {
                _logger.LogError($"Invalid LoginRequest. UserName {login?.UserName}");
                return(SignInResult.Failed);
            }

            await _signInManager.SignOutAsync();

            AppUserEntity appUser = await _userManager.FindByNameAsync(login.UserName);

            if (appUser == null)
            {
                _logger.LogInformation($"No user with username {login.UserName}");
                return(SignInResult.Failed);
            }

            if (sessionCode != null)
            {
                _sessionService.Logout(sessionCode, appUser.Id, SessionEndTypes.Expired);
            }

            if (!appUser.CanLogin())
            {
                _logger.LogInformation($"User is not allowd to login. User {appUser.Id}");
                return(SignInResult.Failed);
            }

            appUser.SessionCode = Guid.NewGuid().ToString();

            Result addSessionResult = _sessionService.Add(appUser.SessionCode, appUser.Id, ip);

            if (addSessionResult.Failure)
            {
                return(SignInResult.Failed);
            }

            SignInResult result = await _signInManager.PasswordSignInAsync(appUser, login.Password, login.RememberMe, lockoutOnFailure : true);

            if (!result.Succeeded)
            {
                if (result.RequiresTwoFactor)
                {
                    _logger.LogInformation($"Login Requires TwoFactor. User {appUser.Id}");
                    _sessionService.Logout(appUser.SessionCode, appUser.Id, SessionEndTypes.TwoFactorLogin);
                }

                if (!result.IsLockedOut)
                {
                    _logger.LogInformation($"Faild to log in user. User {appUser.Id}");
                    _sessionService.Logout(appUser.SessionCode, appUser.Id, SessionEndTypes.InvalidLogin);
                }

                return(result);
            }

            _logger.LogInformation($"User loged in. UserId {appUser.Id}");

            return(result);
        }
예제 #8
0
        internal bool AuthenticationFailedIfRequired(HttpListenerContext context, HttpListenerRequest request, HttpListenerResponse response, ChannelConfigurationInfo channelConfig, out bool authenticated)
        {
            bool failed      = false;
            bool validCookie = false;

            authenticated = false;
            bool authorized = false;

            if (channelConfig.ChannelAttribute.EnableSessions)
            {
                validCookie = ValidSession(request);
            }
            if (channelConfig.AuthenticationRequired && !validCookie)
            {
                try
                {
                    ChannelAuthenticationContext authContext = new ChannelAuthenticationContext
                    {
                        Context = context,
                        Scheme  = channelConfig.AuthScheme,
                        BasicAuthenticationDelegate = _basicAuthenticationMethod,
                        TokenAuthenticationDelegate = _tokenAuthenticationMethod,
                        AuthenticationSettings      = _settings
                    };

                    KeyValuePair <bool, object> authenticationResult = _authenticationService.CheckAuthenticationAndGetResponseObject(authContext);
                    if (authenticationResult.Key == true)
                    {
                        authenticated = true;
                    }
                    else
                    {
                        _msgService.FailedAuthenticationResponse(channelConfig.AuthScheme, response);
                        return(true);
                    }
                    LogChannel.Write(LogSeverity.Info, "User Authenticated");
                    string claimName  = channelConfig.AuthorizeAttribute.ClaimName;
                    string claimValue = channelConfig.AuthorizeAttribute.ClaimValue;
                    if (!String.IsNullOrEmpty(claimName) && !String.IsNullOrEmpty(claimValue))
                    {
                        if (authenticationResult.Value.GetType() == typeof(ClaimsPrincipal))
                        {
                            authorized = _authenticationService.Authorized(claimName, claimValue, (ClaimsPrincipal)authenticationResult.Value);
                        }
                        else
                        {
                            authorized = _authenticationService.Authorized(claimName, claimValue, (Claim[])authenticationResult.Value);
                        }

                        if (!authorized)
                        {
                            _msgService.FailedAuthorizationResponse(response);
                            LogChannel.Write(LogSeverity.Error, "Failed authorization");
                            failed = true;
                        }
                        else
                        {
                            LogChannel.Write(LogSeverity.Info, "User Authorized");
                        }
                    }
                }
                catch (Exception ex)
                {
                    using (StreamWriter writer = new StreamWriter(response.OutputStream))
                    {
                        _msgService.ExceptionHandler(writer, ex, response);
                        LogChannel.Write(LogSeverity.Error, "Authentication Failed");
                        failed = true;
                    }
                }
                if (!authenticated)
                {
                    failed = true;
                }
                else
                {
                    if (channelConfig.ChannelAttribute.EnableSessions)
                    {
                        string sessionKey    = Guid.NewGuid().ToString();
                        Cookie sessionCookie = new Cookie()
                        {
                            Expires = DateTime.Now.AddMinutes(30),
                            Name    = "channelAuthCookie",
                            Secure  = true,
                            Value   = sessionKey
                        };
                        response.SetCookie(sessionCookie);
                        _session.Add(sessionCookie);
                    }
                }
            }

            return(failed);
        }
예제 #9
0
 public IActionResult AddSession(Session session)
 {
     sessionService.Add(session);
     return(RedirectToAction("Index"));
 }