16
loading...
This website collects cookies to deliver better user experience
mkdir Tutorial
npm init
commandnpm install express --save
const express = require("express")
const app = express()
process.env.PORT = 3000
app.get("/" , (req ,res)=>{
res.status(200).send({"STATUS":"SUCCESS"})
})
app.listen(3000 , ()=>{
console.log(`STARTED LISTENING ON PORT ${process.env.PORT}`)
});
node app.js
const isAuthenticated = (req , res , next)=>{
next()
}
app.get("/" ,isAuthenticated, (req ,res)=>{
res.status(200).send({"STATUS":"SUCCESS"})
})
const credentials = {secretName:"Anas Aijaz" , secretPassword:"Catsaresosus"}
const isAuthenticated = (req , res , next)=>{
const [name , password] = ["Anas Aijaz" , "Dogsaresosus"]
// We will add code here later
if(name===credentials.secretName && password===credentials.secretPassword){
// The User is authenticated
return next()
}
// User is not authenticated give a reponse 401
res.set('WWW-Authenticate', 'Basic realm="Access to Index"')
res.status(401).send("Unauthorised access")
}
cd ../ && mkdir client && cd client && touch index.html index.js
<form>
<label>username</label>
<input name="username" type="text"/>
<label>password</label>
<input type="password" name="password"/>
<input type="submit"/>
</form>
document.addEventListener("submit" , (event)=>{
event.preventDefault()
})
username
and password
fetch("http://localhost:3000/" , {})
.then(()=>{})
.catch(()=>{
console.log("an error occured")
})
const headers = new Headers()
headers.append("Accept" , "application/json")
${username}:${password}
)Basic ${base64data}
fetch("http://localhost:3000/", { headers:headers })
.then(()=>{})
.catch(()=>{
console.log("an error occured")
})
})
const encodedAuth = (req.headers.authorization || '')
.split(' ')[1] || '' // getting the part after Basic
const [name, password] = Buffer.from(encodedAuth, 'base64')
.toString().split(':')
if(name===credentials.secretName && password===credentials.secretPassword){
// The User is authenticated
return next()
}
.then((response)=>{
console.log(response)
if(response.status == 200){
document.write("SUCCESFULL LOGIN")
}
})
:PS
There are some caveats in our application such as splitting the >string using ":" delimiter will cause unexpected reaction if the >password or username too have a colon you can fix this by >extracting the username and password by REGEX
you can improve this application by issuing a bearer token and >storing it in cookie to access across pages and maintain the >login state but that's the story of another day :)
further reading