public void AddUpdateFacebookToken(facebook_token ftoken) { var existing = db.facebook_tokens.SingleOrDefault(x => x.pageid == ftoken.pageid && x.subdomainid == ftoken.subdomainid); if (existing != null) { existing.accesstoken = ftoken.accesstoken; } else { db.facebook_tokens.InsertOnSubmit(ftoken); } }
public ActionResult NewAccount(string code, string id, string identifier, PageType pagetype) { var client = new OAuthFacebook(GeneralConstants.FACEBOOK_API_KEY, GeneralConstants.FACEBOOK_API_SECRET, HttpUtility.UrlEncode( string.Format( "{0}/newaccount/{1}?identifier={2}&pagetype={3}", GeneralConstants.FACEBOOK_APP_URL, id, identifier, pagetype)), "read_stream,email,publish_stream,offline_access,manage_pages"); // starting our authorisation process if (string.IsNullOrEmpty(code)) { return(RedirectToAction("Redirect", new{ url = client.AuthorizationLinkGet() })); } if (!client.AccessTokenGet(code)) { return(View("Error", new FacebookViewData { errorMessage = "Unable to obtain permission", pageUrl = pagetype.ToReturnUrl(identifier) })); } // check subdomain is valid id = id.ToLower(); // also check special domain list if (GeneralConstants.SUBDOMAIN_RESTRICTED.Contains(id)) { return(View("Error", new FacebookViewData { errorMessage = "Store address is not available", pageUrl = pagetype.ToReturnUrl(identifier) })); } var mastersubdomain = repository.GetSubDomains().Where(x => x.name == id).SingleOrDefault(); if (mastersubdomain != null) { return(View("Error", new FacebookViewData { errorMessage = "Store address is not available", pageUrl = pagetype.ToReturnUrl(identifier) })); } var facebook = new FacebookService(client.token); var fb_usr = facebook.People.GetUser("me"); if (fb_usr == null) { return(View("Error", new FacebookViewData { errorMessage = "Unable to create account", pageUrl = pagetype.ToReturnUrl(identifier) })); } // verify that email has not been used to register another account if (repository.GetUserByEmail(fb_usr.email).Where(x => (x.role & (int)UserRole.CREATOR) != 0).SingleOrDefault() != null) { Syslog.Write(ErrorLevel.INFORMATION, "Facebook email address in use: " + fb_usr.email); return(View("Error", new FacebookViewData { errorMessage = "Email address is already registered", pageUrl = pagetype.ToReturnUrl(identifier) })); } var usr = new user { role = (int)UserRole.ADMIN, viewid = Crypto.Utility.GetRandomString(), permissions = (int)UserPermission.ADMIN, FBID = fb_usr.id, email = fb_usr.email ?? "", externalProfileUrl = fb_usr.link, firstName = fb_usr.first_name, lastName = fb_usr.last_name, gender = fb_usr.gender, externalProfilePhoto = string.Format("https://graph.facebook.com/{0}/picture?type=large", fb_usr.id) }; // create subdomain entry mastersubdomain = new MASTERsubdomain { flags = 0, name = id, total_outofstock = 0, total_contacts_public = 0, total_contacts_private = 0, total_contacts_staff = 0, total_invoices_sent = 0, total_invoices_received = 0, total_orders_sent = 0, total_orders_received = 0, total_products_mine = 0, accountType = AccountPlanType.ULTIMATE.ToString() }; repository.AddMasterSubdomain(mastersubdomain); // create organisation first var org = new organisation { subdomain = mastersubdomain.id, name = fb_usr.name }; repository.AddOrganisation(org); usr.organisation = org.id; // CREATE DEFAULT STRUCTURES // add default inventory location var loc = new inventoryLocation { name = GeneralConstants.INVENTORY_LOCATION_DEFAULT, subdomain = mastersubdomain.id, lastUpdate = DateTime.UtcNow }; repository.AddInventoryLocation(loc, mastersubdomain.id); // add default shipping profile var shippingProfile = new shippingProfile() { title = "Default", type = ShippingProfileType.FLATRATE.ToString(), subdomainid = mastersubdomain.id }; repository.AddShippingProfile(shippingProfile); // update subdomain entry mastersubdomain.creator = org.id; // create facebookpage to link to subdomain var newEntry = new facebookPage { subdomainid = mastersubdomain.id, pageid = identifier }; repository.AddFacebookPage(newEntry); try { // if user exist then we still need to verify email Random rnd = RandomNumberGenerator.Instance; usr.confirmationCode = rnd.Next(); repository.AddUser(usr); // generate photo new Thread(() => usr.externalProfilePhoto.ReadAndSaveFromUrl(mastersubdomain.id, usr.id, usr.id, PhotoType.PROFILE)).Start(); // add access token var oauthdb = new oauth_token { token_key = client.token, token_secret = "", type = OAuthTokenType.FACEBOOK.ToString(), subdomainid = mastersubdomain.id, appid = usr.id.ToString(), authorised = true }; repository.AddOAuthToken(oauthdb); // obtain any other account tokens var accounts = facebook.Account.GetAccountTokens("me"); if (accounts != null && accounts.data != null) { foreach (var account in accounts.data) { if (account.name != null) { var ftoken = new facebook_token { pageid = account.id, subdomainid = mastersubdomain.id, accesstoken = account.access_token, name = account.name }; repository.AddUpdateFacebookToken(ftoken); } } } repository.Save(); // send confirmation email var viewdata = new ViewDataDictionary() { { "host", id.ToSubdomainUrl() }, { "confirmCode", usr.confirmationCode }, { "email", usr.email } }; EmailHelper.SendEmailNow(EmailViewType.ACCOUNT_CONFIRMATION, viewdata, "New Account Details and Email Verification Link", usr.email, usr.ToFullName(), usr.id); } catch (Exception ex) { Syslog.Write(ex); return(View("Error", new FacebookViewData { errorMessage = "Unable to create account", pageUrl = pagetype.ToReturnUrl(identifier) })); } return(RedirectToAction("Redirect", new { url = pagetype.ToReturnUrl(identifier) })); }
public ActionResult Callback() { var oauthClient = new FacebookOAuthClient(FacebookApplication.Current) { RedirectUri = GetFacebookRedirectUri() }; FacebookOAuthResult oAuthResult; if (oauthClient.TryParseResult(Request.Url, out oAuthResult)) { if (oAuthResult.IsSuccess) { if (!string.IsNullOrWhiteSpace(oAuthResult.Code)) { string returnUrl = ""; string domainName = null; string planName = null; string affiliate = null; var state = new CallbackState(); try { if (!string.IsNullOrWhiteSpace(oAuthResult.State)) { state = (CallbackState)JsonSerializer.Current.DeserializeObject(Encoding.UTF8.GetString(OAuthFacebook.Base64UrlDecode(oAuthResult.State)), typeof(CallbackState)); // TODO: at the moment only check if there is token. Hack Bug // we do this because for logins we are saving token in a separate domain if (!string.IsNullOrEmpty(state.csrf_token) && !ValidateFacebookCsrfToken(state.csrf_token)) { // someone tried to hack the site. return(RedirectToAction("Index", "Error")); } if (!string.IsNullOrEmpty(state.return_url)) { returnUrl = state.return_url; } if (!string.IsNullOrEmpty(state.domain_name)) { domainName = state.domain_name; } if (!string.IsNullOrEmpty(state.plan_name)) { planName = state.plan_name; } if (!string.IsNullOrEmpty(state.affiliate)) { affiliate = state.affiliate; } } } catch (Exception ex) { Syslog.Write(ex); // catch incase user puts his own state, // Base64UrlDecode might throw exception if the value is not properly encoded. return(RedirectToAction("Index", "Error")); } try { var token = (IDictionary <string, object>)oauthClient.ExchangeCodeForAccessToken(oAuthResult.Code); var token_key = (string)token["access_token"]; var token_expires = token.ContainsKey("expires") ? token["expires"].ToString() : ""; if (state.isRegistration && !string.IsNullOrEmpty(domainName)) { var errorMessage = ProcessSuccesfulFacebookRegistrationCallback(token, domainName, planName, affiliate); if (!string.IsNullOrEmpty(errorMessage)) { return(Redirect(ErrorHelper.CreateErrorPage(errorMessage, "/register/" + planName))); } } if (state.isLogin || state.isLink) { var returnUri = new Uri(returnUrl); var queryParameters = HttpUtility.ParseQueryString(returnUri.Query); queryParameters.Add("token", token_key); queryParameters.Add("expires", token_expires); returnUrl = string.Format("{0}://{1}{2}{3}", returnUri.Scheme, returnUri.Host, returnUri.LocalPath, queryParameters.ToQueryString(true)); } if (state.requestPageTokens && !string.IsNullOrEmpty(state.domain_name)) { // obtain any other account tokens var facebook = new FacebookService(token_key); var accounts = facebook.Account.GetAccountTokens("me"); if (accounts != null && accounts.data != null) { var domain = repository.GetSubDomains().SingleOrDefault(x => x.name == state.domain_name); if (domain != null) { foreach (var entry in accounts.data) { if (entry.name != null) { var ftoken = new facebook_token { pageid = entry.id, subdomainid = domain.id, accesstoken = entry.access_token, name = entry.name, category = entry.category, flags = (int)FacebookTokenSettings.NONE }; repository.AddUpdateFacebookToken(ftoken); } } } } } // save any changes repository.Save(); // prevent open redirection attacks. make sure the returnUrl is trusted before redirecting to it if (!string.IsNullOrWhiteSpace(returnUrl) && returnUrl.Contains(GeneralConstants.SUBDOMAIN_HOST)) { return(Redirect(returnUrl)); } } catch (FacebookApiException ex) { // catch incase the user entered dummy code or the code expired. Syslog.Write(ex); } } } else { switch (oAuthResult.ErrorReason) { // permission request denied case "user_denied": return(RedirectToAction("NoAuth", "Error")); default: Syslog.Write(string.Format("Unhandled Facebook OAUTH {0} - {1}", oAuthResult.ErrorReason, oAuthResult.ErrorDescription)); break; } } } return(RedirectToAction("Index", "Error")); }