-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfillScreener.js
155 lines (128 loc) · 5.27 KB
/
fillScreener.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
require('dotenv').config();
const puppeteer = require('puppeteer');
const fs = require('fs').promises;
const admin = require("firebase-admin");
const serviceAccount = JSON.parse(process.env.FIREBASE_API_KEY)
const loginInfo = require("./secrets/login.json")
//const prompt = require('prompt-sync')();
admin.initializeApp({
projectId: "auth-screener",
credential: admin.credential.cert(serviceAccount)
})
const db = admin.firestore();
async function runAutoScreener(writeNewCookie, production=true) {
console.log(writeNewCookie)
const formLink = "https://calberkeley.ca1.qualtrics.com/jfe/form/SV_3xTgcs162K19qRv";
let browser;
if (writeNewCookie) {
browser = await puppeteer.launch({ headless: false, slowMo: 10, timeout: 60000 })
} else if (production) {
browser = await puppeteer.launch({ slowMo: 10 });
} else {
browser = await puppeteer.launch({ headless: false, devtools: true, slowMo: 100 });
}
const page = await browser.newPage();
let userAuth = {};
await db.collection("users")
.doc("personal")
.get()
.then((doc) => {
const dbUserAuth = doc.data()
//userAuth["username"] = dbUserAuth["username"]
//userAuth["password"] = dbUserAuth["password"]
userAuth["username"] = process.env.USERNAME
userAuth["password"] = process.env.PASSWORD
userAuth["authCookie"] = dbUserAuth["authCookie"]
userAuth["authTokenExpires"] = dbUserAuth["authTokenExpires"]
})
try {
await page.goto(formLink);
await page.screenshot({ path: './logs/example.png', fullPage: true });
if (!writeNewCookie) {
//const cookiesString = await fs.readFile('./.env/cookies/cookies_v4.json');
const cookiesString = userAuth["authCookie"]
const cookies = JSON.parse(cookiesString);
await page.setCookie(...cookies)
console.log("Cookies set!")
showDaysToExpiry(userAuth["authTokenExpires"])
}
const q1ID = "#QID10-5-label"
const nextButtonID = "#NextButton"
await page.waitForSelector(q1ID)
await page.click(q1ID)
await page.click(nextButtonID)
// credentials
console.log("Authentication beginning (check Duomobile if not progressing)...")
const usernameID = "#username"
const passwordID = "#password"
const submitBtnID = "#submit"
await page.waitForSelector(usernameID)
await page.waitForSelector(passwordID)
await page.type(usernameID, userAuth["username"])
await page.type(passwordID, userAuth["password"])
await page.click(submitBtnID)
const q2ID = "#QID3-3-label"
await page.waitForSelector(q2ID)
console.log("Authentication completed")
await page.click(q2ID)
await page.click(nextButtonID)
// all questions completed
const finishedID = "#EndOfSurvey"
await page.waitForSelector(finishedID)
await page.screenshot({ path: 'logs/success.png', fullPage: true });
if (writeNewCookie) {
const createdCookies = await page.cookies("https://api-6b447a0c.duosecurity.com");
//console.log(JSON.stringify(createdCookies1))
await writeToDB(createdCookies)
}
await browser.close()
console.log("Task succeeded")
} catch (e) {
console.log(`Task Failed: ${e}`)
await page.screenshot({ path: './logs/error.png', fullPage: true });
}
}
async function writeToDB(cookies) {
// cookies: JSON object
let authToken = findAuthToken(cookies)
if (!authToken) {
throw new Error("Authentication token not found, cookies not saved! Please make sure you're hitting 'remember my cookies' on the Duomobile authentication page.")
} else {
showDaysToExpiry(authToken.expires)
await db.collection("users")
.doc("personal")
.update({
authCookie: JSON.stringify(cookies),
authTokenExpires: authToken.expires
})
.then(() => {
console.log("Cookie successfully written")
})
.catch((e) => {
console.log(`Cookie failed to be written with error: ${e}`)
})
}
}
function showDaysToExpiry(expiryTimestamp) {
// expiryTimestamp: Unix timestamp in seconds
if (expiryTimestamp > 0) {
let expireDate = new Date(expiryTimestamp * 1000);
let today = new Date()
let difInDays = (expireDate - today) / (1000 * 3600 * 24)
console.log(`Auth Token expires ${expireDate.toString()} (${Math.round(difInDays * 100) / 100} days from now)`)
}
}
function findAuthToken(cookiesJSON) {
// cookiesJSON: cookies as JSON object
let authToken;
for (let cookie of cookiesJSON) {
if (cookie["name"] == process.env.AUTH_TOKEN_NAME) {
authToken = cookie
break
}
}
return authToken
}
runAutoScreener(false, true)
.then(() => {console.log("Promise resolved"); process.exit()})
.catch((e) => {console.log(`Task failed with runtime error: ${e}`); process.exit()});