public void CanGetAccessTokenValidInDb()
        {
            var restClient = new Mock <IRestClient>();
            var externalTokenRepository = new LocalRepository <ExternalToken>();
            var serverTime    = new Mock <IServerTime>();
            var jsonConverter = new Mock <IJsonConverter>();

            var api = new GoogleAuthentication(restClient.Object,
                                               externalTokenRepository,
                                               serverTime.Object,
                                               jsonConverter.Object);

            var now = new DateTime(2014, 12, 17, 10, 0, 0);

            serverTime.Setup(st => st.RequestStarted).Returns(now);
            var validAccessToken = new ExternalToken
            {
                AccessToken    = "AccessToken",
                ExpirationDate = now.AddHours(1),
                Type           = "Google_Access_Token"
            };

            externalTokenRepository.Add(validAccessToken);
            var token = api.GetAccessToken();

            Assert.AreEqual("AccessToken", token.AccessToken);
            Assert.AreEqual("Google_Access_Token", token.Type);
            Assert.AreEqual(11, token.ExpirationDate.Hour);
        }
        private void GoogleLogIn(object sender, EventArgs e)
        {
            googleAuth       = new GoogleAuthentication();
            mgoogleApiClient = googleAuth.GoogleLogin(this, this, this, this);
            var signInIntent = Auth.GoogleSignInApi.GetSignInIntent(mgoogleApiClient);

            StartActivityForResult(signInIntent, SIGN_IN_ID);
        }
        public async Task <ActionResult> Index()
        {
            GoogleAuthentication youtubeAuthen  = new GoogleAuthentication();
            CalendarService      googlecalender = new CalendarService(await youtubeAuthen.GetInitializer());
            var re = googlecalender.Events.List(db.Users.Find(User.Identity.GetUserId()).Email).Execute();

            return(View(re.Items));
        }
