Exemplo n.º 1
0
        private async Task <AthleteStatsModel> GetAthleteStatsAsync(string token, LinkedAccount linkedAccount, ILogger logger, CancellationToken cancellationToken)
        {
            try
            {
                var request = new HttpRequestMessage(HttpMethod.Get, new Uri("https://" + $"www.strava.com/api/v3/athletes/{linkedAccount.StravaAccountId}/stats"));
                request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);

                HttpResponseMessage response = await _httpClient.SendAsync(request, cancellationToken);

                response.EnsureSuccessStatusCode();

                string responseBody = await response.Content.ReadAsStringAsync();

                logger.LogInformation($"Received response from Strava: '{responseBody}'");

                AthleteStatsModel statsModel = JsonConvert.DeserializeObject <AthleteStatsModel>(responseBody);
                return(statsModel);
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "Error occurred while requesting athlete info from Strava");
                return(null);
            }
        }
Exemplo n.º 2
0
        public async Task <IActionResult> RunAsync(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "userinfo")]
            HttpRequest request,
            [Table("LinkedAccounts")] CloudTable table,
            ILogger logger,
            CancellationToken cancellationToken)
        {
            try
            {
                // The "user" returned here is an actual ClaimsPrincipal with the claims that were in the access_token.
                // The "token" is a SecurityToken that can be used to invoke services on the part of the user. E.g., create a Google Calendar event on the user's calendar.
                (ClaimsPrincipal user, SecurityToken token) = await _auth0Authenticator.AuthenticateAsync(request, logger, cancellationToken);

                string userId = _auth0Authenticator.GetUserId(user);
                logger.LogInformation($"User authenticated, user id='{userId}'");

                UserInfoModel userInfo = new UserInfoModel();

                LinkedAccount linkedAccount = await _linkedAccountService.GetLinkedAccountAsync(userId, table, logger);

                if (linkedAccount != null)
                {
                    // validate that the access token has not expired and renew if needed
                    string accessToken = await GetValidStravaAccessTokenAsync(linkedAccount, table, logger, cancellationToken);

                    if (accessToken != null)
                    {
                        AthleteModel athlete = await GetAthleteAsync(accessToken, linkedAccount, table, logger, cancellationToken);

                        if (athlete != null)
                        {
                            logger.LogInformation($"Got athlete info from Strava: '{athlete}'");

                            userInfo.FirstName  = athlete.FirstName;
                            userInfo.LastName   = athlete.LastName;
                            userInfo.Country    = athlete.Country;
                            userInfo.City       = athlete.City;
                            userInfo.PictureUrl = athlete.Profile;

                            userInfo.IsStravaAccountLinked = true;
                        }

                        AthleteStatsModel stats = await GetAthleteStatsAsync(accessToken, linkedAccount, logger, cancellationToken);

                        if (stats != null)
                        {
                            logger.LogInformation($"Got athlete stats from Strava: '{stats}'");

                            userInfo.Runs  = stats.AllRunsTotals.Count;
                            userInfo.Swims = stats.AllSwimsTotals.Count;
                            userInfo.Rides = stats.AllRidesTotals.Count;
                        }
                    }
                }

                return(new OkObjectResult(userInfo));
            }
            catch (AuthException)
            {
                return(new UnauthorizedResult());
            }
        }