private TokenDetails GetToken(List <KeyValuePair <string, string> > keyValues, ResponseBase response, int tokenScope, int refreshTokenType, string clientId)
        {
            HttpClient client = new HttpClient();

            client.Timeout = new TimeSpan(0, 0, hpidGetTokenTimeout);
            client.DefaultRequestHeaders.TryAddWithoutValidation("content-type", "application/x-www-form-urlencoded");
            TokenDetails _tokenDetails = new TokenDetails();

            _tokenDetails.tokenScopeType = (TokenScopeType)tokenScope;

            string hpidApiKeyAuth    = null;
            string hpidSecretKeyAuth = null;

            if (!String.IsNullOrEmpty(clientId))
            {
                hpidApiKeyAuth    = SettingRepository.Get <string>("HPIDApiKeyAUTH_" + clientId);
                hpidSecretKeyAuth = SettingRepository.Get <string>("HPIDApiSecretAUTH_" + clientId);
            }
            else
            {
                hpidApiKeyAuth    = SettingRepository.Get <string>("HPIDApiKeyAUTH");
                hpidSecretKeyAuth = SettingRepository.Get <string>("HPIDApiSecretAUTH");
            }


            if (tokenScope == (int)TokenScopeType.userAuthenticate ||
                refreshTokenType == (int)RefreshTokenLoginType.Authentication)
            {
                _tokenDetails.RefreshTokenType             = (int)RefreshTokenLoginType.Authentication;
                client.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Basic",
                                                  Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:", hpidApiKeyAuth) + string.Format("{0}", hpidSecretKeyAuth))));

                log.Debug($"getToken: AUTH: tokenScope='{tokenScope}' reftokentype='{refreshTokenType}' api='{hpidApiKeyAuth}' secret='{hpidSecretKeyAuth}' uri='{oauthUri}' ");
            }
            else
            {
                _tokenDetails.RefreshTokenType             = (int)RefreshTokenLoginType.Credentials;
                client.DefaultRequestHeaders.Authorization =
                    new AuthenticationHeaderValue("Basic",
                                                  Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:", hpidApiKey) + string.Format("{0}", hpidSecretKey))));

                log.Debug($"getToken: CRED: tokenScope='{tokenScope}' reftokentype='{refreshTokenType}'  api='{hpidApiKey}' secret='{hpidSecretKey}' uri='{oauthUri}' ");
            }

            try
            {
                var     postData  = new FormUrlEncodedContent(keyValues);
                var     resp      = client.PostAsync(oauthUri, postData);
                var     jResponse = resp.Result.Content.ReadAsStringAsync().Result;
                JObject respObj   = JObject.Parse(jResponse);

                try
                {
                    string error_cause = (string)respObj["error_cause"];
                    if (error_cause.Equals("accountLocked"))
                    {
                        log.Debug($"getToken: accountLocked");
                        response.ErrorList.Add(Faults.HPIDAccountLocked);
                        return(null);
                    }
                    log.Debug($"getToken: error_cause={error_cause}");
                }
                catch (Exception) { };

                _tokenDetails.AccessToken  = (string)respObj["access_token"];
                _tokenDetails.RefreshToken = (string)respObj["refresh_token"];

                log.Debug($"getToken response: RefreshToken={_tokenDetails.RefreshToken} AccessToken={_tokenDetails.AccessToken}");

                if (string.IsNullOrEmpty(_tokenDetails.RefreshToken))
                {
                    log.Debug($"getToken response: ALL={respObj}");
                }


                return(_tokenDetails);
            }
            catch (TimeoutException ex)
            {
                log.Debug($"getToken: Errortype=TimeoutException,Exception={ex.Message}");
                response.ErrorList.Add(new Fault(Faults.HPIDTimeoutError, ex));
                logger.Error($"GetToken: timeout exception ({ex.Message})");
            }
            catch (Exception ex)
            {
                log.Debug($"getToken: Errortype=Exception,Exception={ex.Message}");
                response.ErrorList.Add(new Fault(Faults.HPIDInternalError, ex));
                logger.Error($"GetToken: other exception ({ex.InnerException?.Message})");
            }

            return(null);
        }
예제 #2
0
        public SCQuery(
            LeagueRepository leagueRepository,
            PlayerRepository playerRepository,
            TournamentRepository tournamentRepository,
            FrameRepository frameRepository,
            UserRepository userRepository,
            SettingRepository settingRepository
            )
        {
            // Leagues
            Field <ListGraphType <LeagueType> >(
                "leagues",
                resolve: context => leagueRepository.Get(null, p => p.OrderBy(p => p.DisplayName))
                );
            Field <LeagueType>(
                "league",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IdGraphType> > {
                Name = "id"
            }),
                resolve: context => leagueRepository.GetById(context.GetArgument <Guid>("id"))
                );

            // Players
            Field <ListGraphType <PlayerType> >(
                "players",
                resolve: context => playerRepository.Get(null, p => p.OrderBy(p => p.FirstName))
                );
            Field <PlayerType>(
                "player",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IdGraphType> > {
                Name = "id"
            }),
                resolve: context => playerRepository.GetById(context.GetArgument <Guid>("id"))
                );

            // Tournaments
            Field <ListGraphType <TournamentType> >(
                "tournaments",
                resolve: context => tournamentRepository.Get(null, t => t.OrderByDescending(t => t.Date))
                );
            Field <TournamentType>(
                "tournament",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IdGraphType> > {
                Name = "id"
            }),
                resolve: context => tournamentRepository.GetById(context.GetArgument <Guid>("id"))
                );

            // Frames
            Field <ListGraphType <FrameType> >(
                "frames",
                resolve: context => frameRepository.Get(null, t => t.OrderByDescending(t => t.EndDate))
                );
            Field <FrameType>(
                "frame",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IdGraphType> > {
                Name = "id"
            }),
                resolve: context => frameRepository.GetById(context.GetArgument <Guid>("id"))
                );

            // Users
            Field <ListGraphType <UserType> >(
                "users",
                resolve: context =>
            {
                // TODO
                //ClaimsPrincipal user = (ClaimsPrincipal)context.UserContext;
                //if (!user.IsInRole("Admin")) { return null; }

                return(userRepository.Get());
            }
                );
            Field <UserType>(
                "user",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <IdGraphType> > {
                Name = "id"
            }),
                resolve: context =>
            {
                // TODO
                //ClaimsPrincipal user = (ClaimsPrincipal)context.UserContext;
                //if (!user.IsInRole("Admin")) { return null; }

                return(userRepository.GetById(context.GetArgument <Guid>("id")));
            }
                );

            // Settings
            Field <ListGraphType <SettingType> >(
                "settings",
                resolve: context => settingRepository.Get(null, s => s.OrderByDescending(s => s.Key))
                );
            Field <SettingType>(
                "setting",
                arguments: new QueryArguments(new QueryArgument <NonNullGraphType <StringGraphType> > {
                Name = "key"
            }),
                resolve: context => settingRepository.GetByKey(context.GetArgument <string>("key"))
                );
        }
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            bool         faultOccured = false;
            ResponseBase r            = new ResponseBase();

            try
            {
                base.OnAuthorization(actionContext);
                if (actionContext.ActionDescriptor.GetCustomAttributes <CredentialsHeaderAttribute>().Count == 0)
                {
                    return;
                }
                string credentialsValue = actionContext.Request.Headers.GetValues("Authorization").ElementAt(0);

                AccessCredentials credentials = new AccessCredentials();
                ParseAuthorizationHeader(credentialsValue, credentials, r);


                if (r.ErrorList.Count > 0)
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, r, GlobalConfiguration.Configuration);
                    faultOccured           = true;

                    return;
                }

                validateUserIdWithToken(r, credentials);

                if (!credentials.IsValid(r))
                {
                    actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, r, GlobalConfiguration.Configuration);
                    faultOccured           = true;

                    return;
                }



                var Controller = actionContext.ControllerContext.Controller as Controllers.RESTAPIControllerBase;
                Controller.UserID       = credentials.UserID;
                Controller.SessionToken = credentials.SessionToken;
                Controller.CallerId     = credentials.CallerId;
                Controller.LanguageCode = credentials.LanguageCode;
                Controller.CountryCode  = credentials.CountryCode;
                Controller.Token        = credentials.Token;
                Controller.LoginDate    = credentials.LoginDate;

                if (credentials.Platform != null)
                {
                    var isPlatformDefined = Enum.IsDefined(typeof(RESTAPIPlatform), credentials.Platform);
                    if (isPlatformDefined)
                    {
                        Controller.ClientPlatform = (RESTAPIPlatform)Enum.Parse(typeof(RESTAPIPlatform), credentials.Platform);
                    }
                    else
                    {
                        Controller.ClientPlatform = RESTAPIPlatform.notsupported;
                    }
                }
                if (r.ErrorList.Count == 0)
                {
                    IsAuthorized(actionContext);
                }


                return;
            }
            catch (Exception)
            {
                r.ErrorList.Add(Faults.InvalidCredentials);
                actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.OK, r, GlobalConfiguration.Configuration);
                faultOccured           = true;
            }
            finally
            {
                APILogLevel apiLogLevel;
                Enum.TryParse(SettingRepository.Get <string>("LogAPICalls", "None"), out apiLogLevel);
                if (faultOccured)
                {
                    filterUtils.Translation(actionContext);
                    filterUtils.LogIntoAdmLogsTable(actionContext.Request, actionContext.Response, actionContext, null, apiLogLevel, faultOccured, false);
                }
            }
        }