Exemple #4
0
 public TransactionController(ILeadRepository repo, IOperationRepository operation, IOptions <UrlOptions> options, IMapper mapper)
 {
     _repo           = repo;
     _restClient     = new RestClient(options.Value.TransactionStoreAPIUrl);
     _authentication = new GoogleAuthentication();
     _mapper         = mapper;
     _operation      = operation;
 }
 public AuthCallbackController(AccessCodeStore accessCodeStore, TextParser textParser,
                               ITelegramBotClient telegramBotClient, ILogger logger, GoogleAuthentication googleAuthentication)
 {
     _accessCodeStore      = accessCodeStore;
     _textParser           = textParser;
     _telegramBotClient    = telegramBotClient;
     _logger               = logger;
     _googleAuthentication = googleAuthentication;
 }
        public async Task <IActionResult> AuthenticateGoogle(GoogleAuthentication googleAuth)
        {
            var validPayload = await GoogleJsonWebSignature.ValidateAsync(googleAuth.id_token);

            if (validPayload != null)
            {
                if (validPayload.EmailVerified)
                {
                    string email   = validPayload.Email;
                    string fam     = validPayload.FamilyName;
                    string given   = validPayload.GivenName;
                    string profile = validPayload.Picture;

                    var user = await _userRepository.GetUser(email);

                    if (user == null)
                    {
                        user = new User()
                        {
                            Email     = email,
                            FirstName = given,
                            LastName  = fam,
                            AllowEmailNotifications = true,
                            UsesGoogleAuth          = true,
                        };
                        if (!string.IsNullOrEmpty(profile))
                        {
                            user.ProfileImageUrl = profile;
                        }
                        await _userRepository.InsertUser(user);
                    }
                    else if (!user.UsesGoogleAuth)
                    {
                        user.UsesGoogleAuth = true;

                        if (!string.IsNullOrEmpty(profile) && string.IsNullOrEmpty(user.ProfileImageUrl))
                        {
                            user.ProfileImageUrl = profile;
                        }

                        await _userRepository.UpdateUser(user);
                    }

                    Response.SendNewToken(await _authenticationService.IssueJwtToUser(user.Id));
                    return(Ok());
                }
                else
                {
                    return(Forbid());
                }
            }
            else
            {
                return(Forbid());
            }
        }
        public void CanConstruct()
        {
            var restClient = new Mock <IRestClient>();
            var externalTokenRepository = new Mock <IRepository <ExternalToken> >();
            var serverTime    = new Mock <IServerTime>();
            var jsonConverter = new Mock <IJsonConverter>();

            var api = new GoogleAuthentication(restClient.Object,
                                               externalTokenRepository.Object,
                                               serverTime.Object,
                                               jsonConverter.Object);
        }
        public void CanGetRefreshToken()
        {
            var restClient = new Mock <IRestClient>();
            var externalTokenRepository = new LocalRepository <ExternalToken>();
            var serverTime    = new Mock <IServerTime>();
            var jsonConverter = new Mock <IJsonConverter>();

            var api = new GoogleAuthentication(restClient.Object,
                                               externalTokenRepository,
                                               serverTime.Object,
                                               jsonConverter.Object);

            var now = new DateTime(2014, 12, 17, 10, 0, 0);

            serverTime.Setup(st => st.RequestStarted).Returns(now);

            var restResponse = new RestResponse();

            restResponse.Content = "{\"access_token\" : \"AccessToken\", \"token_type\" : \"Bearer\", \"expires_in\" : 3600, \"refresh_token\" : \"RefreshToken\"}";
            restClient.Setup(rc => rc.Execute(It.IsAny <RestRequest>()))
            .Returns(restResponse);

            var googleApiTokenResponse = new GoogleApiTokenResponse
            {
                access_token  = "AccessToken",
                expires_in    = 3600,
                token_type    = "Bearer",
                refresh_token = "RefreshToken",
            };

            jsonConverter.Setup(
                jc =>
                jc.Deserilize <GoogleApiTokenResponse>(
                    "{\"access_token\" : \"AccessToken\", \"token_type\" : \"Bearer\", \"expires_in\" : 3600, \"refresh_token\" : \"RefreshToken\"}"))
            .Returns(googleApiTokenResponse);

            var token = api.GetRefreshToken("code", "redirectUrl");

            Assert.AreEqual(2, externalTokenRepository.All().Count());

            Assert.AreEqual("RefreshToken", token.AccessToken);
            Assert.AreEqual("Google_Refresh_Token", token.Type);
            Assert.AreEqual(2114, token.ExpirationDate.Year);

            var hasValidTokenInDb = externalTokenRepository.Any(t => t.Type == "Google_Access_Token" && t.ExpirationDate > now);

            Assert.AreEqual(true, hasValidTokenInDb);
            Assert.AreEqual("AccessToken", externalTokenRepository.Single(t => t.Type == "Google_Access_Token" && t.ExpirationDate > now).AccessToken);
            Assert.AreEqual("Google_Access_Token", externalTokenRepository.Single(t => t.Type == "Google_Access_Token" && t.ExpirationDate > now).Type);
            Assert.AreEqual(11, externalTokenRepository.Single(t => t.Type == "Google_Access_Token" && t.ExpirationDate > now).ExpirationDate.Hour);
        }
        public async Task <ActionResult> GoogleSignInAsync(GoogleAccount account)
        {
            try
            {
                var oauth  = new GoogleAuthentication(this.Tenant);
                var result = await oauth.AuthenticateAsync(account, this.RemoteUser).ConfigureAwait(false);

                return(await this.OnAuthenticatedAsync(result).ConfigureAwait(true));
            }
            catch (NpgsqlException)
            {
                return(this.AccessDenied());
            }
        }
        public async Task <ActionResult> GoogleSignInAsync(GoogleAccount account)
        {
            try
            {
                var oauth  = new GoogleAuthentication();
                var result = await oauth.AuthenticateAsync(account, this.RemoteUser);

                return(OnAuthenticated(result));
            }
            catch (NpgsqlException)
            {
                return(this.AccessDenied());
            }
        }
        public async Task <ActionResult> GoogleSignInAsync(GoogleAccount account)
        {
            try
            {
                GoogleAuthentication oauth  = new GoogleAuthentication();
                LoginResult          result =
                    await oauth.AuthenticateAsync(account, this.RemoteUser);

                return(OnAuthenticated(result));
            }
            catch (NpgsqlException)
            {
                return(Json("Access is denied."));
            }
        }
