UNPKG

1.4 kBJavaScriptView Raw
1const http = require('http')
2const opn = require('opn')
3const getPort = require('get-port')
4const url = require('url')
5const oauth2Client = require('./auth')
6const { PORT = 3000 } = process.env
7const { getToken, getProfile } = require('./client')
8const Gmail = require('./gmail')
9const db = require('./db')
10
11const handler = async (req, res) => {
12 console.log(req.url)
13 const parsed = url.parse(req.url, true)
14 console.log(parsed)
15 if (!req.url.startsWith('/callback')) return
16 const { tokens } = await getToken(parsed.query.code)
17 const profile = await getProfile(tokens.access_token)
18
19 let accounts = {
20 [profile.emailAddress]: {
21 profile,
22 tokens
23 }
24 }
25 db.set('prefs.accounts', accounts).write()
26 let gmail = new Gmail(accounts)
27 gmail.homeMenu()
28 res.writeHead(200, { 'Content-Type': 'text/html' })
29 res.end('<script> window.close(); </script>')
30}
31
32const server = http.createServer(handler)
33
34const scopes = [
35 'https://mail.google.com/',
36 'https://www.googleapis.com/auth/gmail.compose',
37 'https://www.googleapis.com/auth/gmail.modify',
38 'https://www.googleapis.com/auth/gmail.send'
39]
40
41getPort({ port: PORT }).then(port => {
42 console.log('http://localhost:' + port)
43 server.listen(port, async () => {
44 const auth = await oauth2Client()
45 const url = await auth.generateAuthUrl({
46 access_type: 'offline',
47 scope: scopes
48 })
49 opn(url)
50 })
51})