// This is a very simple example of Passport.JS .

    // This is for demonstration purposes and should not be used for production.
    
    // Run npm install express passport passport-custom first.

// Boilerplate for Express apps.
const express = require('express');
const app = express();

// In addition to the Passport library, you have to import
// a strategy. Hundreds are available. For this demo,
// we'll use the custom strategy where you can implement any logic.
const passport = require('passport');
const CustomStrategy = require('passport-custom');

// This is the custom code which determines if the client can be
// authorized. In this case, it relies on the user simply clicking
// on the right button.
function verify(req,cb) {
  if (req.body.yes) {
    return cb(null,'value that represents the user');
  } else {
    return cb(null,false);
  }
  // if (err) return cb(err);
};

passport.use(new CustomStrategy(verify));


// And here are the routes.

app.get('/', (req, res) => {
  res.send(`<pre>
This is a simple example of PassportJS.

Are you allowed to use this app?

<form action="/Login" method="post">
 <button name="yes" value="yes" type="submit">Yes</button>
 <button name="no" type="submit">No</button>
</form>
</pre>`);
});


app.post('/Login',
  express.urlencoded(),
  passport.authenticate('custom', {
    failureRedirect: '/Bad',
    successRedirect: '/Good',
    session: false}));



app.get('/Good', (req, res) => {
  res.send(`<pre>

You are authorized.

<a href="/">Try again.</a>

</pre>`);
})


app.get('/Bad', (req, res) => {
  res.send(`<pre>

You are not authorized.

<a href="/">Try again.</a>

</pre>`);
})

app.listen(8000, () => console.log('Listening to port 8000.'));
    

/*

This is not a practical example.
For example, anyone could just access the /Good route directly and bypass authentication.
Furthermore, the app has no way to remember if the client is authenticated or not.
For that, you would need to use session management like express-session
or tokens.

*/

// https://sean.brunnock.com  1/2023