|
| 1 | +using System.Security.Claims; |
| 2 | +using System.Text.Encodings.Web; |
| 3 | +using Microsoft.AspNetCore.Authentication; |
| 4 | +using Microsoft.Extensions.Options; |
| 5 | +using Microsoft.Extensions.Primitives; |
| 6 | +using Tevling.Strava; |
| 7 | + |
| 8 | +namespace Tevling.Authentication; |
| 9 | + |
| 10 | +public class StravaAuthenticationHandler( |
| 11 | + IStravaClient stravaClient, |
| 12 | + IAthleteService athleteService, |
| 13 | + IOptionsMonitor<StravaAuthenticationOptions> options, |
| 14 | + ILoggerFactory logger, |
| 15 | + UrlEncoder encoder) |
| 16 | + : AuthenticationHandler<StravaAuthenticationOptions>(options, logger, encoder) |
| 17 | +{ |
| 18 | + protected override async Task<AuthenticateResult> HandleAuthenticateAsync() |
| 19 | + { |
| 20 | + if (!Request.Headers.TryGetValue(Options.TokenHeaderName, out StringValues tokenValues) && |
| 21 | + !Request.Query.TryGetValue(Options.TokenQueryName, out tokenValues)) |
| 22 | + { |
| 23 | + return AuthenticateResult.NoResult(); |
| 24 | + } |
| 25 | + |
| 26 | + string? token = tokenValues.Single(); |
| 27 | + |
| 28 | + if (token is null) |
| 29 | + { |
| 30 | + return AuthenticateResult.Fail("Token is null"); |
| 31 | + } |
| 32 | + |
| 33 | + SummaryAthlete stravaAthlete = await stravaClient.GetAuthenticatedAthleteAsync(token); |
| 34 | + Athlete? athlete = await athleteService.GetAthleteByStravaIdAsync(stravaAthlete.Id); |
| 35 | + |
| 36 | + if (athlete is null) |
| 37 | + { |
| 38 | + return AuthenticateResult.Fail("Unknown athlete"); |
| 39 | + } |
| 40 | + |
| 41 | + Claim[] claims = |
| 42 | + [ |
| 43 | + new(ClaimTypes.Name, athlete.Name), |
| 44 | + new(ClaimTypes.NameIdentifier, athlete.Id.ToString()), |
| 45 | + ]; |
| 46 | + |
| 47 | + ClaimsIdentity claimsIdentity = new(claims, Scheme.Name); |
| 48 | + ClaimsPrincipal claimsPrincipal = new(claimsIdentity); |
| 49 | + AuthenticationTicket authenticationTicket = new(claimsPrincipal, Scheme.Name); |
| 50 | + |
| 51 | + return AuthenticateResult.Success(authenticationTicket); |
| 52 | + } |
| 53 | +} |
0 commit comments