OAuth 2.0

constcrypto=require('@arangodb/crypto');constrouter=createRouter();constoauth2=createOAuth2Client({// We'll use Facebook for this exampleauthEndpoint:'https://www.facebook.com/dialog/oauth',tokenEndpoint:'https://graph.facebook.com/oauth/access_token',activeUserEndpoint:'https://graph.facebook.com/v2.0/me',clientId:'keyboardcat',clientSecret:'keyboardcat'});module.context.use('/oauth2',router);// See the user management example for setting up the// sessions and users objects used in this examplerouter.use(sessions);router.post('/auth',function(req,res){constcsrfToken=crypto.genRandomAlphaNumbers(32);consturl=req.reverse('oauth2_callback',{csrfToken});constredirect_uri=req.makeAbsolute(url);// Set CSRF cookie for five minutesres.cookie('oauth2_csrf_token',csrfToken,{ttl:60*5});// Redirect to the provider's authorization URLres.redirect(303,oauth2.getAuthUrl(redirect_uri));});router.get('/auth',function(req,res){// Some providers pass errors as query parameterif(req.queryParams.error){res.throw(500,`Provider error: ${req.queryParams.error}`)}// Make sure CSRF cookie matches the URLconstexpectedToken=req.cookie('oauth2_csrf_token');if(!expectedToken||req.queryParams.csrfToken!==expectedToken){res.throw(400,'CSRF mismatch.');}// Make sure the URL contains a grant tokenif(!req.queryParams.code){res.throw(400,'Provider did not pass grant token.');}// Reconstruct the redirect_uri used for the grant tokenconsturl=req.reverse('oauth2_callback');constredirect_uri=req.makeAbsolute(url);// Fetch an access token from the providerconstauthData=oauth2.exchangeGrantToken(req.queryParams.code,redirect_uri);constfacebookToken=authData.access_token;// Fetch the active user's profile infoconstprofile=oauth2.fetchActiveUser(facebookToken);constfacebookId=profile.id;// Try to find an existing user with the user ID// (this requires the users collection)letuser=users.firstExample({facebookId});if(user){// Update the facebookToken if it has changedif(user.facebookToken!==facebookToken){users.update(user,{facebookToken});}}else{// Create a new user documentuser={username:`fb:${facebookId}`,facebookId,facebookToken}constmeta=users.save(user);Object.assign(user,meta);}// Log the user in (this requires the session middleware)req.session.uid=user._key;req.session.facebookToken=authData.facebookToken;req.sessionStorage.save(req.session);// Redirect to the default routeres.redirect(303,req.makeAbsolute('/'));},'oauth2_callback').queryParam('error',joi.string().optional()).queryParam('csrfToken',joi.string().optional()).queryParam('code',joi.string().optional());