protected void btnCall_Click(object sender, EventArgs e) { fbr = null; //Make sure previous response is cleared this.clearError(); if (!string.IsNullOrEmpty(user)) //User logged in { try { fbr = fb._graph(txtCall.Text); //Making the actual call if (fbr != null) //valid response { txtRequests.Text = txtRequests.Text + "\n" + txtCall.Text; txtData.Text = fbr.ToString(); } else { txtRequests.Text = txtRequests.Text + "\n" + txtCall.Text; txtData.Text = "No Response"; } } catch (FacebookApiException ex) { user = null; lblError.Text = ex.Message; } } else //Not yet logged in { txtRequests.Text = "Not logged in"; txtData.Text = "Not logged in"; } }
public static void LoginFacebookSuccess(FacebookResponse profile) { App.Current.MainPage = new MainPage(); }
async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e) { using (UserDialogs.Instance.Loading("Iniciando Sesión")) { var authenticator = sender as OAuth2Authenticator; if (authenticator != null) { authenticator.Completed -= OnAuthCompleted; authenticator.Error -= OnAuthError; } User user = null; if (e.IsAuthenticated) { String urlInfo = accountLoggedIn.Equals("Google") ? Constants.UserInfoUrl : "https://graph.facebook.com/me?fields=email"; // If the user is authenticated, request their basic user data from Google // UserInfoUrl = https://www.googleapis.com/oauth2/v2/userinfo var request = new OAuth2Request("GET", new Uri(urlInfo), null, e.Account); var response = await request.GetResponseAsync(); if (response != null) { FacebookResponse userFb = new FacebookResponse(); // Deserialize the data and store it in the account store // The users email address will be used to identify data in SimpleDB string userJson = await response.GetResponseTextAsync(); //user = JsonConvert.DeserializeObject<User>(userJson); if (accountLoggedIn.Equals("Google")) { user = JsonConvert.DeserializeObject <User>(userJson); } else { respuestaPerfil = await GetFacebookProfileAsync(); //userFb = JsonConvert.DeserializeObject<FacebookResponse>(userJson); } if (account != null) { store.Delete(account, Constants.AppName); } await store.SaveAsync(account = e.Account, Constants.AppName); if (accountLoggedIn.Equals("Google")) { RegistrarPersona(user.Email, user.Name); } else { String correo = respuestaPerfil.Email; correo = correo.Replace(@"\\u0040", "@"); //await DisplayAlert("else de fb", correo, "ok"); RegistrarPersona(correo, respuestaPerfil.Name); } //await DisplayAlert("Email address", user.Email+", "+user.Name, "OK"); } } } }
public async Task <string> Index() { //Consuming the given Sample API OriginalFile rootObj = new OriginalFile(); using (var httpClient = new HttpClient()) { using (var response = await httpClient.GetAsync("https://reqres.in/api/users")) { string apiResponse = await response.Content.ReadAsStringAsync(); rootObj = JsonConvert.DeserializeObject <OriginalFile>(apiResponse); } } //Building JSON Object for the Facebook Response var FacebookResponse = new FacebookResponse { messaging_type = "RESPONSE", recipient = new Recipient { id = "{PSID}" }, message = new Message { attachment = new Attachment { type = "template", payload = new Payload { template_type = "generic", elements = new List <Element>() { //Only 1 generic template, chose it to be the third user, with 1 button new Element() { title = rootObj.data[2].first_name, image_url = rootObj.data[2].avatar, subtitle = rootObj.data[2].last_name, default_action = new DefaultAction { type = "web_url", url = "mailto:" + rootObj.data[2].email + "?Subject=Hello", webview_height_ratio = "tall" }, buttons = new List <Button>() { new Button() { type = "web_url", url = "mailto:" + rootObj.data[2].email + "?Subject=Hello", title = "Send Email" } } } } } } } }; //Converting to a JSON object and returning it var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(FacebookResponse); return(jsonString); }
public async Task ShowPosts() { FacebookResponse <string> post = await CrossFacebookClient.Current.QueryDataAsync("me/feed", new string[] { "user_posts" }); var jo = JObject.Parse(post.Data.Replace("(", "[").Replace(@"\U", "\\\\U").Replace(");", "],").Replace(" = ", ":").Replace(";", ",")); ListPostedMessages = new List <PostData>(); for (int i = 0; i < ((JArray)jo["data"]).Count; i++) { { try { Message = jo["data"][i]["message"].ToString(); } catch { Message = ""; } try { Story = jo["data"][i]["story"].ToString(); } catch { Story = ""; } ListPostedMessages.Add(new PostData() { MessagePosted = Message, Story = Story }); } } }
public async Task ShowPosts() { FacebookResponse <string> post = await CrossFacebookClient.Current.QueryDataAsync("me/feed", new string[] { "user_posts" }); var jo = JObject.Parse(post.Data); ListPostedMessages = new List <PostData>(); if (jo.ContainsKey("data")) { { var array = ((JArray)jo["data"]); foreach (var item in array) { { var postData = new PostData(); if (!string.IsNullOrEmpty($"{item["message"]}")) { { postData.MessagePosted = $"{item["message"]}"; } } if (!string.IsNullOrEmpty($"{item["story"]}")) { { postData.Story = $"{item["story"]}"; } } ListPostedMessages.Add(postData); } } } } }
protected void Page_Load(object sender, EventArgs e) { FacebookConfig fbConfig = new FacebookConfig() { appId = "160789593985275", apiSecret = "<secret>" }; //for local debugging and custom persistent store - force domain - should allow cross-domain authentication using a single FB app //copy your authtoken from your published app in your local app. // fbConfig.appDomain = "fbAsp.hylas.be"; /* note: for quick and easy debugging on localhost: 1. create facebook app for local debugging: - App Domains: localhost - Sandbox Mode: enabled (only admins can use app) - Website with Facebook Login: http://localhost:<VS debugger or IIS express port>/Example/ 2. it works! (after a minute or two...) 3. but you should put appId & apiSecrit in your web.config, using a web.config transformation to switch between your debug & release application */ fb = new Facebook(fbConfig); this.initPermissions(); pnlPermissions.Visible = false; if (IsPostBack) { if (txtAccessToken.Text.Length > 0) fb.setAccessToken(txtAccessToken.Text); try { //fb.getUser should only fail when graph is unavailable or respons is corrupt user = fb.getUser(); } catch (Exception ex) { iPanel.Visible = false; lblStatus.Text = "Error communicating with graph servers"; fbURL.NavigateUrl = fb.getLoginUrl(); ViewState["user"] = null; return; } } else { try { user = fb.getUser(); } catch (Exception ex) { iPanel.Visible = false; lblStatus.Text = "Error communicating with graph servers"; fbURL.NavigateUrl = fb.getLoginUrl(); ViewState["user"] = null; return; } if (!string.IsNullOrEmpty(user)) { try { iPanel.Visible = true; txtAccessToken.Text = fb.getAccessToken(); fbr = fb._graph("/me"); txtRequests.Text = "/me"; txtData.Text = fbr.ToString(); //txtUserObect.Text = fbr.ToString(); iPicture.ImageUrl = "https://graph.facebook.com/" + fbr["id"].ToString() + "/picture"; iProfile.Text = fbr["name"].ToString();// fbr["name"].value.ToString(); lblStatus.Text = "Connected"; btnConnect1.Text = "Disconnect"; btnConnect1.CssClass = "btnDisconnect"; fbr = fb._graph("/me/albums"); fbURL.NavigateUrl = fb.getLogoutUrl(); if (fbr.ContainsKey("data")) { for (var i = 0; i < fbr["data"].Count; i++) AlbumList.Items.Add(new ListItem(fbr["data"][i.ToString()]["name"].ToString(), fbr["data"][i.ToString()]["id"].ToString())); //or different way: /*foreach (KeyValuePair<String, FacebookResponse> entry in fbr["data"]) { AlbumList.Items.Add(new ListItem(entry.Value["name"].ToString())); }*/ } while (fbr.ContainsKey("paging") && fbr["paging"].ContainsKey("next")) { fbr = fb._graph(fbr["paging"]["next"].ToString()); if (fbr.ContainsKey("data")) for (var i = 0; i < fbr["data"].Count; i++) AlbumList.Items.Add(new ListItem(fbr["data"][i.ToString()]["name"].ToString(), fbr["data"][i.ToString()]["id"].ToString())); } Session.Remove("fb_connect_attempt") ; } catch (FacebookApiException ex) { //todo: log error //probably session expired: we still have the persistent data: user_id and access_token, but the token is no longer valid //best is just to clear the session/cookie OR auto reconnect txtAccessToken.Text = ""; iPanel.Visible = false; user = null; if (Session["fb_connect_attempt"] == null) { Session["fb_connect_attempt"] = 1; connectToFB(); } } } else { iPanel.Visible = false; lblStatus.Text = "Not Connected"; fbURL.NavigateUrl = fb.getLoginUrl(); ViewState["user"] = null; } } }
public async Task <TokenResponse> LoginFacebook(string urlBase, string servicePrefix, string controller, FacebookResponse profile) { try { var request = JsonConvert.SerializeObject(profile); var content = new StringContent(request, Encoding.UTF8, "application/json"); var client = new HttpClient(); client.BaseAddress = new Uri(urlBase); var url = $"{servicePrefix}{controller}"; var response = await client.PostAsync(url, content); if (!response.IsSuccessStatusCode) { return(null); } var tokenResponse = await GetToken(urlBase, profile.Id, profile.Id); return(tokenResponse); } catch { return(null); } }
private FacebookResponse ParseJSON(string jsonText) { FacebookResponse req = new FacebookResponse(); MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonText)); DataContractJsonSerializer serializer = new DataContractJsonSerializer(req.GetType()); req = serializer.ReadObject(ms) as FacebookResponse; ms.Close(); return req; }
public async Task <TokenResponse> LoginFacebook(string urlBase, string servicePrefix, string controller, FacebookResponse profile) { try { var request = JsonConvert.SerializeObject(profile); var content = new StringContent(request, Encoding.UTF8, "application/json"); var client = new HttpClient(); // client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(tokenType, accessToken); client.BaseAddress = new Uri(urlBase); var url = string.Format("{0}{1}", servicePrefix, controller); var response = await client.PostAsync(url, content); if (!response.IsSuccessStatusCode) { return(null); //return new Response //{ // IsSuccess = false, // Message = response.StatusCode.ToString(), //}; } //var result = await response.Content.ReadAsStringAsync(); //var newRecord = JsonConvert.DeserializeObject<T>(result); var tokenResponse = await GetToken(urlBase, profile.Id, profile.Id); return(tokenResponse); } catch { return(null); } }
public static void LoginFacebookSuccess(FacebookResponse profile) { Current.MainPage = new MasterView(); }
private async void fbBtn_Clicked(object sender, EventArgs e) { FacebookResponse <string> response = await CrossFacebookClient.Current.RequestUserDataAsync(new string[] { "email", "first_name", "gender", "last_name", "birthday" }, new string[] { "email", "user_birthday" }); }
public ActionResult SocialSignIn(string provider = "None") { string recordId = ""; dynamic user = null; //Addtional check in case client not registered properly. //only happens when project throws an exception or restarted. if (!OAuthClientFactory.IsFacebookRegistered) { OAuthClientFactory.RegisterFacebookClient(_sessionContext.CurrentSiteConfig.SocialSettings.FacebookApiKey, _sessionContext.CurrentSiteConfig.SocialSettings.FacebookApiSecret, _sessionContext.CurrentSiteConfig.SocialSettings.FacebookUrl); } if (!OAuthClientFactory.IsGoogleRegistered) { OAuthClientFactory.RegisterGoogleClient(_sessionContext.CurrentSiteConfig.SocialSettings.GooglePlusApiKey, _sessionContext.CurrentSiteConfig.SocialSettings.GooglePlusApiSecret, _sessionContext.CurrentSiteConfig.SocialSettings.GooglePlusUrl); } if (!OAuthClientFactory.IsTwitterRegisterd) { OAuthClientFactory.RegisterTwitterClient(_sessionContext.CurrentSiteConfig.SocialSettings.TwitterApiKey, _sessionContext.CurrentSiteConfig.SocialSettings.TwitterApiSecret, _sessionContext.CurrentSiteConfig.SocialSettings.TwitterUrl); } var response = _socialService.SocialSignIn(provider); if (response != null) { var obj = JObject.Parse(response.JsonResponse); switch (response.OAuthClient) { case OAuthClient.Twitter: { user = new TwitterResponse() { Source = Enum.GetName(typeof(OAuthClient), response.OAuthClient), FullName = Convert.ToString(obj["name"]), UserName = Convert.ToString(obj["screen_name"]), SocialId = Convert.ToString(obj["id"]), Email = Convert.ToString(obj["email"]), Location = Convert.ToString(obj["location"]), FirstName = Convert.ToString(obj["name"]).Split(' ')[0], LastName = Convert.ToString(obj["name"]).Split(' ')[1], }; var siteUser = _customerRepository.GetExistingUser(user.Email); if (siteUser.Result.Count == 0) //user not exits, new user { CustomerModel customer = new CustomerModel() { Email = user.Email, FirstName = user.FirstName, LastName = user.LastName, IsRegistered = false }; var result = _customerRepository.Register(customer); recordId = result.Result.RecordId; user.RecordId = recordId; CloudTableRepository _cloudRepository = new CloudTableRepository(); var table = _cloudRepository.CreateTable("SocialUsers"); _cloudRepository.InsertUser(table, user); //insert entry in azure table } else //existing user { recordId = Convert.ToString(siteUser.Result[0].UserId); } } break; case OAuthClient.Facebook: { user = new FacebookResponse() { Source = Enum.GetName(typeof(OAuthClient), response.OAuthClient), FullName = Convert.ToString(obj["name"]), FirstName = Convert.ToString(obj["first_name"]), LastName = Convert.ToString(obj["last_name"]), SocialId = Convert.ToString(obj["id"]), Email = Convert.ToString(obj["email"]), Gender = Convert.ToString(obj["gender"]), Location = Convert.ToString(obj["location"]), HomeTown = Convert.ToString(obj["hometown"]), DateOfBirth = Convert.ToString(obj["birthday"]) }; var siteUser = _customerRepository.GetExistingUser(user.Email); if (siteUser.Result.Count == 0) //user not exits, new user { CustomerModel customer = new CustomerModel() { Email = user.Email, FirstName = user.FirstName, LastName = user.LastName, Gender = user.Gender, IsRegistered = false }; var result = _customerRepository.Register(customer); recordId = result.Result.RecordId; user.RecordId = recordId; CloudTableRepository _cloudRepository = new CloudTableRepository(); var table = _cloudRepository.CreateTable("SocialUsers"); _cloudRepository.InsertUser(table, user); } else //existing user { recordId = Convert.ToString(siteUser.Result[0].UserId); } } break; case OAuthClient.Google: { user = new GoogleResponse() { Source = Enum.GetName(typeof(OAuthClient), response.OAuthClient), SocialId = Convert.ToString(obj["id"]), FullName = Convert.ToString(obj["name"]), FirstName = Convert.ToString(obj["given_name"]), LastName = Convert.ToString(obj["family_name"]), Email = Convert.ToString(obj["email"]), }; var siteUser = _customerRepository.GetExistingUser(user.Email); if (siteUser.Result.Count == 0) //user not exits, new user { CustomerModel customer = new CustomerModel() { Email = user.Email, FirstName = user.FirstName, LastName = user.LastName, IsRegistered = false }; var result = _customerRepository.Register(customer); recordId = result.Result.RecordId; user.RecordId = recordId; CloudTableRepository _cloudRepository = new CloudTableRepository(); var table = _cloudRepository.CreateTable("SocialUsers"); _cloudRepository.InsertUser(table, user); } else //existing user { recordId = Convert.ToString(siteUser.Result[0].UserId); } } break; default: break; } var results = _authenticationService.SocialLogin(recordId); if (results == null) { return(JsonValidationError()); } else { return(Redirect("/")); } } return(null); }
public IActionResult Like() { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var fb = new FacebookFunctions(); var mails = new Dictionary <string, List <string> >(); var userIds = ( from souscription in _db.Souscriptions where souscription.AppletId == 13 select souscription.UserId ).ToList(); foreach (var id in userIds) { var list = new List <string>(); var userName = ( from users in _db.Users where users.Id == id select users.UserName ).FirstOrDefault(); var token = ( from souscription in _db.Souscriptions where souscription.UserId == id && souscription.AppletId == 13 select souscription.FbToken ).FirstOrDefault(); var pageId = ( from souscription in _db.Souscriptions where souscription.UserId == id && souscription.AppletId == 13 select souscription.FbPageId ).FirstOrDefault(); list.Add(token); list.Add(pageId); mails.Add(userName, list); } foreach (var pair in mails) { HttpWebRequest apiRequest = WebRequest.Create("https://graph.facebook.com//v3.2/" + pair.Value[1] + "/feed") as HttpWebRequest; apiRequest.Headers.Add("Authorization", "Bearer " + pair.Value[0]); string apiResponse = ""; using (HttpWebResponse response = apiRequest.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); apiResponse = reader.ReadToEnd(); } /*End*/ FacebookResponse rootObject = JsonConvert.DeserializeObject <FacebookResponse>(apiResponse); var access_token = pair.Value[0]; fb.likeObject(access_token, rootObject.data[0].id); return(Ok(new { message = "Facebook post liked", status = 200 })); } return(BadRequest(new { message = "Facebook post not liked", status = 400 })); }
private async void BtnFBLogin_Clicked(object sender, System.EventArgs e) { try { EnableDisableActivityIndicator(true); EnableDisableControls(false); FacebookResponse <bool> response = await CrossFacebookClient.Current.LoginAsync(new string[] { "email", "public_profile" }); if (response.Status == FacebookActionStatus.Completed) { FacebookResponse <string> respInfo = await CrossFacebookClient.Current.RequestUserDataAsync( new string[] { "email", "first_name", "gender", "last_name", "birthday" }, new string[] { "email", "user_birthday" } ); if (respInfo.Status == FacebookActionStatus.Completed) { var tokenAccess = CrossFacebookClient.Current.ActiveToken; bool isLogged = await serviceLogin.LoginWithFirebaseFB(tokenAccess); if (isLogged) { using (UserRepository userRepository = new UserRepository()) { var userInBD = await userRepository.GetUserByEmail(serviceLogin.getCurrentUser()); if (userInBD != null) { if (userInBD.UserType.Equals("Driver")) { EnableDisableActivityIndicator(false); EnableDisableControls(true); var whatUser = await ShowModalType(Navigation); await Navigation.PushAsync(new DriverTabbedPage(userInBD, whatUser)); } else { EnableDisableActivityIndicator(false); EnableDisableControls(true); await Navigation.PushAsync(new PassengerTabbedPage(userInBD)); } EnableDisableActivityIndicator(false); EnableDisableControls(true); CleanEntries(); } else { respInfo.Data = respInfo.Data .Replace("first_name", "FirstName") .Replace("last_name", "LastName"); User user = JsonConvert.DeserializeObject <User>(respInfo.Data); user.IsFromSocialNetworks = true; EnableDisableActivityIndicator(false); EnableDisableControls(true); await Navigation.PushAsync(new RegistryPage(user)); } } } else { EnableDisableActivityIndicator(false); EnableDisableControls(true); await DisplayAlert("Alerta", "Failed to login with Facebook", "Ok"); } } else { EnableDisableActivityIndicator(false); EnableDisableControls(true); await DisplayAlert("Alerta", respInfo.Message, "Ok"); } } else { EnableDisableActivityIndicator(false); EnableDisableControls(true); await DisplayAlert("Alerta", response.Message, "Ok"); } } catch (Exception ex) { EnableDisableActivityIndicator(false); EnableDisableControls(true); await DisplayAlert("Error", "An unexpected error has occurred" + ex.Message, "Ok"); } }
private async Task <TokenResponse> ExternalLogin(FacebookResponse fbResult, string deviceToken, OsType osType, string deviceId, string currencyCode) { User user = new User(); Password password; string generatedPassword = fbResult.Id.ToCharArray().Reverse().ToString(); var firstCasePerson = await _repository .Filter <User>(x => x.Email == fbResult.Email && x.VerifiedBy == VerifiedBy.Email).FirstOrDefaultAsync(); var secondCasePerson = await _repository.Filter <User>(x => x.Email == fbResult.Email && x.VerifiedBy == VerifiedBy.Email).Include(p => p.Passwords).FirstOrDefaultAsync(); if (firstCasePerson != null && firstCasePerson.IsBlocked || secondCasePerson != null && secondCasePerson.IsBlocked) { throw new Exception(_optionsBinder.Error().BlockedAccount); } int currencyId = 1; Currency currency = _repository.FilterAsNoTracking <Currency>(c => c.Code == currencyCode).FirstOrDefault(); if (currency != null) { currencyId = currency.Id; } if (firstCasePerson == null) { var photo = await _mediaAccessor.GetPhotoFromSocial(fbResult.Url); generatedPassword = fbResult.Id.ToCharArray().Reverse().ToString(); user = new User { Email = fbResult.Email, FullName = $"{fbResult.First_name} {fbResult.Last_name}", ProfilePhoto = photo, RoleEnum = Role.User, VerifiedBy = VerifiedBy.Email, OsType = osType, UserStatusType = UserStatusType.Active, DateOfBirth = null, IsLocal = false, CurrencyId = currencyId }; _repository.Create(user); password = new Password { UserId = user.Id, LoginProvider = SocialLoginProvider.Facebook, UniqueIdentifier = fbResult.Id, PasswordHash = Utilities.HashPassword(generatedPassword) }; _repository.Create(password); var verified = await _repository.Filter <Verified>(x => x.Email.ToLower() == fbResult.Email.ToLower()).FirstOrDefaultAsync(); if (verified == null) { verified = new Verified { Code = null, Email = fbResult.Email, IsRegistered = true, VerifiedType = VerifiedType.Verify, VerifiedBy = VerifiedBy.Email, IsVerified = true }; } _repository.Create(verified); } else if (secondCasePerson != null) { user = secondCasePerson; } if ((firstCasePerson == null) && (secondCasePerson == null)) { foreach (SubscriptionsType variable in Enum.GetValues(typeof(SubscriptionsType))) { _repository.Create(new PersonSetting { UserId = user.Id, SubscriptionsType = variable }); } _repository.Create(new PersonOtherSetting { UserId = user.Id, AreaUnit = AreaUnit.SquareMeter, Language = Language.English }); } await _repository.SaveChangesAsync(); if (user.VerifiedBy == VerifiedBy.Email) { var html = Utilities.NewUserEmailStyle(user.Email); Utilities.SendEmail(user.Email, "Baitkm", html); } return(await Token(new SocialTokenViewModel { DeviceToken = deviceToken, DeviceId = deviceId, OsType = osType, Password = generatedPassword, Provider = SocialLoginProvider.Facebook, SocialId = fbResult.Id, Email = user.Email, Id = user.Id })); }
public async void FacebookUserProfileAsync(string accessToken) { var client = new HttpClient(); var socialLogInPost = new SocialLogInPost(); // Actual call to Facebooks end point now that we have the token (appending accessToken to URL in constants file) var facebookResponse = client.GetStringAsync(Constant.FacebookUserInfoUrl + accessToken); // makes the call to Facebook and returns True/False var userData = facebookResponse.Result; // returns Facebook email and social ID System.Diagnostics.Debug.WriteLine(facebookResponse); System.Diagnostics.Debug.WriteLine(userData); // Deserializes JSON object from info provided by Facebook FacebookResponse facebookData = JsonConvert.DeserializeObject <FacebookResponse>(userData); socialLogInPost.email = facebookData.email; socialLogInPost.password = ""; socialLogInPost.social_id = facebookData.id; socialLogInPost.signup_platform = "FACEBOOK"; // Create JSON object for Login Endpoint var socialLogInPostSerialized = JsonConvert.SerializeObject(socialLogInPost); var postContent = new StringContent(socialLogInPostSerialized, Encoding.UTF8, "application/json"); System.Diagnostics.Debug.WriteLine(socialLogInPostSerialized); // Call to RDS database with endpoint and JSON data var RDSResponse = await client.PostAsync(Constant.LogInUrl, postContent); // True or False if Parva's endpoint ran preperly. var responseContent = await RDSResponse.Content.ReadAsStringAsync(); // Contains Parva's code containing all the user data including userid System.Diagnostics.Debug.WriteLine(RDSResponse.IsSuccessStatusCode); // Response code is Yes/True if successful from httpclient system.net package System.Diagnostics.Debug.WriteLine(responseContent); // Response JSON that RDS returns if (RDSResponse.IsSuccessStatusCode) { if (responseContent != null) { // Do I don't have the email in RDS if (responseContent.Contains(Constant.EmailNotFound)) { var signUp = await DisplayAlert("Message", "It looks like you don't have a MTYD account. Please sign up!", "OK", "Cancel"); if (signUp) { // HERE YOU NEED TO SUBSTITUTE MY SOCIAL SIGN UP PAGE WITH MTYD SOCIAL SIGN UP // NOTE THAT THIS SOCIAL SIGN UP PAGE NEEDS A CONSTRUCTOR LIKE THE FOLLOWING ONE // SocialSignUp(string socialId, string firstName, string lastName, string emailAddress, string accessToken, string refreshToken, string platform) Application.Current.MainPage = new CarlosSocialSignUp(facebookData.id, facebookData.name, "", facebookData.email, accessToken, accessToken, "FACEBOOK"); // need to write new statment here ... } } // if Response content contains 200 if (responseContent.Contains(Constant.AutheticatedSuccesful)) { var data = JsonConvert.DeserializeObject <SuccessfulSocialLogIn>(responseContent); Application.Current.Properties["user_id"] = data.result[0].customer_uid; // converts RDS data into appication data. UpdateTokensPost updateTokensPost = new UpdateTokensPost(); updateTokensPost.uid = data.result[0].customer_uid; updateTokensPost.mobile_access_token = accessToken; updateTokensPost.mobile_refresh_token = accessToken; // only get access token from Facebook so we store the data again var updateTokensPostSerializedObject = JsonConvert.SerializeObject(updateTokensPost); var updateTokensContent = new StringContent(updateTokensPostSerializedObject, Encoding.UTF8, "application/json"); var updateTokensResponse = await client.PostAsync(Constant.UpdateTokensUrl, updateTokensContent); // This calls the database and returns True or False var updateTokenResponseContent = await updateTokensResponse.Content.ReadAsStringAsync(); System.Diagnostics.Debug.WriteLine(updateTokenResponseContent); if (updateTokensResponse.IsSuccessStatusCode) { DateTime today = DateTime.Now; DateTime expDate = today.AddDays(Constant.days); // Internal assignment - not from the database Application.Current.Properties["time_stamp"] = expDate; Application.Current.Properties["platform"] = "FACEBOOK"; // Application.Current.MainPage = new SubscriptionPage(); Application.Current.MainPage = new NavigationPage(new SubscriptionPage()); // THIS IS HOW YOU CAN ACCESS YOUR USER ID FROM THE APP //string userID = (string)Application.Current.Properties["user_id"]; //printing id for testing //System.Diagnostics.Debug.WriteLine("user ID after success: " + userID); } else { await DisplayAlert("Oops", "We are facing some problems with our internal system. We weren't able to update your credentials", "OK"); } } // Wrong Platform message if (responseContent.Contains(Constant.ErrorPlatform)) { var RDSCode = JsonConvert.DeserializeObject <RDSLogInMessage>(responseContent); await DisplayAlert("Message", RDSCode.message, "OK"); } // Wrong LOGIN method message if (responseContent.Contains(Constant.ErrorUserDirectLogIn)) { await DisplayAlert("Oops!", "You have an existing MTYD account. Please use direct login", "OK"); } } } }
public async Task <IHttpActionResult> LoginFacebook(FacebookResponse profile) { try { var user = await db.Users.Where(u => u.Email == profile.Id).FirstOrDefaultAsync(); if (user == null) { user = new User { Email = profile.Id, FavoriteTeamId = 1, FirstName = profile.FirstName, LastName = profile.LastName, NickName = profile.Name.Length > 20 ? profile.Name.Substring(0, 20) : profile.Name, Picture = profile.Picture.Data.Url, Points = 0, UserTypeId = 2, }; db.Users.Add(user); CreateUserASP(profile.Id, "User", profile.Id); } else { user.FirstName = profile.FirstName; user.LastName = profile.LastName; user.Picture = profile.Picture.Data.Url; db.Entry(user).State = EntityState.Modified; } await db.SaveChangesAsync(); if (user.GroupUsers.Count == 0) { await AddUserToGroup(user.UserId); } return(Ok(true)); } catch (DbEntityValidationException e) { var message = string.Empty; foreach (var eve in e.EntityValidationErrors) { message = string.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { message += string.Format("\n- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } return(BadRequest(message)); } catch (Exception ex) { return(BadRequest(ex.Message)); } }
public static async Task NavigateToProfile(FacebookResponse profile) { if (profile == null) { mainViewModel.Login.SetStatusControl(true, true, false, 0); //await dialogService.ShowMessage( //"Error", //"the facebook response is not available, try later...!!!", //"Accept"); navigationService.SetMainPage("LoginPage"); // Application.Current.MainPage = new NavigationPage(new LoginPage()); return; } var token = await apiService.LoginFacebook( MethodsHelper.GetUrlAPI(), "/api", "/Users/LoginFacebook", profile); if (token == null) { mainViewModel.Login.SetStatusControl(true, true, false, 0); await dialogService.ShowMessage( "Error", "Login with facebook is not available, try later...!!!", "Accept"); // Application.Current.MainPage = new NavigationPage(new LoginPage()); navigationService.SetMainPage("LoginPage"); return; } // Get data of the user var response = await apiService.Get <UserDataResponse>( MethodsHelper.GetUrlAPI(), "/api/Users", "/GetServicesVzLaUSerByEmail", string.Format( "/?email={0}", token.UserName), token.TokenType, token.AccessToken); if (!response.IsSuccess) { mainViewModel.Login.SetStatusControl(true, true, false, 0); await dialogService.ShowMessage( "Error", response.Message, "Accept"); navigationService.SetMainPage("LoginPage"); return; } // Load values of the UserData LoadOfValueUserData( (UserDataResponse)response.Result, mainViewModel); // Load value to token mainViewModel.Token = token; // Gets an instance of the CantvViewModel mainViewModel.Cantv = new CantvViewModel(); // Set the MainPage to MasterPage navigationService.SetMainPage("MasterPage"); }
// This function evaluates direct user's userType based on role and whether or not // their profile was updated succesfully. (Overloading) //async Task<UserTypeEvaluation> EvaluateUserType(string role, string password) //{ // UserTypeEvaluation userType = new UserTypeEvaluation(); // try // { // if (role == "CUSTOMER" || role == "ADMIN") // { // userType.role = "CUSTOMER"; // userType.statusCode = true; // } // else if (role == "GUEST") // { // var didProfileUpdatedSucessfully = await UpdateUserProfile(password); // if (didProfileUpdatedSucessfully) // { // userType.role = "CUSTOMER"; // userType.statusCode = true; // } // else // { // userType.role = "GUEST"; // userType.statusCode = false; // } // } // } // catch // { // } // return userType; //} // This function evaluates social media user's userType based on role and whether or not // their profile was updated succesfully. (Overloading) //async Task<UserTypeEvaluation> EvaluateUserType(string role, string mobile_access_token, string mobile_refresh_token, string social_id, string platform) //{ // UserTypeEvaluation userType = new UserTypeEvaluation(); // try // { // if (role == "CUSTOMER" || role == "ADMIN") // { // userType.role = "CUSTOMER"; // userType.statusCode = true; // } // else if (role == "GUEST") // { // var didProfileUpdatedSucessfully = await UpdateUserProfile(mobile_access_token, mobile_refresh_token, social_id, platform); // if (didProfileUpdatedSucessfully) // { // userType.role = "CUSTOMER"; // userType.statusCode = true; // } // else // { // userType.role = "GUEST"; // userType.statusCode = false; // } // } // } // catch // { // } // return userType; //} // This function updates direct user's role from GUEST to CUSTOMER. (Overloading) //async Task<bool> UpdateUserProfile(string password) //{ // bool result = false; // try // { // var clientSignUp = new SignUp(); // var content = clientSignUp.UpdateDirectUser(user, password); // result = await SignUp.SignUpNewUser(content); // } // catch // { // Debug.Write("ERROR UPDATING DIRECT USER'S PROFILE FROM GUEST TO CUSTOMER"); // } // return result; //} // This function updates social media user's role from GUEST to CUSTOMER. (Overloading) //async Task<bool> UpdateUserProfile(string mobile_access_token, string mobile_refresh_token, string social_id, string platform) //{ // bool result = false; // try // { // var clientSignUp = new SignUp(); // var content = clientSignUp.UpdateSocialUser(user, mobile_access_token, mobile_refresh_token, social_id, platform); // result = await SignUp.SignUpNewUser(content); // } // catch // { // Debug.Write("ERROR UPDATING SOCIAL MEDIA USER'S PROFILE FROM GUEST TO CUSTOMER"); // } // return result; //} // EVALUATION FUNTIONS FOR DIRECT AND SOCIAL MEDIA ____________________ // NOTIFICATION FUNCTION ______________________________________________ // This function send GUID to database. //async Task<bool> SetUserRemoteNotification() //{ // bool result = false; // try // { // deviceId = Preferences.Get("guid", null); // if (deviceId != null) // { // var client = new HttpClient(); // NotificationPost notificationPost = new NotificationPost(); // notificationPost.uid = user.getUserID(); // notificationPost.guid = deviceId.Substring(5); // user.setUserDeviceID(deviceId.Substring(5)); // notificationPost.notification = "TRUE"; // var notificationSerializedObject = JsonConvert.SerializeObject(notificationPost); // var notificationContent = new StringContent(notificationSerializedObject, Encoding.UTF8, "application/json"); // var clientResponse = await client.PostAsync(Constant.NotificationsUrl, notificationContent); // if (clientResponse.IsSuccessStatusCode) // { // result = true; // Debug.WriteLine("GUID WAS WRITTEN SUCCESFULLY WERE SET SUCESSFULLY"); // } // else // { // Debug.WriteLine("ERROR SETTING GUID FOR NOTIFICATIONS"); // } // } // } // catch // { // } // return result; //} // NOTIFICATION FUNCTION ______________________________________________ // SOCIAL MEDIA VERIFICATION FUNCTION__________________________________ // This function verifies if credentails exist and whether or not user is // authenticated by our system. (Overloading) public async Task <string> VerifyUserCredentials(string accessToken = "", string refreshToken = "", AuthenticatorCompletedEventArgs googleAccount = null, AppleAccount appleCredentials = null, string platform = "") { var isUserVerified = ""; try { string _accessToken = accessToken; string _refreshToken = refreshToken; var client = new HttpClient(); var socialLogInPost = new SocialLogInPost(); var googleData = new GoogleResponse(); var facebookData = new FacebookResponse(); if (platform == "GOOGLE") { var request = new OAuth2Request("GET", new Uri(Constant.GoogleUserInfoUrl), null, googleAccount.Account); var GoogleResponse = await request.GetResponseAsync(); var googelUserData = GoogleResponse.GetResponseText(); googleData = JsonConvert.DeserializeObject <GoogleResponse>(googelUserData); socialLogInPost.email = googleData.email; socialLogInPost.social_id = googleData.id; //Debug.WriteLine("IMAGE: " + googleData.picture); //user.setUserImage(googleData.picture); _accessToken = accessToken; _refreshToken = refreshToken; } else if (platform == "FACEBOOK") { var facebookResponse = client.GetStringAsync(Constant.FacebookUserInfoUrl + accessToken); var facebookUserData = facebookResponse.Result; Debug.WriteLine("FACEBOOK DATA: " + facebookUserData); facebookData = JsonConvert.DeserializeObject <FacebookResponse>(facebookUserData); socialLogInPost.email = facebookData.email; socialLogInPost.social_id = facebookData.id; _accessToken = accessToken; _refreshToken = refreshToken; } else if (platform == "APPLE") { socialLogInPost.email = appleCredentials.Email; socialLogInPost.social_id = appleCredentials.UserId; _accessToken = appleCredentials.Token; _refreshToken = appleCredentials.Token; } socialLogInPost.password = ""; socialLogInPost.signup_platform = platform; var socialLogInPostSerialized = JsonConvert.SerializeObject(socialLogInPost); var postContent = new StringContent(socialLogInPostSerialized, Encoding.UTF8, "application/json"); var RDSResponse = await client.PostAsync(Constant.LogInUrl, postContent); var responseContent = await RDSResponse.Content.ReadAsStringAsync(); var authetication = JsonConvert.DeserializeObject <RDSAuthentication>(responseContent); if (RDSResponse.IsSuccessStatusCode) { if (responseContent != null) { if (authetication.code.ToString() == Constant.EmailNotFound) { // need to sign up userToSignUp = new SignUpAccount(); if (platform == "GOOGLE") { userToSignUp.socialID = googleData.id; userToSignUp.email = googleData.email; userToSignUp.firstName = googleData.given_name; userToSignUp.lastName = googleData.family_name; userToSignUp.accessToken = _accessToken; userToSignUp.refreshToken = _refreshToken; userToSignUp.platform = platform; } else if (platform == "FACEBOOK") { userToSignUp.socialID = facebookData.id; userToSignUp.email = facebookData.email; userToSignUp.firstName = facebookData.name; userToSignUp.accessToken = _accessToken; userToSignUp.refreshToken = _refreshToken; userToSignUp.platform = platform; } else if (platform == "APPLE") { userToSignUp.socialID = appleCredentials.UserId; userToSignUp.email = appleCredentials.Email; userToSignUp.firstName = appleCredentials.Name; userToSignUp.accessToken = _accessToken; userToSignUp.refreshToken = _refreshToken; userToSignUp.platform = platform; } isUserVerified = "USER NEEDS TO SIGN UP"; } if (authetication.code.ToString() == Constant.AutheticatedSuccesful) { try { DateTime today = DateTime.Now; DateTime expDate = today.AddDays(Constant.days); user = new User(); user.id = authetication.result[0].driver_uid; user.sessionTime = expDate; user.platform = platform; user.email = ""; user.socialId = ""; user.route_id = ""; var statusUpdatingTokens = await UpdateAccessRefreshToken(user.id, accessToken, refreshToken); isUserVerified = EvaluteUserUpdates(statusUpdatingTokens); SaveUser(user); } catch (Exception second) { Debug.WriteLine(second.Message); } } if (authetication.code.ToString() == Constant.ErrorPlatform) { //var RDSCode = JsonConvert.DeserializeObject<RDSLogInMessage>(responseContent); isUserVerified = "WRONG SOCIAL MEDIA TO SIGN IN"; } if (authetication.code.ToString() == Constant.ErrorUserDirectLogIn) { isUserVerified = "SIGN IN DIRECTLY"; } } } } catch (Exception errorVerifyUserCredentials) { //var client = new Diagnostic(); //client.parseException(errorVerifyUserCredentials.ToString(), user); Debug.WriteLine("ERROR IN 'errorVerifyUserCredentials' FUNCTION"); isUserVerified = "ERROR"; } return(isUserVerified); }
public async void FillPrincipalData() { FacebookResponse <bool> resp = await CrossFacebookClient.Current.LoginAsync(new string[] { "email", "public_profile", "user_friends" }); attrs = await CrossFacebookClient.Current.RequestUserDataAsync ( new string[] { "id", "name", "picture", "cover", "friends" }, new string[] { } ); Profile = new FaceBookData() { FullName = attrs.Data["name"].ToString(), Cover = new UriImageSource { Uri = new System.Uri(Utilities.JsonConvert(attrs.Data["cover"].ToString(), "source")) }, Picture = new UriImageSource { Uri = new System.Uri(Utilities.JsonConvert(attrs.Data["picture"].ToString(), "url", "data")) } }; await ShowPosts(); await App.Navigation.PushAsync(new MyProfilePage(Profile, ListPostedMessages)); }
public async Task <string> UserVerification(AuthenticatorCompletedEventArgs user = null, AppleAccount appleCredentials = null, string platform = "") { string result = ""; try { var client = new HttpClient(); var socialLogInPost = new SocialLogInPost(); var googleData = new GoogleResponse(); var facebookData = new FacebookResponse(); var localTimeZone = TimeZoneInfo.Local; var _accessToken = ""; var _refreshToken = ""; socialLogInPost.time_zone = localTimeZone.Id; if (platform == "GOOGLE") { var request = new OAuth2Request("GET", new Uri(AppConstants.GoogleUserInfoUrl), null, user.Account); var GoogleResponse = await request.GetResponseAsync(); var googelUserData = GoogleResponse.GetResponseText(); googleData = JsonConvert.DeserializeObject <GoogleResponse>(googelUserData); socialLogInPost.email = googleData.email; socialLogInPost.social_id = googleData.id; socialLogInPost.mobile_access_token = user.Account.Properties["access_token"]; socialLogInPost.mobile_refresh_token = user.Account.Properties["refresh_token"]; socialLogInPost.user_first_name = googleData.given_name; socialLogInPost.user_last_name = googleData.family_name; } else if (platform == "FACEBOOK") { var facebookResponse = client.GetStringAsync(AppConstants.FacebookUserInfoUrl + user.Account.Properties["access_token"]); var facebookUserData = facebookResponse.Result; facebookData = JsonConvert.DeserializeObject <FacebookResponse>(facebookUserData); socialLogInPost.email = facebookData.email; socialLogInPost.social_id = facebookData.id; socialLogInPost.mobile_access_token = user.Account.Properties["access_token"]; socialLogInPost.mobile_refresh_token = user.Account.Properties["access_token"]; socialLogInPost.user_first_name = facebookData.name; socialLogInPost.user_last_name = ""; } else if (platform == "APPLE") { socialLogInPost.email = appleCredentials.Email; socialLogInPost.social_id = appleCredentials.UserId; socialLogInPost.mobile_access_token = appleCredentials.Token; socialLogInPost.mobile_refresh_token = appleCredentials.Token; socialLogInPost.user_first_name = appleCredentials.Name == null ? "" : appleCredentials.Name; socialLogInPost.user_last_name = ""; } socialLogInPost.signup_platform = platform; _accessToken = socialLogInPost.mobile_access_token; _refreshToken = socialLogInPost.mobile_refresh_token; var socialLogInPostSerialized = JsonConvert.SerializeObject(socialLogInPost); var postContent = new StringContent(socialLogInPostSerialized, Encoding.UTF8, "application/json"); var RDSResponse = await client.PostAsync(AppConstants.BaseUrl + AppConstants.login, postContent); //var RDSResponse = await client.PostAsync(AppConstants.BaseUrl + AppConstants.UserIdFromEmailUrl, postContent); var responseContent = await RDSResponse.Content.ReadAsStringAsync(); Debug.WriteLine(responseContent); var authetication = JsonConvert.DeserializeObject <SuccessfulSocialLogIn>(responseContent); var session = JsonConvert.DeserializeObject <Session>(responseContent); if (RDSResponse.IsSuccessStatusCode) { if (responseContent != null) { if (authetication.code.ToString() == AppConstants.EmailNotFound) { // Missing a Oops message you don't have an account //Application.Current.MainPage = new LogInPage(); result = "EMAIL WAS NOT FOUND"; return(result); } if (authetication.code.ToString() == AppConstants.AutheticatedSuccesful) { Debug.WriteLine("USER AUTHENTICATED"); DateTime today = DateTime.Now; DateTime expDate = today.AddDays(AppConstants.days); MainPage.account = SetAccount(); MainPage.account.userID = session.result[0].user_unique_id; MainPage.account.sessionTime = expDate; MainPage.account.accessToken = _accessToken; MainPage.account.refreshToken = _refreshToken; MainPage.account.platform = platform; MainPage.account.isGoalsActive = true; if (platform == "GOOGLE") { MainPage.account.isCalendarActive = true; } var notificationStatus = await SetUserRemoteNotification(MainPage.account.userID); if (notificationStatus) { result = "USER SIGNED IN SUCCESSFULLY AND DEVICE ID WAS REGISTERED SUCCESSFULLY"; } else { result = "USER SIGNED IN SUCCESSFULLY AND DEVICE ID WAS NOT REGISTERED SUCCESSFULLY"; } SaveUser(MainPage.account); } if (authetication.code.ToString() == AppConstants.ErrorPlatform) { result = "SIGN IN WITH THE CORRECT VIA SOCIAL MEDIA ACCOUNT"; } } } return(result); } catch (Exception UserVerificationIssue) { Debug.WriteLine("ERROR IN 'UserVerification' FUNCTION: " + UserVerificationIssue.Message); result = "SOMETHING FAILED IN THE USER VERIFICATION METHOD"; } return(result); }