Sometimes you have great app idea, but you need to make authentication. Without further ado, I'll show you how to do it.
Part 1
Let's assume you have installed express
and now you need to:
npm i body-parser cookie-parser
Now you need to make file called accounts.json
Replace content of accounts.json
file with this:
[
{
"name": "user",
"password": "user",
"data": "I'm user"
},
{
"name": "user2",
"password": "user2",
"data": "I'm second user"
},
{
"name": "user3",
"password": "user3",
"data": "I'm third *special* user"
}
]
⚠ This is only example. Storing unhashed passwords is dangerous. If you know how to use databases you can use database.
Part 2
Now you need to have accounts list in an object and have sessions array.
Add this lines below const app
in your index.js
const accounts = require("accounts.json")
const sessions = {};
app.use(bodyParser.urlencoded());
app.use(cookieParser());
function randomSID() {
var sID = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15)
if(!sessions.hasOwnProperty(sID)){
return sID;
}
return randomSID();
}
Part 3
Create an /login
API endpoints.
app.get('/login', (req,res)=>{
res.send(`
<form type="post">
<input name="name">
<input name="password" type="password">
<button type="submint">Log In</button>
</form>
`)
})
app.post('/login', (req,res)=>{
if(accounts.find(x=>x.name == req.body.name && x.password == req.body.password){
const newSessionID = randomSID()
res.cookie('sID', newSessionID)
sessions[newSessionID] = accounts.findIndex(x => x.name ===
body.name && x.password === body.password)
res.redirect('/')
}
else {
res.send("Bad password")
}
})
Create logout API endpoint:
app.get('/logout', (req, res) => {
delete loggedInSessions[req.cookies.sID]
res.clearCookie('sID')
res.redirect('/')
})
Part 4
Create an account middleware
function accountMiddleware(req,res,next){
if(accounts[sessions[req.cookies.sID]]){
req.account = accounts[sessions[req.cookies.sID]]
}
else {
req.account = null;
}
next()
}
Also add this line next to app.use
's.
app.use(accountMiddleware)
Part 5
Now you can easily get account data using req.account
.
Example endpoint:
app.get('/', (req, res) => {
if(req.account){
res.send(`You are logged in as ${req.account.name} and here is your data: ${req.account.data}`)
}
else {
res.send("You are logged out")
}
});
Top comments (0)