private void LoadFriendData(int?status) { if (status == null) { status = 0; } dataView.List = true; RegisteredUser ru = registeredUserRepository.Get(this.UserId); dataView.Friends = friendRepository.Search(this.ProxyLoggedUser, string.Empty, (FriendStatus)status, 0); dataView.NewFriendsRequest = ru.FriendsThatInvitedMe.Count; dataView.UserMail = Membership.GetUser().Email; dataView.NewFriend = new NewFriendView(); ViewData["GMailAuthUrl"] = new GoogleProvider().GetAuthorizationURL(); ViewData["LiveAuthUrl"] = new LiveProvider().GetAuthorizationURL(); ViewData["YahooAuthUrl"] = "N/D"; if (Session["NewFriendsAdded"] != null) { TempData["NewFriendsAdded"] = Session["NewFriendsAdded"]; Session["NewFriendsAdded"] = null; } }
public void ParseResult_ErrorJson_Throws() { SearchProvider search = new GoogleProvider(configuration); string json = "{ \"error\": { \"code\": 404, \"message\": \"Requested entity was not found.\", \"errors\": [ { \"message\": \"Requested entity was not found.\", \"domain\": \"global\", \"reason\": \"notFound\" } ], \"status\": \"NOT_FOUND\" }}"; Assert.Throws <ArgumentException>(() => search.ParseResponse(json)); }
public async Task AuthenticateUserThrowsExceptionIfGoogleApiFails() { // Arrange var config = CreateProviderConfig(); var(restClientFactory, restClient) = CreateRestClientAndFactory(); // Arrnage - Calling Google API for token succeeds SetupTokenResultSuccess(restClient, "token", "secret"); // Arrange - Calling Google API fails var response = Substitute.For <IRestResponse <AccessTokenResult> >(); response.IsSuccessful.Returns(false); restClient.ExecuteAsync <AccessTokenResult>(Arg.Any <RestRequest>()).Returns(Task.FromResult(response)); var provider = new GoogleProvider(config, restClientFactory, "url1", "url2"); var http = Substitute.For <HttpRequest>(); http.Query.Returns(new QueryCollection(new Dictionary <string, StringValues> { { "state", new StringValues("TestState") }, { "code", new StringValues("TestCode") }, })); // Act / Assert await Assert.ThrowsAsync <NogginNetCoreAuthException>(() => provider.AuthenticateUser(http, "secret")); }
public void GivenNoCodeAndNoErrorWasReturned_AuthenticateClient_ThrowsAnException() { // Arrange. var googleProvider = new GoogleProvider(new ProviderParams { Key = "aa", Secret = "bb" }); const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "aaa", "bbb" }, { "state", existingState } }; var googleAuthenticationServiceSettings = new GoogleAuthenticationServiceSettings { State = existingState, CallBackUri = new Uri("http://2p1s.com") }; // Act. var result = Assert.Throws <AuthenticationException>( () => googleProvider.AuthenticateClient(googleAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal("No code parameter provided in the response query string from Google.", result.Message); }
public void GivenGoogleReturnedAnError_AuthenticateClient_ThrowsAnException() { // Arrange. var googleProvider = new GoogleProvider(new ProviderParams { Key = "aa", Secret = "bb" }); const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "error", "I dont' always use bayonets. But when I do, I transport them on Aircraft Carriers." }, { "state", existingState } }; var googleAuthenticationServiceSettings = new GoogleAuthenticationServiceSettings { State = existingState, CallBackUri = new Uri("http://2p1s.com") }; // Act. var result = Assert.Throws <AuthenticationException>( () => googleProvider.AuthenticateClient(googleAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal( "Failed to retrieve an authorization code from Google. The error provided is: I dont' always use bayonets. But when I do, I transport them on Aircraft Carriers.", result.Message); }
public void ParseResult_EmptyJson_Throws() { SearchProvider search = new GoogleProvider(configuration); string json = string.Empty; Assert.Throws <ArgumentException>(() => search.ParseResponse(json)); }
protected void lbImportUsers_Click(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(ddlDomains.SelectedValue)) { try { AppsService service = new AppsService(ddlDomains.SelectedValue, UserContext.Current.Organization.GoogleAdminAuthToken); int count = 0; int failed = 0; GoogleProvider.ImportUsers(UserContext.Current.OrganizationId, service, out count, out failed); lbImportUsers.Enabled = false; lbImportUsers.Enabled = false; lbImportUsers.Text = string.Format(CultureInfo.CurrentCulture, Resources.GoogleIntegrationControl_ImportUsers_Result_Text, count - failed, failed); } catch (AppsException a) { lblStep1Error.Text = string.Format(CultureInfo.CurrentCulture, Resources.GoogleIntegrationControl_GoogleAppsError_Text, a.ErrorCode, a.InvalidInput, a.Reason); mvStep1.SetActiveView(vwStep1Error); } catch (Exception ex) { ShowError(ex, lblStep1Error, mvStep1, vwStep1Error); } } else { lblStep1Error.Text = Resources.GoogleIntegrationControl_DomainMisingError_Text; mvStep1.SetActiveView(vwStep1Error); } }
protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); var context = new Bookmarks.Mongo.Data.BookmarksContext(ConnectionString); container.Register <IBookmarksContext>(context); var twitterProvider = new TwitterProvider(new ProviderParams { PublicApiKey = Utils.GetAppSetting("TwitterConsumerKey"), SecretApiKey = Utils.GetAppSetting("TwitterConsumerSecret") }); var facebookProvider = new FacebookProvider(new ProviderParams { PublicApiKey = Utils.GetAppSetting("FBClientId"), SecretApiKey = Utils.GetAppSetting("FBClientSecret") }); var googleProvider = new GoogleProvider(new ProviderParams { PublicApiKey = Utils.GetAppSetting("GoogleConsumerKey"), SecretApiKey = Utils.GetAppSetting("GoogleConsumerSecret") }); var authenticationProviderFactory = new AuthenticationProviderFactory(); try { authenticationProviderFactory.AddProvider(twitterProvider); authenticationProviderFactory.AddProvider(facebookProvider); authenticationProviderFactory.AddProvider(googleProvider); } catch (ReflectionTypeLoadException ex) { var loaderEx = ex.LoaderExceptions; } container.Register <IAuthenticationCallbackProvider>(new SocialAuthenticationCallbackProvider(context)); }
public void GivenExecutingUserInfoWorksButIsMissingSomeRequiredData_AuthenticateClient_ThrowsAnException() { // Arrange. var mockRestResponse = new Mock <IRestResponse <AccessTokenResult> >(); mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK); mockRestResponse.Setup(x => x.Data).Returns(new AccessTokenResult { AccessToken = "aaa", ExpiresIn = 100, IdToken = "What if that sexy girl in that pop up chat really does want to meet people in my area?", TokenType = "overly attached girlfriend" }); var mockRestResponseUserInfo = new Mock <IRestResponse <UserInfoResult> >(); mockRestResponseUserInfo.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK); mockRestResponseUserInfo.Setup(x => x.Data).Returns(new UserInfoResult()); // Missing required info. var mockRestClient = MockRestClient; mockRestClient .Setup(x => x.Execute <AccessTokenResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponse.Object); mockRestClient. Setup(x => x.Execute <UserInfoResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponseUserInfo.Object); var googleProvider = new GoogleProvider(new ProviderParams { Key = "aa", Secret = "bb" }) { RestClientFactory = new RestClientFactory(mockRestClient.Object) }; const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "code", "aaa" }, { "state", existingState } }; var googleAuthenticationServiceSettings = new GoogleAuthenticationServiceSettings { State = existingState, CallBackUri = new Uri("http://2p1s.com") }; // Act. var result = Assert.Throws <AuthenticationException>( () => googleProvider.AuthenticateClient(googleAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal( "We were unable to retrieve the User Id from Google API, the user may have denied the authorization.", result.Message); }
public void GivenExecutingUserInfoThrowsAnException_AuthenticateClient_ThrowsAnException() { // Arrange. var mockRestResponse = new Mock <IRestResponse <AccessTokenResult> >(); mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK); mockRestResponse.Setup(x => x.Data).Returns(new AccessTokenResult { AccessToken = "aaa", ExpiresIn = 100, IdToken = "What if that sexy girl in that pop up chat really does want to meet people in my area?", TokenType = "overly attached girlfriend" }); var mockRestResponseUserInfo = new Mock <IRestResponse <UserInfoResult> >(); mockRestResponseUserInfo.Setup(x => x.StatusCode).Returns(HttpStatusCode.Unauthorized); mockRestResponseUserInfo.Setup(x => x.StatusDescription).Returns("Unauthorized"); var mockRestClient = MockRestClient; mockRestClient .Setup(x => x.Execute <AccessTokenResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponse.Object); mockRestClient. Setup(x => x.Execute <UserInfoResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponseUserInfo.Object); var googleProvider = new GoogleProvider(new ProviderParams { Key = "aa", Secret = "bb" }) { RestClientFactory = new RestClientFactory(mockRestClient.Object) }; const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "code", "aaa" }, { "state", existingState } }; var googleAuthenticationServiceSettings = new GoogleAuthenticationServiceSettings { State = existingState, CallBackUri = new Uri("http://2p1s.com") }; // Act. var result = Assert.Throws <AuthenticationException>( () => googleProvider.AuthenticateClient(googleAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal( "Failed to obtain some UserInfo data from the Google Api OR the the response was not an HTTP Status 200 OK. Response Status: Unauthorized. Response Description: Unauthorized. Error Message: --no error exception--.", result.Message); }
static void Main(string[] args) { var excelProvider = new ExcelProvider(); var words = excelProvider.ReadColumn("C:\\Users\\StephanyHenrique\\Documents\\planilha2.xls"); var googleProvider = new GoogleProvider(); foreach (var word in words) { googleProvider.SaveAudio(word); } }
public void ParseResult_CorrectJson_ReturnsTrue() { SearchProvider search = new GoogleProvider(configuration); string filename = "google.json"; Assembly thisAssembly = Assembly.GetExecutingAssembly(); var reader = new StreamReader(thisAssembly.GetManifestResourceStream(resourcesDir + filename)); string json = reader.ReadToEnd(); var response = search.ParseResponse(json); Assert.IsTrue(response.Any(r => r.Snippet.Contains("Bible", StringComparison.InvariantCultureIgnoreCase))); }
public ActionResult FriendsRequest() { RegisteredUser ru = registeredUserRepository.Get(this.UserId); FriendsData fd = new FriendsData(); fd.List = false; fd.Friends = ru.FriendsThatInvitedMe; ViewData["GMailAuthUrl"] = new GoogleProvider().GetAuthorizationURL(); ViewData["LiveAuthUrl"] = new LiveProvider().GetAuthorizationURL(); ViewData["YahooAuthUrl"] = "N/D"; return(View("Index", fd)); }
public void MakeRequest_CorrectParameters_ReturnsTrue() { SearchProvider search = new GoogleProvider(configuration); string query = "Bible"; int num = 7; string host = "https://www.googleapis.com/customsearch/v1"; string key = UrlEncode(configuration["Google:key"]); string cx = UrlEncode(configuration["Google:cx"]); string expected = $"{host}?q={query}&cx={cx}&key={key}&num={num}"; string url = search.MakeRequest(query, num).Address.AbsoluteUri; Console.WriteLine($"got:\n{url}"); Console.WriteLine($"expected:\n{expected}"); Assert.IsTrue(url == expected); }
protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); var googleProvider = new GoogleProvider(new ProviderParams { PublicApiKey = WebSettings.Settings.GoogleConsumerKey, SecretApiKey = WebSettings.Settings.GoogleConsumerSecret }); googleProvider.AuthenticateRedirectionUrl = new System.Uri("https://accounts.google.com/o/oauth2/v2/auth"); var authenticationProviderFactory = new AuthenticationProviderFactory(); authenticationProviderFactory.AddProvider(googleProvider); container.Register <IAuthenticationCallbackProvider>(new CrossoutAuthenticationCallbackProvider(userRepository)); container.Register <JsonSerializer, CustomJsonSerializer>(); }
protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); // database configuration var factory = new RepositoryFactory(); container.Register(factory.UserRepository); // security configuration var googleProvider = new GoogleProvider(new ProviderParams { PublicApiKey = GoogleClientId, SecretApiKey = GoogleSecret }); var authenticationProviderFactory = new AuthenticationProviderFactory(); authenticationProviderFactory.AddProvider(googleProvider); container.Register<IAuthenticationCallbackProvider>(new GoogleAuthenticationCallbackProvider(factory.UserRepository)); }
protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); var googleProvider = new GoogleProvider(new ProviderParams { PublicApiKey = GlobalConfig.GoogleConsumerKey, SecretApiKey = GlobalConfig.GoogleConsumerSecret }); var authenticationProviderFactory = new AuthenticationProviderFactory(); authenticationProviderFactory.AddProvider(googleProvider); container.Register<IAuthenticationCallbackProvider>(new RusserAuthenticationCallbackProvider()); }
protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); //var twitterProvider = new TwitterProvider(new ProviderParams { PublicApiKey = TwitterConsumerKey, SecretApiKey = TwitterConsumerSecret }); var facebookProvider = new FacebookProvider(new ProviderParams { PublicApiKey = FacebookAppId, SecretApiKey = FacebookAppSecret }); var googleProvider = new GoogleProvider(new ProviderParams { PublicApiKey = GoogleConsumerKey, SecretApiKey = GoogleConsumerSecret }); var authenticationProviderFactory = new AuthenticationProviderFactory(); //authenticationProviderFactory.AddProvider(twitterProvider); authenticationProviderFactory.AddProvider(facebookProvider); authenticationProviderFactory.AddProvider(googleProvider); container.Register<IAuthenticationCallbackProvider>(new MedSetAuthenticationCallbackProvider()); }
public async Task AuthenticateUserReturnsUserInfo() { // Arrange var config = CreateProviderConfig(); var(restClientFactory, restClient) = CreateRestClientAndFactory(); // Arrange - Calling Google API for token SetupTokenResultSuccess(restClient, "token", "secret"); // Arrange - Calling Google for user details var googleResponse = Substitute.For <IRestResponse <UserInfoResult> >(); googleResponse.IsSuccessful.Returns(true); googleResponse.StatusCode.Returns(HttpStatusCode.OK); googleResponse.Data.Returns(new UserInfoResult { Id = "TestId", DisplayName = "RichardG2268", Name = new Name { FamilyName = "Garside", GivenName = "Richard" }, Language = "en-GB", Image = new Image { Url = "hotdang.jpg" } }); restClient.ExecuteAsync <UserInfoResult>(Arg.Any <RestRequest>()).Returns(Task.FromResult(googleResponse)); var provider = new GoogleProvider(config, restClientFactory, "url1", "url2"); var http = Substitute.For <HttpRequest>(); http.Query.Returns(new QueryCollection(new Dictionary <string, StringValues> { { "state", new StringValues("TestState") }, { "code", new StringValues("TestCode") }, })); // Act var authenticatedUser = await provider.AuthenticateUser(http, "secret"); // Assert Assert.Equal("Richard Garside", authenticatedUser.Name); Assert.Equal("RichardG2268", authenticatedUser.UserName); Assert.Equal("hotdang.jpg", authenticatedUser.Picture); }
public async Task GenerateStartRequestDoesNotCallGoogleApi() { // Arrange var config = CreateProviderConfig(); var(restClientFactory, restClient) = CreateRestClientAndFactory(); var provider = new GoogleProvider(config, restClientFactory, "url1", "url2"); var http = Substitute.For <HttpRequest>(); // Act var result = await provider.GenerateStartRequestUrl(http); // Assert await restClient.DidNotReceive().ExecuteAsync <AccessTokenResult>(Arg.Any <IRestRequest>()); }
public void GivenANullCallbackUriWhileTryingToRetrieveAnAccessToken_AuthenticateClient_ThrowsAnException() { // Arrange. var mockRestResponse = new Mock <IRestResponse <AccessTokenResult> >(); mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.BadRequest); mockRestResponse.Setup(x => x.StatusDescription).Returns("Bad Request"); mockRestResponse.Setup(x => x.Content).Returns("{\n \"error\" : \"invalid_request\"\n}"); var mockRestClient = MockRestClient; mockRestClient .Setup(x => x.Execute <AccessTokenResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponse.Object); var googleProvider = new GoogleProvider(new ProviderParams { Key = "aa", Secret = "bb" }) { RestClientFactory = new RestClientFactory(mockRestClient.Object) }; const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "code", "aaa" }, { "state", existingState } }; var googleAuthenticationServiceSettings = new GoogleAuthenticationServiceSettings { State = existingState, CallBackUri = new Uri("http://2p1s.com") }; // Act. var result = Assert.Throws <AuthenticationException>( () => googleProvider.AuthenticateClient(googleAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal( "Failed to obtain an Access Token from Google OR the the response was not an HTTP Status 200 OK. Response Status: BadRequest. Response Description: Bad Request. Error Content: {\n \"error\" : \"invalid_request\"\n}. Error Message: --no error exception--.", result.Message); }
protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); //var twitterProvider = new TwitterProvider(new ProviderParams { PublicApiKey = TwitterConsumerKey, SecretApiKey = TwitterConsumerSecret }); var facebookProvider = new FacebookProvider(new ProviderParams { PublicApiKey = FacebookAppId, SecretApiKey = FacebookAppSecret }); var googleProvider = new GoogleProvider(new ProviderParams { PublicApiKey = GoogleConsumerKey, SecretApiKey = GoogleConsumerSecret }); var authenticationProviderFactory = new AuthenticationProviderFactory(); //authenticationProviderFactory.AddProvider(twitterProvider); authenticationProviderFactory.AddProvider(facebookProvider); authenticationProviderFactory.AddProvider(googleProvider); container.Register <IAuthenticationCallbackProvider>(new MedSetAuthenticationCallbackProvider()); }
public void GivenAnRequestTokenWithMissingParameters_AuthenticateClient_ThrowsAnException() { // Arrange. var mockRestResponse = new Mock <IRestResponse <AccessTokenResult> >(); mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK); mockRestResponse.Setup(x => x.Data).Returns(new AccessTokenResult()); var mockRestClient = MockRestClient; mockRestClient .Setup(x => x.Execute <AccessTokenResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponse.Object); var googleProvider = new GoogleProvider(new ProviderParams { Key = "aa", Secret = "bb" }) { RestClientFactory = new RestClientFactory(mockRestClient.Object) }; const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "code", "aaa" }, { "state", existingState } }; var googleAuthenticationServiceSettings = new GoogleAuthenticationServiceSettings { State = existingState, CallBackUri = new Uri("http://2p1s.com") }; // Act. var result = Assert.Throws <AuthenticationException>( () => googleProvider.AuthenticateClient(googleAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal( "Retrieved a Google Access Token but it doesn't contain one or more of either: access_token, expires_in or token_type.", result.Message); }
public async Task GenerateStartRequestUrlReturnsToken() { // Arrange var config = CreateProviderConfig(); var(restClientFactory, restClient) = CreateRestClientAndFactory(); // Arrange - Calling Google API succeeds var provider = new GoogleProvider(config, restClientFactory, "url1", "url2"); var http = Substitute.For <HttpRequest>(); // Act var result = await provider.GenerateStartRequestUrl(http); // Assert Assert.NotNull(result.url); Assert.NotNull(result.secret); Assert.True(Guid.TryParse(result.secret, out var guidSecret)); }
public void GivenSomeState_RedirectToAuthenticate_ReturnsAUri() { // Arrange. var googleProvider = new GoogleProvider(new ProviderParams { Key = "aa", Secret = "bb" }); // Act. var result = googleProvider.RedirectToAuthenticate(new GoogleAuthenticationServiceSettings { State = "bleh", CallBackUri = new Uri("http://2p1s.com") }); // Assert. Assert.NotNull(result); Assert.Equal( "https://accounts.google.com/o/oauth2/auth?client_id=aa&redirect_uri=http://2p1s.com/&response_type=code&scope=https://www.googleapis.com/auth/userinfo.profile%20https://www.googleapis.com/auth/userinfo.email&state=bleh", result.AbsoluteUri); }
static HomeController() { // For the purpose of this example we just made the service static in // a static constructor, normally you would do this using dependency injection // but for the take of simplicity we added it it here. Please refer // to the Advanced sample for the DI version. Don't use a static constructor // like this in your project, please. :) var facebookProvider = new FacebookProvider(new ProviderParams { Key = FacebookAppId, Secret = FacebookAppSecret }); var twitterProvider = new TwitterProvider(new ProviderParams { Key = TwitterConsumerKey, Secret = TwitterConsumerSecret }); var googleProvider = new GoogleProvider(new ProviderParams { Key = GoogleConsumerKey, Secret = GoogleConsumerSecret }); AuthenticationService = new AuthenticationService(); AuthenticationService.AddProvider(facebookProvider); AuthenticationService.AddProvider(twitterProvider); AuthenticationService.AddProvider(googleProvider); }
public void GivenAnErrorOccuredWhileTryingToRetrieveAnAccessToken_AuthenticateClient_ThrowsAnException() { // Arrange. const string errorMessage = "If God says he was not created by a creator, does that mean: god is an aetheist?"; var mockRestClient = MockRestClient; mockRestClient.Setup(x => x.Execute <AccessTokenResult>(It.IsAny <IRestRequest>())) .Throws(new InvalidOperationException(errorMessage)); var googleProvider = new GoogleProvider(new ProviderParams { Key = "aa", Secret = "bb" }) { RestClientFactory = new RestClientFactory(mockRestClient.Object) }; const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "code", "aaa" }, { "state", existingState } }; var googleAuthenticationServiceSettings = new GoogleAuthenticationServiceSettings { State = existingState, CallBackUri = new Uri("http://2p1s.com") }; // Act. var result = Assert.Throws <AuthenticationException>( () => googleProvider.AuthenticateClient(googleAuthenticationServiceSettings, queryStringParameters)); // Assert. Assert.NotNull(result); Assert.Equal("Failed to retrieve an Access Token from Google.", result.Message); Assert.NotNull(result.InnerException); Assert.Equal(errorMessage, result.InnerException.RecursiveErrorMessages()); }
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (LogOnViaGoogleLink.Visible) { LogOnViaGoogleLink.NavigateUrl = GoogleProvider.GetLoginUrl(this.OrganizationId, this.InstanceId); } bool modernTheme = (FrameworkConfiguration.Current.WebApplication.MasterPage.Theme == MasterPageTheme.Modern); if (this.EnableEmbeddedStyleSheets) { Micajah.Common.Pages.MasterPage.CreatePageHeader(this.Page, this.EnableClientCaching, true, true, modernTheme, modernTheme, false); } else if (!this.EnableClientCaching) { Micajah.Common.Pages.MasterPage.DisableClientCaching(this.Page); } if (TitleLabel != null) { TitleContainer.Visible = (!string.IsNullOrEmpty(TitleLabel.Text)); } ErrorPanel.Visible = (!string.IsNullOrEmpty(ErrorPanel.InnerHtml)); if (modernTheme) { ResourceProvider.RegisterValidatorScriptResource(this.Page); } if (m_MainContainerHeight > 0 && (MainContainer != null)) { MainContainer.Style[HtmlTextWriterStyle.Height] = m_MainContainerHeight.ToString(CultureInfo.InvariantCulture) + "px"; MainContainer.Style[HtmlTextWriterStyle.MarginTop] = (-Convert.ToInt32(m_MainContainerHeight / 2)).ToString(CultureInfo.InvariantCulture) + "px"; } }
public void GivenExecutingRetrieveSomeUserInfo_AuthenticateClient_ReturnsAnAuthenticatedClient() { // Arrange. const string accessToken = "aaa"; const int expiresIn = 100; var mockRestResponse = new Mock <IRestResponse <AccessTokenResult> >(); mockRestResponse.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK); mockRestResponse.Setup(x => x.Data).Returns(new AccessTokenResult { AccessToken = accessToken, ExpiresIn = expiresIn, IdToken = "What if that sexy girl in that pop up chat really does want to meet people in my area?", TokenType = "overly attached girlfriend" }); var userInfoResult = new UserInfoResult { Email = "aaa", FamilyName = "bbb", Gender = "male", GivenName = "ccc", Id = "ddd", Link = "http://2p1s.com", Locale = "en-au", Name = "eee", Picture = "http://2p1s.com/zomg", VerifiedEmail = true }; var mockRestResponseUserInfo = new Mock <IRestResponse <UserInfoResult> >(); mockRestResponseUserInfo.Setup(x => x.StatusCode).Returns(HttpStatusCode.OK); mockRestResponseUserInfo.Setup(x => x.Data).Returns(userInfoResult); var mockRestClient = MockRestClient; mockRestClient .Setup(x => x.Execute <AccessTokenResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponse.Object); mockRestClient. Setup(x => x.Execute <UserInfoResult>(It.IsAny <IRestRequest>())) .Returns(mockRestResponseUserInfo.Object); var googleProvider = new GoogleProvider(new ProviderParams { Key = "aa", Secret = "bb" }) { RestClientFactory = new RestClientFactory(mockRestClient.Object) }; const string existingState = "Oops! - Tasselhoff Burrfoot"; var queryStringParameters = new NameValueCollection { { "code", accessToken }, { "state", existingState } }; var googleAuthenticationServiceSettings = new GoogleAuthenticationServiceSettings { State = existingState, CallBackUri = new Uri("http://2p1s.com") }; // Act. var result = googleProvider.AuthenticateClient(googleAuthenticationServiceSettings, queryStringParameters); // Assert. Assert.NotNull(result); Assert.Equal("google", result.ProviderName); Assert.NotNull(result.AccessToken); Assert.Equal(accessToken, result.AccessToken.PublicToken); Assert.True(DateTime.UtcNow.AddSeconds(expiresIn) >= result.AccessToken.ExpiresOn); Assert.NotNull(result.UserInformation); Assert.Equal(GenderType.Male, result.UserInformation.Gender); Assert.Equal(userInfoResult.Id, result.UserInformation.Id); Assert.Equal(userInfoResult.Locale, result.UserInformation.Locale); Assert.Equal(userInfoResult.Name, result.UserInformation.Name); Assert.Equal(userInfoResult.Picture, result.UserInformation.Picture); Assert.Equal(userInfoResult.GivenName, result.UserInformation.UserName); }
private void CreateNewOrganization() { if (string.Compare((string)Session["NewOrg"], "1", StringComparison.OrdinalIgnoreCase) == 0) { string url = null; UserContext user = UserContext.Current; if (user != null) { if (string.Compare(user.Email, Email.Text, StringComparison.OrdinalIgnoreCase) == 0) { url = LoginProvider.Current.GetLoginUrl(user.Email, true, user.OrganizationId, user.InstanceId, null); Response.Redirect(url); } } url = LoginProvider.Current.GetLoginUrl(); Response.Redirect(url); } else { Instance templateInstance = null; InstanceCollection insts = Micajah.Common.Bll.Providers.InstanceProvider.GetTemplateInstances(); if (insts.Count == 0) { throw new NotImplementedException(Resources.SignupOrganizationControl_NoActiveTemplateInstances); } else { templateInstance = insts[0]; } string howYouHearAboutUs = null; bool isGoogleProviderRequest = GoogleProvider.IsGoogleProviderRequest(this.Request); if (isGoogleProviderRequest) { howYouHearAboutUs = Resources.SignupOrganizationControl_HowYouHearAboutUs_Text; } Guid orgId = OrganizationProvider.InsertOrganization(OrganizationName.Text, null, null , null, null, null, null, null, null, string.Empty, howYouHearAboutUs , templateInstance.TimeZoneId, templateInstance.InstanceId , Email.Text, null, this.UserFirstName, this.UserLastName, null, null, null , OrganizationUrl.Text, this.Request , true); Session["NewOrg"] = "1"; Instance inst = InstanceProvider.GetFirstInstance(orgId); if (isGoogleProviderRequest) { string returnUrl = null; OAuth2Parameters parameters = JsonConvert.DeserializeObject <OAuth2Parameters>(this.OAuth2Parameters); GoogleProvider.ProcessAuthorization(this.Context, ref parameters, ref returnUrl); } string url = LoginProvider.Current.GetLoginUrl(Email.Text, true, orgId, inst.InstanceId, null); Response.Redirect(url); } }
protected void Page_Load(object sender, EventArgs e) { Micajah.Common.Pages.MasterPage.SetPageTitle(this.Page, ActionProvider.PagesAndControls.FindByActionId(ActionProvider.SignUpOrganizationPageActionId)); if (!this.Page.IsPostBack) { this.LoadResources(); ErrorPanel.Visible = false; if (GoogleProvider.IsGoogleProviderRequest(this.Request)) { string returnUrl = null; OAuth2Parameters parameters = null; try { GoogleProvider.ProcessAuthorization(this.Context, ref parameters, ref returnUrl); this.OAuth2Parameters = JsonConvert.SerializeObject(parameters); } catch (System.Security.Authentication.AuthenticationException ex) { ErrorContinueLink.NavigateUrl = returnUrl; ErrorLabel.Text = ex.Message; ErrorPanel.Visible = true; return; } string email = null; string firstName = null; string lastName = null; GoogleProvider.GetUserProfile(parameters.AccessToken, out email, out firstName, out lastName); if (!string.IsNullOrEmpty(email)) { Email.Text = email; Email.ReadOnly = true; } if (!string.IsNullOrEmpty(firstName)) { this.UserFirstName = firstName; } if (!string.IsNullOrEmpty(lastName)) { this.UserLastName = lastName; } } OrganizationUrlRow.Visible = FrameworkConfiguration.Current.WebApplication.CustomUrl.Enabled; OrganizationName.Focus(); Control captchaTextBoxLabel = Captcha.FindControl("CaptchaTextBoxLabel"); if (captchaTextBoxLabel != null) { captchaTextBoxLabel.Visible = false; } } ResourceProvider.RegisterValidatorScriptResource(this.Page); }
private void Authenticate() { string password = Request.QueryString["p"]; string isPersistentString = Request.QueryString["cp"]; string loginName = this.LoginName; bool isPersistent = true; if (isPersistentString != null) { if (!Boolean.TryParse(isPersistentString, out isPersistent)) { isPersistent = false; } } Guid organizationId = this.OrganizationId; Guid instanceId = this.InstanceId; bool isCustomUrlEnabled = FrameworkConfiguration.Current.WebApplication.CustomUrl.Enabled; if (isCustomUrlEnabled) { if (organizationId == Guid.Empty) { string host = Request.Url.Host; if (!CustomUrlProvider.IsDefaultVanityUrl(host)) { CustomUrlProvider.ParseHost(host, ref organizationId, ref instanceId); } } else if (!GoogleProvider.IsGoogleProviderRequest(Request)) { this.VerifyVanityUrl(organizationId, instanceId); } } if (!(string.IsNullOrEmpty(loginName) || string.IsNullOrEmpty(password) || (organizationId == Guid.Empty))) { if (!isCustomUrlEnabled) { LoginProvider loginProvider = new LoginProvider(); loginProvider.SignOut(true, false); } try { LoginProvider.Current.Authenticate(loginName, Support.Decrypt(password), false, isPersistent, organizationId, instanceId); this.RedirectAfterLogOn(); } catch (AuthenticationException ex) { ShowErrorMessage(ex.Message); } } else { if (GoogleProvider.IsGoogleProviderRequest(Request)) { try { string accessToken = GoogleProvider.ProcessAuthorization(this.Context, ref organizationId, ref instanceId); string firstName = null; string lastName = null; GoogleProvider.GetUserProfile(accessToken, out loginName, out firstName, out lastName); } catch (AuthenticationException ex) { ShowErrorMessage(ex.Message); } if (!string.IsNullOrEmpty(loginName)) { m_EmailToLink = loginName; string message = null; try { string domain = GoogleProvider.GetDomain(Request); if (!string.IsNullOrEmpty(domain)) { EmailSuffixProvider.ParseEmailSuffixName(domain, ref organizationId, ref instanceId); } if (LoginProvider.Current.Authenticate(loginName, null, false, true, organizationId, instanceId)) { this.RedirectAfterLogOn(); } } catch (AuthenticationException ex) { message = ex.Message; } if (!string.IsNullOrEmpty(message)) { if (LoginProvider.Current.GetLogin(loginName) == null) { message = string.Format(CultureInfo.InvariantCulture, Resources.UserContext_ErrorMessage_YourAccountIsNotFound, loginName); } } if (!string.IsNullOrEmpty(message)) { this.ShowErrorMessage(message); this.EnableCustomHandling = false; } } } } }
public static void MyClassInitialize(TestContext testContext) { _provider = new GoogleProvider(); }