/// <summary>
        /// gets oauth token for domain admin
        /// </summary>
        /// <returns></returns>
        public ActionResult GetToken()
        {
            var client = new OAuthClient(OAuthTokenType.TRADEME,
                                         OAuthClient.OAUTH_TRADEME_CONSUMER_KEY,
                                         OAuthClient.OAUTH_TRADEME_CONSUMER_SECRET,
                                         TradeMe.RestBase.CallbackUrl,
                                         "HMAC-SHA1",
                                         "MyTradeMeRead,MyTradeMeWrite");

            if (!client.GetRequestToken())
            {
                return(Redirect("/Error"));
            }

            var oauthdb = new oauth_token
            {
                token_key    = client.oauth_token,
                token_secret = client.oauth_secret,
                type         = OAuthTokenType.TRADEME.ToString(),
                subdomainid  = subdomainid.Value,
                appid        = sessionid.Value.ToString(),
                authorised   = false
            };

            repository.AddOAuthToken(oauthdb);

            return(Redirect(client.authorize_url));
        }
Exemple #2
0
        public ActionResult SaveToken(string token, string expires)
        {
            var facebook = new FacebookService(token);
            var fbUsr    = facebook.People.GetUser("me");

            var usr = repository.GetUserById(sessionid.Value, subdomainid.Value);

            usr.FBID = fbUsr.id;

            DateTime expiresOn = !string.IsNullOrEmpty(expires) ? DateTime.UtcNow.AddSeconds(Convert.ToDouble(expires)) : DateTime.MaxValue;
            var      oauthdb   = new oauth_token
            {
                token_key    = token,
                token_secret = "",
                type         = OAuthTokenType.FACEBOOK.ToString(),
                subdomainid  = subdomainid.Value,
                appid        = sessionid.Value.ToString(),
                authorised   = true,
                expires      = expiresOn
            };

            repository.AddOAuthToken(oauthdb);

            repository.Save();

            return(Redirect("/dashboard/networks#facebook"));
        }
Exemple #3
0
        public ActionResult Yahoo(long subdomainid, long appid)
        {
            var client = new OAuthClient(OAuthTokenType.YAHOO, OAuthClient.OAUTH_YAHOO_CONSUMER_KEY,
                                         OAuthClient.OAUTH_YAHOO_CONSUMER_SECRET, "secure".ToTradelrDomainUrl("/oauth/yahoo"), "plaintext");

            if (!client.GetRequestToken())
            {
                return(Redirect("/Error"));
            }

            var oauthdb = new oauth_token
            {
                token_key    = client.oauth_token,
                token_secret = client.oauth_secret,
                type         = OAuthTokenType.YAHOO.ToString(),
                subdomainid  = subdomainid,
                appid        = appid.ToString(),
                authorised   = false
            };

            using (var repository = new TradelrRepository())
            {
                repository.AddOAuthToken(oauthdb);
            }
            return(Redirect(client.authorize_url));
        }
Exemple #4
0
 private void DeleteOAuthTokenIfExpired(oauth_token token)
 {
     if (token != null && token.expires.HasValue && DateTime.UtcNow > token.expires.Value)
     {
         db.oauth_tokens.DeleteOnSubmit(token);
         db.SubmitChanges();
     }
 }
Exemple #5
0
        /// <summary>
        /// checks if there is an existing entry by subdomainid, sessionid and type
        /// </summary>
        /// <param name="oauthToken"></param>
        public void AddOAuthToken(oauth_token oauthToken)
        {
            // if exist then just update it
            var exist = db.oauth_tokens.SingleOrDefault(x => x.type == oauthToken.type &&
                                                        x.subdomainid == oauthToken.subdomainid &&
                                                        x.appid == oauthToken.appid);

            if (exist != null)
            {
                exist.token_key    = oauthToken.token_key;
                exist.token_secret = oauthToken.token_secret;
                exist.expires      = oauthToken.expires;
                exist.authorised   = oauthToken.authorised;
            }
            else
            {
                db.oauth_tokens.InsertOnSubmit(oauthToken);
            }
            db.SubmitChanges();
        }
Exemple #6
0
        public ActionResult getToken()
        {
            var ebayservice = new EbayService();
            var requesturl  = ebayservice.GetRequestTokenUrl();

            var oauthdb = new oauth_token
            {
                token_key    = ebayservice.SessionID,
                token_secret = "",
                type         = OAuthTokenType.EBAY.ToString(),
                subdomainid  = subdomainid.Value,
                appid        = sessionid.Value.ToString(),
                authorised   = false
            };

            repository.AddOAuthToken(oauthdb);

            // need to append ruparameter
            var parameters = new NameValueCollection {
                { "sid", ebayservice.SessionID }
            };

            return(Redirect(string.Format(requesturl + "&ruparams={0}", parameters.ToQueryString(true).Substring(1))));
        }
Exemple #7
0
        public ActionResult Index(string token, string expires, string redirect, int?r)
        {
            if (!subdomainid.HasValue)
            {
                return(RedirectToAction("find", "login"));
            }

            // check if this is a redirect from a successful callback
            if (!string.IsNullOrEmpty(token))
            {
                // success, now see if we have an existing user
                var facebook = new FacebookService(token);
                var fbUsr    = facebook.People.GetUser("me");
                if (fbUsr == null)
                {
                    return(RedirectToAction("index", "login"));
                }

                var usr = repository.GetUserByFBID(fbUsr.id, subdomainid.Value);
                if (usr != null)
                {
                    // token is valid add/update to database
                    var oauthdb = new oauth_token
                    {
                        token_key    = token,
                        token_secret = "",
                        type         = OAuthTokenType.FACEBOOK.ToString(),
                        subdomainid  = subdomainid.Value,
                        appid        = usr.id.ToString(),
                        authorised   = true
                    };

                    if (!string.IsNullOrEmpty(expires))
                    {
                        DateTime expiresOn = DateTime.UtcNow.AddSeconds(Convert.ToDouble(expires));
                        oauthdb.expires = expiresOn;
                    }

                    repository.AddOAuthToken(oauthdb);
                    repository.Save();
                    SetAuthCookie(usr, true);
                }

                if (!string.IsNullOrEmpty(redirect))
                {
                    return(Redirect(redirect));
                }

                return(Redirect("/dashboard"));
            }

            if (sessionid.HasValue)
            {
                if (!string.IsNullOrEmpty(redirect))
                {
                    return(Redirect(HttpUtility.UrlDecode(redirect)));
                }

                return(Redirect("/dashboard"));
            }

            var org      = MASTERdomain.organisation;
            var viewdata = new LoginViewModel(baseviewmodel)
            {
                loginPageName        = string.IsNullOrEmpty(org.name) ? accountSubdomainName : org.name,
                showRegistrationHelp = r.HasValue && r.Value == 1
            };

            return(View(viewdata));
        }
Exemple #8
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) }));
        }
Exemple #9
0
        private string ProcessSuccesfulFacebookRegistrationCallback(IDictionary <string, object> result, string domainName, string planName, string affiliate)
        {
            var accessToken = (string)result["access_token"];

            // incase the expires on is not present, it means we have offline_access permission
            DateTime expiresOn = result.ContainsKey("expires") ? DateTime.UtcNow.AddSeconds(Convert.ToDouble(result["expires"])) : DateTime.MaxValue;

            // create subdomain
            var facebook     = new FacebookService(accessToken);
            var fbUsr        = facebook.People.GetUser("me");
            var errorMessage = "";

            if (fbUsr == null)
            {
                errorMessage = "Could not obtain facebook authorization";
                Syslog.Write(errorMessage);
                return(errorMessage);
            }

            // verify that email has not been used to register another account
            if (repository.GetUsersByEmail(fbUsr.email).SingleOrDefault(x => (x.role & (int)UserRole.CREATOR) != 0) != null)
            {
                errorMessage = string.Format("{0} is in use. Please choose a different email address.", fbUsr.email);
                Syslog.Write(errorMessage);
                return(errorMessage);
            }

            // CHECK THAT FBID NOT ALREADY BEEN USED
            if (repository.GetUserByFBID(fbUsr.id).SingleOrDefault(x => (x.role & (int)UserRole.CREATOR) != 0) != null)
            {
                errorMessage = "Facebook ID is in use. ";
                Syslog.Write(errorMessage + fbUsr.id);
                return(errorMessage);
            }

            var account = new Account(repository, fbUsr.email, domainName, planName.ToEnum <AccountPlanType>(), affiliate);

            errorMessage = account.CreateAccountWithFacebookLogin(fbUsr);
            if (!string.IsNullOrEmpty(errorMessage))
            {
                return(errorMessage);
            }

            try
            {
                // generate photo
                new Thread(() => account.usr.externalProfilePhoto.ReadAndSaveFromUrl(account.mastersubdomain.id, account.usr.id, account.usr.id, PhotoType.PROFILE)).Start();

                // add access token
                var oauthdb = new oauth_token
                {
                    token_key    = accessToken,
                    token_secret = "",
                    type         = OAuthTokenType.FACEBOOK.ToString(),
                    subdomainid  = account.mastersubdomain.id,
                    appid        = account.usr.id.ToString(),
                    authorised   = true,
                    expires      = expiresOn
                };

                repository.AddOAuthToken(oauthdb);

                // send confirmation email
                var viewdata = new ViewDataDictionary()
                {
                    { "host", domainName.ToTradelrDomainUrl("") },
                    { "confirmCode", account.usr.confirmationCode },
                    { "email", account.usr.email }
                };
                EmailHelper.SendEmailNow(EmailViewType.ACCOUNT_CONFIRMATION, viewdata, "New Account Details and Email Verification Link",
                                         account.usr.email, account.usr.ToFullName(), null);
            }
            catch (Exception ex)
            {
                Syslog.Write(ex);
                return("An error has occurred creating your account");
            }

            return("");
        }