Esempio n. 1
0
        public ActionResult Permissions(string scope)
        {
            // connect with facebook if we have no token
            var token = repository.GetOAuthToken(subdomainid.Value, sessionid.Value.ToString(), OAuthTokenType.FACEBOOK);

            if (token == null)
            {
                //we need to get user to connect with facebook first
                return(Json(JavascriptReturnCodes.NOTOKEN.ToJsonOKData(), JsonRequestBehavior.AllowGet));
            }

            var oauthClient = new FacebookOAuthClient(FacebookApplication.Current)
            {
                RedirectUri = GetFacebookRedirectUri()
            };

            dynamic parameters = new ExpandoObject();

            parameters.scope = scope;
            var state = new CallbackState()
            {
                return_url        = Request.UrlReferrer != null ? Request.UrlReferrer.AbsoluteUri : accountHostname.ToDomainUrl("/dashboard"),
                requestPageTokens = true,
                domain_name       = accountSubdomainName
            };

            parameters.state = OAuthFacebook.Base64UrlEncode(Encoding.UTF8.GetBytes(JsonSerializer.Current.SerializeObject(state)));

            return(Redirect(oauthClient.GetLoginUrl(parameters).AbsoluteUri));
        }
Esempio n. 2
0
        public ActionResult Login(string redirect)
        {
            // try to get from db first
            var oauthClient = new FacebookOAuthClient(FacebookApplication.Current)
            {
                RedirectUri = GetFacebookRedirectUri()
            };

            var relativeUrl = "/login";

            if (!string.IsNullOrEmpty(redirect))
            {
                relativeUrl = string.Concat(relativeUrl, "?redirect=", HttpUtility.UrlEncode(redirect));
            }

            dynamic parameters = new ExpandoObject();
            var     state      = new CallbackState()
            {
                return_url = accountHostname.ToDomainUrl(relativeUrl),
                isLogin    = true
            };

            parameters.state = OAuthFacebook.Base64UrlEncode(Encoding.UTF8.GetBytes(JsonSerializer.Current.SerializeObject(state)));

            return(Redirect(oauthClient.GetLoginUrl(parameters).AbsoluteUri));
        }
Esempio n. 3
0
        public ActionResult Tab(string code, string signed_request)
        {
            var client = new OAuthFacebook(GeneralConstants.FACEBOOK_APP_ID, GeneralConstants.FACEBOOK_API_SECRET,
                                           GeneralConstants.HTTP_SECURE + "/fbapp/tab", "email");

            if (!string.IsNullOrEmpty(code))
            {
                client.AccessTokenGet(code);

                var access_token = client.token;

                // TODO: save token for use later?

                return(Redirect(string.Format("http://www.facebook.com/add.php?api_key={0}&pages=1", GeneralConstants.FACEBOOK_APP_ID)));
            }

            if (!string.IsNullOrEmpty(signed_request))
            {
                if (!client.ValidateSignedRequest(signed_request))
                {
                    throw new NotImplementedException();
                }
                var payload = client.ParseSignedRequest(signed_request);

                var fbpage = repository.GetFacebookPage(payload.page.id).SingleOrDefault();
                if (fbpage != null)
                {
                    var viewModel = new FacebookGalleryViewModel();
                    viewModel.InitGalleryView(fbpage, repository, payload.page.liked);

                    var owner = fbpage.MASTERsubdomain.organisation.users.FirstOrDefault();
                    if (owner != null && owner.FBID == payload.user_id)
                    {
                        viewModel.isOwner = true;
                        viewModel.token   = payload.oauth_token;
                    }

                    return(View("Gallery", viewModel));
                }

                return(View("Configure", new FacebookConfigureViewModel()
                {
                    pageID = payload.page.id,
                    profileID = payload.user_id,
                    signed_request = signed_request
                }));
            }

            throw new NotImplementedException();
        }
Esempio n. 4
0
        public ActionResult GetToken(string perms)
        {
            var oauthClient = new FacebookOAuthClient(FacebookApplication.Current)
            {
                RedirectUri = GetFacebookRedirectUri()
            };

            dynamic parameters = new ExpandoObject();

            parameters.scope = "publish_stream";
            var state = new CallbackState()
            {
                return_url  = accountHostname.ToDomainUrl("/fb/saveToken"),
                isLink      = true,
                domain_name = MASTERdomain.name
            };

            parameters.state = OAuthFacebook.Base64UrlEncode(Encoding.UTF8.GetBytes(JsonSerializer.Current.SerializeObject(state)));

            return(Redirect(oauthClient.GetLoginUrl(parameters).AbsoluteUri));
        }
