// Environmental Configurations
require('dotenv').config();

// Load 3rd party libraries
const Koa = require('koa');
const body = require('koa-body');
const jwt = require('koa-jwt');
const jsonwt = require('jsonwebtoken');
const unless = require('koa-unless');
const logger = require('koa-logger');
const bouncer = require('koa-bouncer');

const Router = require('koa-router');
const auth = new Router();

// Use Google OAuth for authentication
const passport = require('koa-passport');
const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

// Local imports
const db = require('./db');
const routes = require('./routes');
const config = require('./config');

const app = new Koa();

// development debugging tools
if (config.NODE_ENV === 'development') {
  app.use(logger());
}

app.use(passport.initialize());
app.use(body());
app.use(bouncer.middleware());

passport.use(new GoogleStrategy({
    clientID: config.GOOGLE_CONSUMER_KEY,
    clientSecret: config.GOOGLE_CONSUMER_SECRET,
    callbackURL: 'http://' + config.HOSTNAME + '/auth/google/callback',
  },
  function(token, tokenSecret, profile, done) {
    db.findUserG(profile.id).then(
      function(user) {
        err = null;
        return done(err, user);
      }
    )
    .catch(
      function(user) {
        user = db.createUser(profile.id, profile.name.givenName,
                             profile.emails);
        err = null;
        return done(err, user);
      }
    );
}));

auth.get('/auth/google',
  passport.authenticate('google',
  {scope: ['https://www.googleapis.com/auth/plus.login']})
);

auth.get('/auth/google/callback',
  passport.authenticate('google', {
    session: false,
  }),
  async(ctx) => {
    await ctx.state.user.then(
      async function(user) {
        await ctx.cookies.set(
          'authorization',
          jsonwt.sign(user.uuid, config.JWT_SECRET, {
            expiresIn: 60,
          })
        );
        ctx.response.status = 200;
      }
    )
    .catch(
      function() {
        ctx.response.status = 401;
      }
    );
});

// app.use(home.routes());
app.use(auth.routes());

// require jwt unless the path is public
app.use(jwt({
  secret: config.JWT_SECRET,
  cookie: 'authorization',
}).unless({path: [/^\/auth/]}));
app.use(routes.routes());
app.start = function() {
  app.listen(3000);
};

module.exports = app;

@@ -1076,16 +1076,22 @@
 %0A  %7D,%0A  
+async 
 function
@@ -1132,16 +1132,29 @@
 ) %7B%0A    
+user = await 
 db.findU
@@ -1173,60 +1173,26 @@
 .id)
-.then(%0A      function(user) %7B%0A        err = null;%0A  
+;%0A    if (user) %7B%0A
     
@@ -1197,35 +1197,36 @@
     return done(
-err
+null
 , user);%0A      %7D
@@ -1226,55 +1226,17 @@
     
-  %7D%0A    )%0A    .catch(%0A      function(user)
+%7D else
  %7B%0A
-  
     
@@ -1243,16 +1243,22 @@
   user =
+ await
  db.crea
@@ -1288,24 +1288,26 @@
 ile.
-name.given
+display
 Name,%0A
+     
     
@@ -1352,30 +1352,8 @@
 s);%0A
-        err = null;%0A  
     
@@ -1370,11 +1370,12 @@
 one(
-err
+null
 , us
@@ -1379,31 +1379,22 @@
  user);%0A
-  
     %7D%0A
-    );%0A
 %7D));%0A%0Aau
@@ -1627,29 +1627,30 @@
 x) =%3E %7B%0A    
-await
+user =
  ctx.state.u
@@ -1656,35 +1656,17 @@
 user
-.then(%0A      async function
+;%0A    if 
 (use
@@ -1666,26 +1666,24 @@
 if (user) %7B%0A
-  
       await 
@@ -1707,18 +1707,16 @@
         
- 
- 
 'authori
@@ -1732,18 +1732,16 @@
         
-  
 jsonwt.s
@@ -1748,17 +1748,46 @@
 ign(
-user.uuid
+%7B%0A          data: user.uuid,%0A        %7D
 , co
@@ -1804,29 +1804,16 @@
 ECRET, %7B
-%0A            
 expiresI
@@ -1819,11 +1819,14 @@
 In: 
-60,
+'1hr'%7D
 %0A   
@@ -1834,26 +1834,12 @@
     
-  %7D)%0A        
+)
 );%0A
-  
     
@@ -1875,51 +1875,17 @@
     
-  %7D%0A    )%0A    .catch(%0A      function()
+%7D else
  %7B%0A
-  
     
@@ -1921,18 +1921,9 @@
     
-  %7D%0A    );
+%7D
 %0A%7D);

fix oauth2 login flow