Exemple #12
0
        public void SaveProvider_SavesProvider_GoogleLoadsCorectly()
        {
            //Arrange
            AuthenticationProvider provider        = AuthenticationProvider.Google;
            GoogleAuthentication   authentication  = new GoogleAuthentication();
            SettingsManager        settingsManager = new SettingsManager();

            //Act
            settingsManager.SaveProvider(provider);

            //Assert
            Assert.AreEqual(settingsManager.LoadProvider(), provider.ToString());

            //Cleanup
            settingsManager.DeleteProvider();
        }
        public void CanGetAuthenticationUrl()
        {
            var restClient = new Mock <IRestClient>();
            var externalTokenRepository = new Mock <IRepository <ExternalToken> >();
            var serverTime    = new Mock <IServerTime>();
            var jsonConverter = new Mock <IJsonConverter>();

            var api = new GoogleAuthentication(restClient.Object,
                                               externalTokenRepository.Object,
                                               serverTime.Object,
                                               jsonConverter.Object);

            var url = api.GetAuthorizationCodeUrl("redirectUrl");

            Assert.AreEqual("https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fanalytics.readonly&redirect_uri=redirectUrl&response_type=code&client_id=&access_type=offline", url);
        }
Exemple #14
0
        private async Task <GoogleUser> DoTest(string userId, string adminId)
        {
            var googleUser = new GoogleUser()
            {
                Id = userId
            };
            var googleUserString     = JsonConvert.SerializeObject(googleUser);
            var googleAuthentication = new GoogleAuthentication(
                new RestConnectorBuilder()
                .WithResult(googleUserString)
                .Build(),
                new OptionBuilder()
                .WithAuthentication(adminId, "this is a very well kept secret. Bla blabla. I will find you and I will hug you!")
                .Build());
            var result = await googleAuthentication.Login("token");

            return(result);
        }
        public void CanGetNewAccessTokenIfNotValidInDbOrForcedForNew()
        {
            var restClient = new Mock <IRestClient>();
            var externalTokenRepository = new LocalRepository <ExternalToken>();
            var serverTime    = new Mock <IServerTime>();
            var jsonConverter = new Mock <IJsonConverter>();

            var api = new GoogleAuthentication(restClient.Object,
                                               externalTokenRepository,
                                               serverTime.Object,
                                               jsonConverter.Object);

            var now = new DateTime(2014, 12, 17, 10, 0, 0);

            serverTime.Setup(st => st.RequestStarted).Returns(now);
            var validRefreshToken = new ExternalToken
            {
                AccessToken    = "RefreshToken",
                ExpirationDate = now.AddYears(100),
                Type           = "Google_Refresh_Token"
            };

            var inValidAccessToken = new ExternalToken
            {
                AccessToken    = "AccessToken",
                ExpirationDate = now.AddHours(-2),
                Type           = "Google_Access_Token"
            };

            externalTokenRepository.Add(validRefreshToken);
            externalTokenRepository.Add(inValidAccessToken);

            var restResponse = new RestResponse();

            restResponse.Content = "{ \"access_token\" : \"NewAccessToken\", \"token_type\" : \"Bearer\", \"expires_in\" : 3600}";
            restClient.Setup(rc => rc.Execute(It.IsAny <RestRequest>()))
            .Returns(restResponse);

            var googleApiTokenResponse = new GoogleApiTokenResponse
            {
                access_token = "NewAccessToken",
                expires_in   = 3600,
                token_type   = "Bearer"
            };

            jsonConverter.Setup(
                jc =>
                jc.Deserilize <GoogleApiTokenResponse>(
                    "{ \"access_token\" : \"NewAccessToken\", \"token_type\" : \"Bearer\", \"expires_in\" : 3600}"))
            .Returns(googleApiTokenResponse);

            var hasValidTokenInDb = externalTokenRepository.Any(t => t.Type == "Google_Access_Token" && t.ExpirationDate > now);

            Assert.AreEqual(false, hasValidTokenInDb);

            var token = api.GetAccessToken();

            var gotNewValidToken = externalTokenRepository.Any(t => t.Type == "Google_Access_Token" && t.ExpirationDate > now);

            Assert.AreEqual(true, gotNewValidToken);

            Assert.AreEqual("NewAccessToken", token.AccessToken);
            Assert.AreEqual("Google_Access_Token", token.Type);
            Assert.AreEqual(11, token.ExpirationDate.Hour);
        }
Exemple #16
0
 public void UpdateAuth(GoogleAuthentication auth)
 {
     PicasaService = new PicasaService(auth.RequestFactory.ApplicationName);
     PicasaService.RequestFactory = auth.RequestFactory;
 }
Exemple #17
0
 public GooglePhotosService(GoogleAuthentication auth)
 {
     Auth = auth;
     auth.AddReceiver(this);
 }