Dialog

Facebook

Sep 22nd, 2014
313
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.21 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Net.Http;
  5. using System.Net.Http.Headers;
  6. using System.Text.RegularExpressions;
  7. using System.Threading.Tasks;
  8.  
  9. /*
  10.      * Creator: Dialog
  11.      *
  12.      * Contact:
  13.      * E-mail: Relekka(at)outlook .com
  14.      * XMPP: [email protected]
  15.      *
  16.      * Created: 09.22.2014
  17.      */
  18.  
  19. namespace ConsoleApplication1
  20. {
  21.     /// <summary>
  22.     /// Validates Facebook credentials
  23.     /// </summary>
  24.     public static class Facebook
  25.     {
  26.         private static HttpClient _client;
  27.  
  28.         /// <summary>
  29.         /// Asynchronously tries to sign in to Facebook
  30.         /// </summary>
  31.         /// <param name="creds">The credentials to sign in to. Enter an e-mail address for the username</param>
  32.         /// <returns>A boolean indicating success. False if something went wrong or the credentials are invalid</returns>
  33.         public static async Task<bool> TrySignInAsync(NetworkCredential creds)
  34.         {
  35.             const string signInUrl = "https://www.facebook.com/login.php?login_attempt=1";
  36.             var tokens = await GetTokenAsync();
  37.  
  38.             using (var message = new HttpRequestMessage(HttpMethod.Post, new Uri(signInUrl)))
  39.             {
  40.                 message.Content = new FormUrlEncodedContent(new Dictionary<string, string>
  41.                 {
  42.                     { "lsd", tokens.Item1 },
  43.                     { "email", creds.UserName },
  44.                     { "pass", creds.Password },
  45.                     { "default_persistent", "0" },
  46.                     { "timezone", "-120" },
  47.                     { "lgnrnd", tokens.Item2 },
  48.                     { "lgnjs", UnixTime().ToString() },
  49.                     { "locale", "nl_NL" }
  50.                 });
  51.                 message.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");
  52.  
  53.                 var response = await _client.SendAsync(message);
  54.                 var responseContent = await response.Content.ReadAsStringAsync();
  55.  
  56.                 return responseContent.IndexOf("<input class=\"uiLinkButtonInput\"", StringComparison.Ordinal) != -1;
  57.             }
  58.         }
  59.  
  60.         /// <summary>
  61.         /// Asynchronously gets Facebook's authenticity tokens
  62.         /// </summary>
  63.         /// <returns>A tuple with the lsd token as its first item, and lgnrnd as its second</returns>
  64.         private static async Task<Tuple<string, string>> GetTokenAsync()
  65.         {
  66.             _client = new HttpClient(new HttpClientHandler() { CookieContainer = new CookieContainer() }, true);
  67.             _client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0");
  68.  
  69.             var pageSource = await _client.GetStringAsync(new Uri("https://facebook.com"));
  70.             return ParseTokens(pageSource);
  71.         }
  72.  
  73.         /// <summary>
  74.         /// Parses Facebook tokens from a page source
  75.         /// </summary>
  76.         private static Tuple<string, string> ParseTokens(string pageSource)
  77.         {
  78.             const string lsdPattern = "(\\[\"LSD\",\\[\\]).*?(\"token\").*?(\".*?\")";
  79.             const string lgnrndPattern = ".*?(\"lgnrnd\").*?(value).*?(\".*?\")";
  80.  
  81.             var lsdMatch = Regex.Match(pageSource, lsdPattern);
  82.             var lgnrndMatch = Regex.Match(pageSource, lgnrndPattern);
  83.  
  84.             if (!(lsdMatch.Success && lgnrndMatch.Success))
  85.             {
  86.                 throw new WebException("Could not get tokens.");
  87.             }
  88.  
  89.             var trimChars = new[] { '\\', '"' };
  90.             var lsdToken = lsdMatch.Groups[3].Value.Trim(trimChars);
  91.             var lgnrndToken = lgnrndMatch.Groups[3].Value.Trim(trimChars);
  92.  
  93.             var result = new Tuple<string, string>(lsdToken, lgnrndToken);
  94.             return result;
  95.         }
  96.  
  97.         /// <summary>
  98.         /// Gets the unix epoch time
  99.         /// Credits: Ben Cull @ stackoverflow.com
  100.         /// </summary>
  101.         /// <returns>Unix epoch time in seconds</returns>
  102.         private static long UnixTime()
  103.         {
  104.             var epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
  105.             return Convert.ToInt64((DateTime.Now.ToUniversalTime() - epoch).TotalSeconds);
  106.         }
  107.     }
  108. }
Advertisement
Add Comment
Please, Sign In to add comment