Esempio n. 5
0
        public ActionResult Register(string name, string plan, string affiliate)
        {
            if (!repository.IsDomainAvailable(name))
            {
                return(Redirect(ErrorHelper.CreateErrorPage(name + " is not available. Please select another name.", Request.UrlReferrer.AbsoluteUri)));
            }

            var oauthClient = new FacebookOAuthClient(FacebookApplication.Current)
            {
                RedirectUri = GetFacebookRedirectUri()
            };

            dynamic parameters = new ExpandoObject();

            // TODO: to be handled separately
            parameters.scope = "email,publish_stream";
            var returnUrl = name.ToTradelrDomainUrl("/login");

            // add csrf_token to prevent cross site forger attacks
            // pass returnUrl as state, so the callback know which page to redirect when the oauth login is successful
            // to make the querystring ?state=value safe, encode the value of state using Base64UrlEncode.
            var state = new CallbackState()
            {
                csrf_token     = Utility.CalculateMD5Hash(Guid.NewGuid().ToString()),
                return_url     = returnUrl,
                domain_name    = name,
                plan_name      = plan,
                isRegistration = true,
                affiliate      = affiliate
            };

            parameters.state = OAuthFacebook.Base64UrlEncode(Encoding.UTF8.GetBytes(JsonSerializer.Current.SerializeObject(state)));
            SetFacebookCsrfToken(state.csrf_token);

            return(Redirect(oauthClient.GetLoginUrl(parameters).AbsoluteUri));
        }
Esempio n. 6
0
        public ActionResult Configure(string pageid, string address, string affiliate, string profileid, string token)
        {
            bool isError = (string.IsNullOrEmpty(pageid) && string.IsNullOrEmpty(profileid)) ||
                           string.IsNullOrEmpty(address);

            Uri storeAddress = null;

            try
            {
                if (address.IndexOf('.') == -1)
                {
                    // user only enter store name
                    address = string.Format("{0}.tradelr.com", address);
                }
                if (!address.StartsWith("http"))
                {
                    // user did not enter http
                    address = string.Format("http://{0}", address);
                }
                storeAddress = new Uri(address);
            }
            catch
            {
                Syslog.Write(new Exception("FB: Unable to parse " + address));
                isError = true;
            }

            if (!isError)
            {
                string subdomain = "";
                if (storeAddress.Host.Split('.').Length > 2)
                {
                    int lastIndex = storeAddress.Host.LastIndexOf(".");
                    int index     = storeAddress.Host.LastIndexOf(".", lastIndex - 1);
                    subdomain = storeAddress.Host.Substring(0, index);
                }
                else
                {
                    return(View("Error", new FacebookPageViewModel
                    {
                        errorMessage = "This is not a valid store address",
                        pageID = pageid
                    }));
                }

                var mastersd = repository.GetSubDomains().SingleOrDefault(x => x.name == subdomain);

                if (mastersd == null)
                {
                    Syslog.Write("New FB subdomain:" + subdomain);
                    // TODO: create new account
                    var client = new OAuthFacebook(GeneralConstants.FACEBOOK_APP_ID, GeneralConstants.FACEBOOK_API_SECRET,
                                                   GeneralConstants.HTTP_SECURE + "/fbapp/tab", "email");

                    if (!client.ValidateSignedRequest(token))
                    {
                        return(View("Error", new FacebookPageViewModel
                        {
                            errorMessage = "There was an error processing your request",
                            pageID = pageid
                        }));
                    }
                    var payload = client.ParseSignedRequest(token);

                    var facebook = new FacebookService(payload.oauth_token);
                    var fb_usr   = facebook.People.GetUser("me");

                    try
                    {
                        var account     = new Account(repository, fb_usr.email, subdomain, AccountPlanType.BASIC, affiliate);
                        var errorString = account.CreateAccountWithFacebookLogin(fb_usr);
                        if (!string.IsNullOrEmpty(errorString))
                        {
                            return(View("Error", new FacebookPageViewModel
                            {
                                errorMessage = errorString,
                                pageID = pageid
                            }));
                        }
                        mastersd = account.mastersubdomain;
                    }
                    catch (Exception ex)
                    {
                        Syslog.Write(ex);
                        return(View("Error", new FacebookPageViewModel
                        {
                            errorMessage = "There was an error processing your request. Your store was not created. Please try again.",
                            pageID = pageid
                        }));
                    }
                }

                // check if there's already an entry, we ignore if there's already an entry
                var existing =
                    repository.GetFacebookPage(pageid).SingleOrDefault(x => x.subdomainid == mastersd.id);

                if (existing == null)
                {
                    existing = new facebookPage {
                        subdomainid = mastersd.id, pageid = pageid
                    };
                    repository.AddFacebookPage(existing);
                }

                var viewmodel = new FacebookGalleryViewModel();
                viewmodel.InitGalleryView(existing, repository, false);

                return(View("Gallery", viewmodel));
            }

            return(View("Error",
                        new FacebookPageViewModel {
                pageID = pageid, errorMessage = "This is not a valid store address"
            }));
        }
Esempio n. 7
0
        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) }));
        }
Esempio n. 8
0
        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"));
        }