Beispiel #1
0
        private async Task <string> AddTokens(string userId, TokenResponse tokens, string type)
        {
            var storedConfiguration = new StoredConfiguration()
            {
                Id   = Guid.NewGuid().ToString(),
                Type = type
            };

            FillTokens(storedConfiguration, tokens);
            var user = await context.Users.Include(v => v.Configurations).FirstOrDefaultAsync(v => v.Id == userId);

            if (null == user)
            {
                user = new User()
                {
                    Id             = userId,
                    Configurations = new List <StoredConfiguration>()
                    {
                        storedConfiguration
                    }
                };
                await context.Users.AddAsync(user);
            }
            else
            {
                if (null == user.Configurations)
                {
                    user.Configurations = new List <StoredConfiguration>();
                }
                user.Configurations.Add(storedConfiguration);
            }
            await context.SaveChangesAsync();

            return(storedConfiguration.Id);
        }
 public GraphCalendarProvider(IGraphAuthenticationProviderFactory graphAuthenticationProviderFactory,
                              StoredConfiguration config,
                              IOptions <CalendarConfigurationOptions> optionsAccessor)
 {
     this.graphAuthenticationProviderFactory = graphAuthenticationProviderFactory;
     this.config = config;
     options     = optionsAccessor.Value;
 }
 public GoogleCalendarProvider(StoredConfiguration config, IGoogleCredentialProvider googleCredentialProvider,
                               IOptions <CalendarConfigurationOptions> optionsAccessor, ILogger <GoogleCalendarProvider> logger,
                               GoogleCalendarColorProvider googleCalendarColorProvider)
 {
     this.config = config;
     this.googleCredentialProvider = googleCredentialProvider;
     this.logger = logger;
     _googleCalendarColorProvider = googleCalendarColorProvider;
     options = optionsAccessor.Value;
 }
 public GoogleCalendarColorProvider(IMemoryCache memoryCache,
                                    StoredConfiguration config,
                                    IGoogleCredentialProvider googleCredentialProvider,
                                    ILogger <GoogleCalendarColorProvider> logger)
 {
     _memoryCache = memoryCache;
     _config      = config;
     _googleCredentialProvider = googleCredentialProvider;
     _logger = logger;
 }
        private ICalendarProvider GetProvider(StoredConfiguration config)
        {
            switch (config.Type)
            {
            case CalendarType.Microsoft:
                return(graphCalendarProviderFactory.GetProvider(config));

            case CalendarType.Google:
                return(googleCalendarProviderFactory.GetProvider(config));

            default:
                throw new NotImplementedException();
            }
        }
        public async Task <IConfigurableHttpClientInitializer> CreateByConfigAsync(StoredConfiguration config)
        {
            var semaphore = ConfigurationRepository.ConfigSemaphores.GetOrAdd(config.Id, new SemaphoreSlim(1));

            try
            {
                await semaphore.WaitAsync(); //if the authenticationprovider is used concurrently, only the first parallel usage shall refresh the token

                if (config.ExpiresIn <= DateTime.Now)
                {
                    var flow = new Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow(new Google.Apis.Auth.OAuth2.Flows.GoogleAuthorizationCodeFlow.Initializer()
                    {
                        Scopes = new[] { "https://www.googleapis.com/auth/calendar.events.readonly",
                                         "https://www.googleapis.com/auth/calendar.readonly" },
                        ClientSecrets = new ClientSecrets()
                        {
                            ClientId     = options.GoogleClientID,
                            ClientSecret = options.GoogleClientSecret
                        }
                    });
                    Google.Apis.Auth.OAuth2.Responses.TokenResponse tokenResponse;
                    try
                    {
                        tokenResponse = await flow.RefreshTokenAsync("unused", config.RefreshToken, CancellationToken.None);
                    }
                    catch (TokenResponseException e)
                    {
                        throw new CalendarConfigurationException($"Google: Could not redeem authorization code: {e.Error.ErrorDescription}", e);
                    }
                    var tokens = new TokenResponse()
                    {
                        access_token  = tokenResponse.AccessToken,
                        expires_in    = (int)tokenResponse.ExpiresInSeconds,
                        refresh_token = tokenResponse.RefreshToken ?? config.RefreshToken
                    };
                    config = await configurationRepository.RefreshTokens(config.Id, tokens);
                }
            }
            finally
            {
                semaphore.Release();
            }
            return(GoogleCredential.FromAccessToken(config.AccessToken));
        }
        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            var semaphore = ConfigurationRepository.ConfigSemaphores.GetOrAdd(config.Id, new SemaphoreSlim(1));
            await semaphore.WaitAsync(); //if the authenticationprovider is used concurrently, only the first parallel usage shall refresh the token

            try
            {
                if (config.ExpiresIn <= DateTime.Now)
                {
                    var client = new HttpClient();
                    var dict   = new Dictionary <string, string>()
                    {
                        { "client_id", options.MSClientId },
                        { "scope", "offline_access Calendars.Read" },
                        { "grant_type", "refresh_token" },
                        { "refresh_token", config.RefreshToken },
                        { "redirect_uri", options.MSRedirectUri },
                        { "client_secret", options.MSSecret }
                    };
                    var result = await client.PostAsync("https://login.microsoftonline.com/common/oauth2/v2.0/token",
                                                        new FormUrlEncodedContent(dict));

                    if (!result.IsSuccessStatusCode)
                    {
                        throw new CalendarConfigurationException($"Could not redeem refresh token: {result.StatusCode}");
                    }
                    var tokenResponse = await result.Content.ReadAsStringAsync();

                    var tokens = JsonConvert.DeserializeObject <TokenResponse>(tokenResponse);
                    config = await configurationRepository.RefreshTokens(config.Id, tokens);
                }
            }
            finally
            {
                semaphore.Release();
            }
            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", config.AccessToken);
        }
Beispiel #8
0
 private void FillTokens(StoredConfiguration config, TokenResponse tokens)
 {
     config.RefreshToken = tokens.refresh_token;
     config.AccessToken  = tokens.access_token;
     config.ExpiresIn    = DateTime.Now.AddSeconds(tokens.expires_in);
 }
Beispiel #9
0
 public async Task <IAuthenticationProvider> GetByConfig(StoredConfiguration config)
 {
     return(new GraphTokenAuthenticationProvider(configurationRepository, options, config));
 }
 public ICalendarProvider GetProvider(StoredConfiguration config)
 {
     return(new GraphCalendarProvider(graphAuthenticationProviderFactory, config, optionsAccessor));
 }
 public GoogleCalendarColorProvider Get(StoredConfiguration config,
                                        IGoogleCredentialProvider googleCredentialProvider)
 {
     return(new GoogleCalendarColorProvider(_memoryCache,
                                            config, googleCredentialProvider, _logger));
 }
Beispiel #12
0
 public ICalendarProvider GetProvider(StoredConfiguration config)
 {
     return(new GoogleCalendarProvider(config, googleCredentialProvider, options, logger,
                                       _googleCalendarColorProviderFactory.Get(config, googleCredentialProvider)));
 }
 public GraphTokenAuthenticationProvider(IConfigurationRepository configurationRepository, CalendarConfigurationOptions options, StoredConfiguration config)
 {
     this.configurationRepository = configurationRepository;
     this.options = options;
     this.config  = config;
 }