Created
March 2, 2019 15:41
-
-
Save k0d3d/f062e3d815928ecca8f5849a8e713a63 to your computer and use it in GitHub Desktop.
setting state data -> cookies now work using cosmos db bindings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const puppeteer = require("puppeteer"); | |
module.exports = async function(context, req, pageCookiesIn) { | |
context.log("Started working function"); | |
if (!req.body || | |
!req.body.username || | |
!req.body.password) { | |
context.res = { | |
status: 400, | |
body: "Request Parameters not set // expecting {username: 'xxx', password: 'xxx'} in req.body" | |
} | |
return | |
} | |
const browser = await puppeteer.connect({ | |
browserWSEndpoint: "ws://d.ixit.com.ng" | |
}); | |
const page = await browser.newPage(); | |
await page.setViewport({ width: 1237, height: 670 }); | |
await page.goto("https://www.instagram.com/accounts/login"); | |
let userHasExisitingSession = false | |
if (pageCookiesIn) { | |
userHasExisitingSession = Object.values(context.bindings.pageCookiesIn[0]) | |
userHasExisitingSession = userHasExisitingSession.filter(o => o instanceof Object) | |
await page.setCookie(...userHasExisitingSession) | |
} | |
// attempt login | |
await page.waitForSelector("[name=username]"); | |
await page.type("[name=username]", req.body.username); | |
await page.type("[name=password]", req.body.password); | |
await page.click("[type=submit]"); | |
try { | |
await page.waitForNavigation({ timeout: 2000 }); | |
let ob = { ...await page.cookies(), id: req.body.username } | |
// Cosmos DB output binding | |
// create a new document | |
context.bindings.pageCookiesOut = JSON.stringify(ob); | |
await page.goto("https://www.instagram.com/accounts/activity/"); | |
let isLoggedin = false | |
isLoggedIn = await page.$("h1"); | |
if (isLoggedIn) { | |
context.res = { | |
body: await page.content(), | |
headers: { | |
"Content-Type": "text/html" | |
} | |
}; | |
} else { | |
context.res = { | |
body: await page.content(), | |
headers: { | |
"Content-Type": "text/html" | |
} | |
}; | |
} | |
await browser.close(); | |
} catch (e) { | |
// the page does not refresh because, of .... | |
// many possible errors. | |
// Instagram displays an error alert message | |
// if authentication fails. | |
try { | |
await page.waitForSelector("[role=alert]"); | |
const alertElement = await page.$eval( | |
"[role=alert]", | |
node => node.innerHTML | |
); | |
// check for that then respond | |
context.res = { | |
status: 401, | |
body: alertElement | |
}; | |
} catch (e) { | |
context.res = { | |
body: await page.content(), | |
headers: { | |
"Content-Type": "text/html" | |
} | |
}; | |
} | |
await browser.close(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment