Skip to content

Instantly share code, notes, and snippets.

@alexpchin
Forked from JamesTheHacker/Session.js
Created May 5, 2021 18:58
Show Gist options
  • Save alexpchin/548ed7c0922adee8cdf8d31a75a8cd30 to your computer and use it in GitHub Desktop.
Save alexpchin/548ed7c0922adee8cdf8d31a75a8cd30 to your computer and use it in GitHub Desktop.
Log into Facebook using cookies
'use strict'
let Promise = require('bluebird');
let fs = Promise.promisifyAll(require('fs'));
let Cheerio = require('cheerio');
let Request = require('request');
let ToughCookie = require('tough-cookie');
class Session {
constructor(useragent) {
this.ua = useragent;
this.fbdtsg = null;
this.uid = null;
}
dtsg() {
return new Promise((resolve, reject) => {
if(this.request === null) {
reject(new Error("self.request is not set. Are you logged in?"));
return;
}
this.request('https://facebook.com', (err, resp, body) => {
if(err) {
reject(new Error(err));
return;
}
let match = /name="fb_dtsg" value="([A-Za-z0-9-_:]+)"/.exec(body);
if(match == null) {
reject(new Error("Failed to parse fb_dtsg"));
return;
}
resolve(match[1]);
})
})
}
parseEditThisCookieJSON(file) {
return new Promise((resolve, reject) => {
fs.readFileAsync(file).then((data) => {
let cookies = [];
let JSONCookies;
// Catch any errors when parsing JSON
try {
JSONCookies = JSON.parse(data);
} catch(err) {
reject(new Error(err));
return;
}
// Loop through each cookie in the JSON object adding them to a cooikes array
JSONCookies.forEach(cookie => {
let extensions = [
'session=true',
'sameSite=no_restriction'
];
if(cookie.expirationDate) {
extensions.push('expirationDate=' + cookie.expirationDate)
}
cookies.push(new ToughCookie.Cookie({
key: cookie.name,
value: cookie.value,
secure: cookie.secure || false,
path: cookie.path,
httpOnly: cookie.httpOnly || false,
extensions: extensions
}));
// Set the uid property of object with users ID
if(cookie.name === 'c_user') {
this.uid = cookie.value;
}
})
resolve(cookies);
})
})
}
setCookies(cookies) {
let cookieJar = Request.jar();
return new Promise((resolve, reject) => {
this.parseEditThisCookieJSON(cookies).then(cookies => {
cookies.forEach(function(cookie) {
cookieJar.setCookie(cookie, 'https://facebook.com', (err, cookie) => {
if(err) {
reject(new Error(err));
return;
}
})
})
this.request = Request.defaults({
jar: cookieJar, headers: { 'User-Agent': this.ua }
});
this.dtsg().then(dtsg => {
this.fbdtsg = dtsg;
resolve(true);
})
})
})
}
}
module.exports = Session;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment