// This is a very simple example of Passport.JS
    // and passport-local .

    // Run npm install express passport passport-local first.

// Standard code to use Express.
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 local strategy where the client provides
// a username and password.
const passport = require('passport');
const LocalStrategy = require('passport-local');


// Very simple password database below. Do not use in production.
const passwords = {
  jon: 1234,
  jan: 4567
}


// Enable the Passport object with a verifiaction function.
// The verification function returns
function verify(username, password, cb) {
  if (passwords[username] == password) {
    return cb(null, username); // right password
  } else {
    return cb(null, false); // wrong password
  }
}

passport.use(new LocalStrategy(verify));


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

req.user=${req.user}

You can log in as ${Object.entries(passwords).map(x=>`username ${x[0]} and password ${x[1]}`).join(' or \n')}.
  
<form action="/Login" method="post">
 <label for="username">Username</label>
 <input name="username" type="text" required autofocus>

 <label for="password">Password</label>
 <input name="password" type="password" required>

 <button type="submit">Login</button>
</form>
</pre>`);
    
});


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

  (req, res) => {
    res.send(`<pre>
You are logged in.

req.user=${req.user}

This authentication will not carry over to the next request.
To do that, you need some sort of session management.

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

</form>

</pre>`)
    
  }
);


app.get('/Bad', (req, res) =>
  res.send(`<pre> Failed.\n\n <a href="/">Try again.</a> </pre>`));


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


// https://sean.brunnock.com 12/2022