public bool AuthenticateForSignUp(System.Web.HttpContext context, out Me me, out string accessToken) { me = null; accessToken = ""; string code = context.Request.QueryString["code"]; string url; WebClient webClient = new WebClient(); // If this is a return of a Facebook result then check is an error has orrured string log = ""; if (context.Request.QueryString["error_reason"] != null) log += "error_reason" + context.Request.QueryString["error_reason"] + ";"; if (context.Request.QueryString["error"] != null) log += "error" + context.Request.QueryString["error"] + ";"; if (context.Request.QueryString["error_description"] != null) log += "error_description" + context.Request.QueryString["error_description"] + ";"; if (!String.IsNullOrEmpty(log)) { Exception exception = new Exception(log); Logger.Instance.Write(LogLevel.Error, exception, log); throw exception; } // No code given means initialize Facebook authentication. Redirect this page to Facebook with neccesery parameters if (String.IsNullOrEmpty(code)) { url = FACEBOOK_OAUTH_DIALOG; url += "?client_id=" + ConfigurationManager.AppSettings["Facebook.App.Id"]; //GetConfiguration("facebook.app_id"); url += "&redirect_uri=" + HttpUtility.UrlEncode(context.Request.Url.AbsoluteUri); url += "&scope=email,publish_stream,manage_pages"; url += "&state=" + context.Session.SessionID; context.Response.Redirect(url, true); //return; } // When code is given then Facebook authentication went without errors. if (context.Session.SessionID == context.Request.QueryString["state"]) { url = FACEBOOK_OAUTH_ACCESS; url += "?client_id=" + ConfigurationManager.AppSettings["Facebook.App.Id"]; //GetConfiguration("facebook.app_id"); url += "&redirect_uri=" + HttpUtility.UrlEncode(context.Request.Url.AbsoluteUri.Replace(context.Request.Url.Query, "")); url += "&client_secret=" + ConfigurationManager.AppSettings["Facebook.App.Secret"]; //GetConfiguration("facebook.app_secret"); url += "&code=" + code; string oAuthAccessResult = webClient.DownloadString(url); Logger.Instance.Write(LogLevel.Debug, "Facebook authentication result: " + oAuthAccessResult, oAuthAccessResult); DateTime expires = DateTime.Now.AddMinutes(1); int expiresIndex = oAuthAccessResult.IndexOf("&expires="); if (expiresIndex == -1) { expiresIndex = oAuthAccessResult.Length; } else { string expiresStr = oAuthAccessResult.Substring(expiresIndex + 9, oAuthAccessResult.Length - expiresIndex - 9); int expiresInSec = int.Parse(expiresStr); expires = DateTime.Now.AddSeconds(expiresInSec); } accessToken = oAuthAccessResult.Substring(oAuthAccessResult.IndexOf("access_token=") + 13, expiresIndex - 13); me = GetMe(accessToken); if (me == null) { Logger.Instance.Write(LogLevel.Error, "Cannot verify the Facebook account", new object[] { accessToken }); throw new Exception("Cannot verify the Facebook account"); } var _client = new FacebookClient(accessToken); dynamic _me = _client.Get("me"); firstName = _me.first_name; lastName = _me.last_name; email = _me.email; using (Database db = new MySqlDatabase()) { isEmailExist = db.isEmailAlreadyRegistered(email); } if (string.IsNullOrEmpty(email) || isEmailExist == true) return false; //fbAuthentication.Persist(me, accessToken, expires); } return true; }
//private static IOAuth1ServiceProvider<ITwitter> twitterProvider = null; //public static bool TwitterAuth(HttpContext context, out OAuthToken accessToken, out string oauthVerifier, out TwitterProfile me) //{ // //TrackProtect.Twitter.AuthenticationService authentication = new TrackProtect.Twitter.AuthenticationService(); // accessToken = null; // oauthVerifier = null; // me = null; // //OAuthToken requestToken; // //if (!authentication.TryAuthentication(out requestToken, out oauthVerifier)) // //{ // // authentication.Authenticate(context); // // return false; // //} // //authentication.Authorize(context, out me, out accessToken, out oauthVerifier); // return true; //} //public static bool TwitterAuthorize(out TwitterProfile profile) //{ // profile = null; // string key = GetConfiguration("twitter.app_id"); // string secret = GetConfiguration("twitter.app_secret"); // string twitterTarget = "/social/twitter.aspx"; // StringBuilder sb = new StringBuilder(); // sb.Append(HttpContext.Current.Request.Url.Scheme); // sb.Append("://"); // sb.Append(HttpContext.Current.Request.Url.Authority); // sb.Append(twitterTarget); // twitterTarget = sb.ToString(); // twitterProvider = new TwitterServiceProvider(key, secret); // NameValueCollection par = new NameValueCollection(); // par.Add("force_login", "true"); // OAuthToken requestToken = twitterProvider.OAuthOperations.FetchRequestTokenAsync(twitterTarget, par).Result; // using (Database db = new MySqlDatabase()) // { // ClientInfo ci = db.GetClientInfo(Util.UserId); // db.UpdateSocialCredential(ci.ClientId, SocialConnector.Twitter, "requesttoken.value", requestToken.Value); // db.UpdateSocialCredential(ci.ClientId, SocialConnector.Twitter, "requesttoken.secret", requestToken.Secret); // } // //OAuthToken accessToken = twitterProvider.OAuthOperations.ExchangeForAccessTokenAsync(requestToken, new NameValueCollection()); // //ITwitter twitter = twitterProvider.GetApi(accessToken.Value, accessToken.Secret); // //TwitterProfile prof = twitter.UserOperations.GetUserProfileAsync().Result; // return true; //} //public static void TwitterPublish(string text) //{ // OAuthToken requestToken = TwitterGetRequestToken(); // if (requestToken == null) // { // //TODO: TwitterAuthorize(); // requestToken = TwitterGetRequestToken(); // } // if (requestToken == null) // return; // Can't authorize, can't tweet // string key = GetConfiguration("twitter.app_id"); // string secret = GetConfiguration("twitter.app_secret"); // twitterProvider = new TwitterServiceProvider(key, secret); // HttpContext.Current.Session["TwitterRequestToken"] = requestToken; // HttpContext.Current.Session["TwitterTweet"] = text; // HttpContext.Current.Response.Redirect(twitterProvider.OAuthOperations.BuildAuthenticateUrl(requestToken.Value, null)); //} //public static void TwitterCallback() //{ // string oauth_verifier; // using (Database db = new MySqlDatabase()) // { // ClientInfo ci = db.GetClientInfo(Util.UserId); // oauth_verifier = db.GetSocialCredential(ci.ClientId, SocialConnector.Twitter, "oauth_verifier"); // } // if (string.IsNullOrEmpty(oauth_verifier)) // return; // string key = GetConfiguration("twitter.app_id"); // string secret = GetConfiguration("twitter.app_secret"); // twitterProvider = new TwitterServiceProvider(key, secret); // OAuthToken requestToken = HttpContext.Current.Session["TwitterRequestToken"] as OAuthToken; // AuthorizedRequestToken authorizedRequestToken = new AuthorizedRequestToken(requestToken, oauth_verifier); // OAuthToken token = twitterProvider.OAuthOperations.ExchangeForAccessTokenAsync(authorizedRequestToken, null).Result; // HttpContext.Current.Session["TwitterAccessToken"] = token; // ITwitter twitterClient = twitterProvider.GetApi(token.Value, token.Secret); // //TwitterProfile profile = twitterClient.UserOperations.GetUserProfileAsync().Result; // string tweet = HttpContext.Current.Session["TwitterTweet"] as string; // twitterClient.TimelineOperations.UpdateStatusAsync(tweet); //} //public static void TwitterComplete() //{ //} //private static OAuthToken TwitterGetRequestToken() //{ // string tokenValue = null, tokenSecret = null; // using (Database db = new MySqlDatabase()) // { // ClientInfo ci = db.GetClientInfo(Util.UserId); // tokenValue = db.GetSocialCredential(ci.ClientId, SocialConnector.Twitter, "requesttoken.value"); // tokenSecret = db.GetSocialCredential(ci.ClientId, SocialConnector.Twitter, "requesttoken.secret"); // } // if (string.IsNullOrEmpty(tokenValue) || string.IsNullOrEmpty(tokenSecret)) // return null; // return new OAuthToken(tokenValue, tokenSecret); //} /// <summary> /// Authenticate with Facebook. When not logged in or never set app authorisation the page will be redirected to Facebook. /// </summary> /// <param name="context">Http Context</param> /// <param name="accessToken">Access token</param> /// <param name="me">The user's information</param> /// <returns>True if succeed, false if not</returns> public static bool FacebookAuth(HttpContext context, out string accessToken, out Me me) { AuthenticationService authentication = new AuthenticationService(); me = null; accessToken = ""; if (!authentication.TryAuthenticate(out me, out accessToken)) { authentication.Authenticate(context, out me, out accessToken); if (me == null) { Logger.Instance.Write(LogLevel.Warning, "Cannot authenticate with facebook", new object[] { accessToken }); return false; } } return true; }
private bool isEmailAccessible(Me me) { MeData medata = null; try { WebClient webClient = new WebClient(); string rawResult = webClient.DownloadString(String.Format("https://graph.facebook.com/{0}?fields=first_name,last_name,email", me.Id)); MeData result = JsonConvert.DeserializeObject<MeData>(rawResult); // http://james.newtonking.com/projects/json-net.aspx medata = result; if (string.IsNullOrEmpty(medata.email)) return false; } catch (Exception ex) { Log.Instance.Write(LogLevel.Error, ex); } return true; }
/// <summary> /// Authenticate on Facebook through a aspx page. /// </summary> /// <param name="context">Http context to the login page</param> /// <param name="me">Me info</param> /// <param name="accessToken">Access token</param> public void Authenticate(System.Web.HttpContext context, out Me me, out string accessToken) { me = null; accessToken = ""; string code = context.Request.QueryString["code"]; string url; WebClient webClient = new WebClient(); // If this is a return of a Facebook result then check is an error has orrured string log = ""; if (context.Request.QueryString["error_reason"] != null) log += "error_reason" + context.Request.QueryString["error_reason"] + ";"; if (context.Request.QueryString["error"] != null) log += "error" + context.Request.QueryString["error"] + ";"; if (context.Request.QueryString["error_description"] != null) log += "error_description" + context.Request.QueryString["error_description"] + ";"; if (!String.IsNullOrEmpty(log)) { Exception exception = new Exception(log); Logger.Instance.Write(LogLevel.Error, exception, log); throw exception; } // No code given means initialize Facebook authentication. Redirect this page to Facebook with neccesery parameters if (String.IsNullOrEmpty(code)) { url = FACEBOOK_OAUTH_DIALOG; url += "?client_id=" + ConfigurationManager.AppSettings["Facebook.App.Id"]; //GetConfiguration("facebook.app_id"); url += "&redirect_uri=" + HttpUtility.UrlEncode(context.Request.Url.AbsoluteUri); url += "&scope=publish_stream,manage_pages,publish_actions,read_friendlists,manage_friendlists"; url += "&state=" + context.Session.SessionID; context.Response.Redirect(url, true); return; } // When code is given then Facebook authentication went without errors. if (context.Session.SessionID == context.Request.QueryString["state"]) { url = FACEBOOK_OAUTH_ACCESS; url += "?client_id=" + ConfigurationManager.AppSettings["Facebook.App.Id"]; //GetConfiguration("facebook.app_id"); url += "&redirect_uri=" + HttpUtility.UrlEncode(context.Request.Url.AbsoluteUri.Replace(context.Request.Url.Query, "")); url += "&client_secret=" + ConfigurationManager.AppSettings["Facebook.App.Secret"]; //GetConfiguration("facebook.app_secret"); url += "&code=" + code; string oAuthAccessResult = webClient.DownloadString(url); Logger.Instance.Write(LogLevel.Debug, "Facebook authentication result: " + oAuthAccessResult, oAuthAccessResult); DateTime expires = DateTime.Now.AddHours(1); int expiresIndex = oAuthAccessResult.IndexOf("&expires="); if (expiresIndex == -1) { expiresIndex = oAuthAccessResult.Length; } else { string expiresStr = oAuthAccessResult.Substring(expiresIndex + 9, oAuthAccessResult.Length - expiresIndex - 9); int expiresInSec = int.Parse(expiresStr); expires = DateTime.Now.AddSeconds(expiresInSec); } accessToken = oAuthAccessResult.Substring(oAuthAccessResult.IndexOf("access_token=") + 13, expiresIndex - 13); accessToken = getLongLivedAccessToken(accessToken); expires = DateTime.Now.AddDays(59); me = GetMe(accessToken); if (me == null) { Logger.Instance.Write(LogLevel.Error, "Cannot verify the Facebook account", new object[] { accessToken }); throw new Exception("Cannot verify the Facebook account"); } Persist(me, accessToken, expires); } }
/// <summary> /// Authenticate with social credentials from database. Also validates at Facebook. /// </summary> /// <param name="me">Me info</param> /// <param name="accessToken">Access token</param> /// <returns>True if authenticated, false if not.</returns> public bool TryAuthenticate(out Me me, out string accessToken) { if (_clientInfo == null) GetUser(); me = null; accessToken = ""; using (Database db = new MySqlDatabase()) { accessToken = db.GetSocialCredential(_clientInfo.ClientId, SocialConnector.Facebook, "accesstoken"); if (String.IsNullOrEmpty(accessToken)) return false; string expiresRaw = db.GetSocialCredential(_clientInfo.ClientId, SocialConnector.Facebook, "accesstokenexpires"); if (String.IsNullOrEmpty(expiresRaw)) return false; DateTime expires = DateTime.MinValue; if (!DateTime.TryParse(expiresRaw, out expires)) return false; if (expires < DateTime.Now) return false; me = GetMe(accessToken); if (me == null) return false; } return true; }
public void PersistForAdmin(Me me, string accessToken, DateTime expires) { using (Database db = new MySqlDatabase()) { string fbid = me.Id; string fbname = me.Name; db.saveAdminFBCred(fbid, fbname, accessToken, expires); IDictionary<string, string> pagesAlreadyInDB = db.getAlreadyStoredPageInfo(); IList<TrackProtect.Facebook.Page> pageList = new List<TrackProtect.Facebook.Page>(); if (pagesAlreadyInDB != null) if (pagesAlreadyInDB.Count > 0) { pageList = getFacebookPageList(accessToken); foreach (TrackProtect.Facebook.Page pg in pageList) { bool exist = false; foreach (var dict in pagesAlreadyInDB) { if (pg.PageID == dict.Value) { exist = true; break; } } if (exist == false) db.saveAdminFBPages(pg.PageName, pg.PageID, pg.AccessToken); } return; } pageList = getFacebookPageList(accessToken); foreach (TrackProtect.Facebook.Page pg in pageList) { db.saveAdminFBPages(pg.PageName, pg.PageID, pg.AccessToken); } } }
/// <summary> /// Save Facebook data to the database /// </summary> /// <param name="me">Me info</param> /// <param name="accessToken">Access token</param> /// <param name="expires">Experiation of the access token</param> public void Persist(Me me, string accessToken, DateTime expires) { if (_clientInfo == null) GetUser(); using (Database db = new MySqlDatabase()) { db.UpdateSocialCredential(_clientInfo.ClientId, SocialConnector.Facebook, "facebookid", me.Id); db.UpdateSocialCredential(_clientInfo.ClientId, SocialConnector.Facebook, "accesstoken", accessToken); db.UpdateSocialCredential(_clientInfo.ClientId, SocialConnector.Facebook, "accesstokenexpires", expires.ToString("o")); string facebookId = me.Name; _clientInfo.FacebookId = facebookId; db.RegisterClientInfo( _clientInfo.LastName, _clientInfo.FirstName, _clientInfo.AddressLine1, _clientInfo.AddressLine2, _clientInfo.ZipCode, _clientInfo.State, _clientInfo.City, _clientInfo.Country, _clientInfo.Language, _clientInfo.Telephone, _clientInfo.Cellular, _clientInfo.CompanyName, _clientInfo.UserId, _clientInfo.AccountOwner, _clientInfo.BumaCode, _clientInfo.SenaCode, _clientInfo.IsrcCode, _clientInfo.TwitterId, _clientInfo.FacebookId, _clientInfo.SoundCloudId, _clientInfo.SoniallId, _clientInfo.OwnerKind, _clientInfo.CreditCardNr, _clientInfo.CreditCardCvv, _clientInfo.EmailReceipt, _clientInfo.Referer, _clientInfo.Gender, _clientInfo.Birthdate, _clientInfo.stagename); } }