2018-08-05 16:26:28 +02:00
const fs = require ( 'fs' ) ;
const path = require ( 'path' ) ;
const http = require ( 'http' ) ;
const url = require ( 'url' ) ;
const querystring = require ( 'querystring' ) ;
const opn = require ( 'opn' ) ;
const destroyer = require ( 'server-destroy' ) ;
const { google } = require ( 'googleapis' ) ;
const plus = google . plus ( 'v1' ) ;
const keys = sails . config . custom . googleapi ;
/ * *
* Create a new OAuth2 client with the configured keys .
* /
const oauth2Client = new google . auth . OAuth2 (
keys . client _id ,
keys . client _secret ,
keys . redirect _uris [ 0 ]
) ;
/ * *
* This is one of the many ways you can configure googleapis to use authentication credentials . In this method , we 're setting a global reference for all APIs. Any other API you use here, like google.drive(' v3 ' ) , will now use this auth client . You can also override the auth client at the service and method call levels .
* /
google . options ( { auth : oauth2Client } ) ;
/ * *
* Open an http server to accept the oauth callback . In this simple example , the only request to our webserver is to / callback ? code = < code >
* /
async function authenticate ( scopes ) {
return new Promise ( ( resolve , reject ) => {
// grab the url that will be used for authorization
const authorizeUrl = oauth2Client . generateAuthUrl ( {
access _type : 'offline' ,
scope : scopes . join ( ' ' )
} ) ;
const server = http . createServer ( async ( req , res ) => {
try {
if ( req . url . indexOf ( '/oauth2callback' ) > - 1 ) {
const qs = querystring . parse ( url . parse ( req . url ) . query ) ;
res . end ( 'Authentication successful! Please return to the console.' ) ;
server . destroy ( ) ;
const { tokens } = await oauth2Client . getToken ( qs . code ) ;
oauth2Client . credentials = tokens ;
resolve ( oauth2Client ) ;
}
} catch ( e ) {
reject ( e ) ;
}
} ) . listen ( 3000 , ( ) => {
// open the browser to the authorize url to start the workflow
opn ( authorizeUrl , { wait : false } ) . then ( cp => cp . unref ( ) ) ;
} ) ;
destroyer ( server ) ;
} ) ;
}
async function runSample ( ) {
// retrieve user profile
const res = await plus . people . get ( { userId : 'me' } ) ;
console . log ( res . data ) ;
}
const scopes = [ 'https://www.googleapis.com/auth/plus.me' ] ;
/ * a u t h e n t i c a t e ( s c o p e s )
. then ( client => runSample ( client ) )
. catch ( console . error ) ; * /
function authUrl ( ) {
const authorizeUrl = oauth2Client . generateAuthUrl ( {
access _type : 'offline' ,
scope : scopes . join ( ' ' )
} ) ;
return authorizeUrl ;
}
2018-08-05 14:14:39 +02:00
module . exports = {
friendlyName : 'Signin' ,
description : 'Signin users.' ,
inputs : {
} ,
exits : {
success : {
responseType : 'view' ,
viewTemplatePath : 'pages/users/signin'
}
} ,
fn : async function ( inputs , exits ) {
2018-08-05 16:26:28 +02:00
const url = authUrl ( ) ;
return exits . success ( { url : url } ) ;
2018-08-05 14:14:39 +02:00
}
} ;
2018-08-05 16:26:28 +02:00