Ejemplo n.º 1
0
        public IActionResult ReceiveAuthorizationCodeFacebook(
            [FromQuery] RedirectionErrorModelFacebook error,
            [FromQuery] AuthorizationCodeModel authorizationCode)
        {
            if (authorizationCode?.SessionId == null)
            {
                _logger.LogError("Received redirect request from Facebook without session id (state)");
                return(BadRequest(ErrorModel.AuthorizationError("Session Id is missing.")));
            }

            if (error.Error != null || error.ErrorDescription != null)
            {
                _logger.LogError(@$ "Received redirect request from Facebook with error query params: {error.Error}  |  {error.ErrorDescription}");
                return(BadRequest(ErrorModel.AuthorizationError($"{error.Error} {error.ErrorDescription}")));
            }

            string socialServiceName = "facebook";

            _userProfileReceivingServiceContext.SetStrategies(
                _tokenReceivingServices.First(s => s.SocialServiceName == socialServiceName),
                _profileManagingServices.First(s => s.SocialServiceName == socialServiceName));

            _memoryCache.TryGetValue(authorizationCode.SessionId, out CacheModel cache);
            string scope = _context.Settings.FirstOrDefault(x => x.AppId == cache.AppId && x.SocialId == cache.SocialId).Scope;

            authorizationCode.Scope = scope;

            return(ContinueFlow(authorizationCode));
        }
Ejemplo n.º 2
0
        public async Task <IActionResult> GetUserProfileAsync(
            [FromHeader(Name = "App_id")] int appId,
            [FromBody] SessionIdModel sessionIdModel)
        {
            if (sessionIdModel == null || string.IsNullOrWhiteSpace(sessionIdModel.SessionId))
            {
                _logger.LogError("Request body doesn't contain session id or it is empty");
                return(BadRequest(ErrorModel.SessionIdError));
            }

            bool isSuccess = _memoryCache.TryGetValue(sessionIdModel.SessionId, out CacheModel sessionInfo);

            if (isSuccess == false || sessionInfo == null)
            {
                _logger.LogError("Unable to find session id in memory cache." +
                                 "Authorization timeout has expired");
                return(BadRequest(ErrorModel.SessionIdError));
            }

            if (sessionInfo.UserStartedAuthorization == false)
            {
                return(BadRequest(ErrorModel.AuthorizationAborted));
            }

            isSuccess = _memoryCache.TryGetValue(sessionIdModel.SessionId, out sessionInfo);
            if (isSuccess && sessionInfo?.UserProfile == null)
            {
                int requestCounter = 0;
                while (requestCounter < 50)
                {
                    isSuccess = _memoryCache.TryGetValue(sessionIdModel.SessionId, out sessionInfo);
                    if (isSuccess && sessionInfo?.UserProfile != null)
                    {
                        break;
                    }

                    await Task.Delay(200);

                    requestCounter++;
                }
            }


            if (sessionInfo?.UserProfile == null)
            {
                _logger.LogError("Unable to find user's profile in memory cache." +
                                 "Error occured during the authorization process");
                return(BadRequest(ErrorModel.AuthorizationError("Error occured during the authorization process. " +
                                                                "Unable to receive user's profile for some reasons")));
            }

            return(Ok(_memoryCache.Get <CacheModel>(sessionIdModel.SessionId).UserProfile));
        }
Ejemplo n.º 3
0
        public IActionResult ReceiveAuthorizationCodeGoogle(
            [FromQuery] RedirectionErrorModelGoogle error,
            [FromQuery] AuthorizationCodeModel authorizationCode)
        {
            if (authorizationCode?.SessionId == null)
            {
                _logger.LogError("Received redirect request from Google without session id (state)");
                return(BadRequest(ErrorModel.AuthorizationError("Session Id is missing.")));
            }

            if (error.Error != null || error.ErrorDescription != null)
            {
                _logger.LogError(@$ "Received redirect request from Google with error query params: {error.Error}  |  {error.ErrorDescription}");
                return(BadRequest(ErrorModel.AuthorizationError($"{error.Error} {error.ErrorDescription}")));
            }

            string socialServiceName = "google";

            _userProfileReceivingServiceContext.SetStrategies(
                _tokenReceivingServices.First(s => s.SocialServiceName == socialServiceName),
                _profileManagingServices.First(s => s.SocialServiceName == socialServiceName));

            return(ContinueFlow(authorizationCode));
        }
