var express = require('express');
var router = express.Router();
var auth = require("../bin/auth")

/* GET home page. */
router.get('/', function(req, res, next) {

  if(auth.check(req.cookies.token)) {
  
      res.redirect(302, "/")
  } else {
      res.clearCookie('token')
      res.render('login', {version: require("../package.json").version});
  }


});

module.exports = router;

router.post("/", (req, res) => {
  const body = req.body

  const token = auth.login({
    username: body.username,
    password: body.password
  })

  if(token == "AUTH_FAILED") {

    
    res.status(403).send("AUTH_FAILED")
  
  
  } else {

    res.cookie('token' , token, { maxAge: 900000000, httpOnly: true })
    res.status(200).send("AUTH_SUCCESS")
  }

}) 

router.get('/signout', function(req, res, next) {

  if(!auth.check(req.cookies.token)) {

    res.clearCookie('token')
    res.redirect(302, "/")

  
  } else {

    auth.signout(req.cookies.token)
    res.clearCookie('token')
    res.redirect(302, "/")
    
  }
  
});