Ejemplo n.º 4
0
        private IActionResult ContinueFlow(AuthorizationCodeModel authorizationCode)
        {
            CacheModel session = _memoryCache.Get <CacheModel>(authorizationCode.SessionId);

            if (session == null)
            {
                _logger.LogError("Authorization time has expired");
                return(BadRequest(ErrorModel.AuthorizationError("Time for authorization has expired")));
            }
            string device = session.Device.ToLower().Trim();

            session.UserStartedAuthorization = true;

            try
            {
                _userProfileReceivingServiceContext.Execute(session.AppId, authorizationCode);
            }
            catch (AuthorizationCodeExchangeException exception)
            {
                _logger.LogError("Error occured during authorization code exchange or process of receiving user profile from social service\n " +
                                 $"Error: {exception.Description?.Error}\n ErrorDescription: {exception.Description?.ErrorDescription}");
            }

            if (device.Equals("browser"))
            {
                return(new ContentResult
                {
                    ContentType = "text/html",
                    Content = "<script>window.close()</script>"
                });
            }
            else
            {
                return(Redirect(device));
            }
        }
Ejemplo n.º 5
0
        public async Task <ActionResult <AdminProfile> > GetTokenAndProfile(
            [FromBody, Required] SessionIdModel sessionIdModel)
        {
            if (sessionIdModel == null || string.IsNullOrWhiteSpace(sessionIdModel.SessionId))
            {
                return(BadRequest(ErrorModel.SessionIdError));
            }

            bool isSuccess = _memoryCache.TryGetValue(sessionIdModel.SessionId, out CacheModel sessionInfo);

            if (isSuccess == false || sessionInfo == null)
            {
                return(BadRequest(ErrorModel.SessionIdError));
            }

            if (sessionInfo.UserStartedAuthorization == false)
            {
                return(BadRequest(ErrorModel.AuthorizationAborted));
            }

            isSuccess = _memoryCache.TryGetValue(sessionIdModel.SessionId, out sessionInfo);
            if (isSuccess && sessionInfo?.UserProfile == null)
            {
                int requestCounter = 0;
                while (requestCounter < 50)
                {
                    isSuccess = _memoryCache.TryGetValue(sessionIdModel.SessionId, out sessionInfo);
                    if (isSuccess && sessionInfo?.UserProfile != null)
                    {
                        break;
                    }

                    await Task.Delay(200);

                    requestCounter++;
                }
            }

            if (sessionInfo?.UserProfile == null)
            {
                return(BadRequest(ErrorModel.AuthorizationError("Error occured during the authorization process. " +
                                                                "Unable to receive user's profile for some reasons")));
            }

            var admin = new AdminProfile(_memoryCache.Get <CacheModel>(sessionIdModel.SessionId).UserProfile);

            if (_backOfficeContext.Admins.FirstOrDefault(a => a.Name == admin.Id) == null)
            {
                await _backOfficeContext.Admins.AddAsync(new Admin()
                {
                    Name = admin.Id
                });

                await _backOfficeContext.SaveChangesAsync();
            }

            var identity     = _authService.GetIdentity(admin.Id);
            var jwt          = _authService.GenerateToken(identity.Claims);
            var encodedJwt   = new JwtSecurityTokenHandler().WriteToken(jwt);
            var refreshToken = _authService.GenerateRefreshToken();

            _refreshTokenService.SaveRefreshToken(identity.Name, refreshToken);

            Response.Cookies.Append("X-Refresh-Token", refreshToken,
                                    new CookieOptions {
                HttpOnly = true, Secure = true, Expires = DateTime.UtcNow.AddDays(7), SameSite = SameSiteMode.None
            });
            admin.Token = encodedJwt;
            return(new JsonResult(admin));
        }