Created
April 19, 2023 02:53
-
-
Save quocthinhle/81aea741c023acfbda47ea7eb5a95096 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require('express'); | |
const jsonwebtoken = require('jsonwebtoken'); | |
const app = express(); | |
const dbs = [ | |
{ | |
username: 'thinh', | |
age: 22, | |
email: '[email protected]', | |
id: 1, | |
password: 'thinh12345', | |
balance: 1000000, | |
}, | |
{ | |
username: 'phu', | |
age: 24, | |
email: '[email protected]', | |
id: 2, | |
password: 'phu12345', | |
balance: 1000000000, | |
}, | |
]; | |
const SECRET = 'your-secret'; | |
app.use(express.json()); | |
app.post('/login', function (req, res, next) { | |
const username = req.body.username; | |
const password = req.body.password; | |
// Find user in db | |
const user = dbs.find(u => u.username === username); | |
// Case 1: User does not exist | |
if (!user) { | |
return res.status(400).json({ | |
message: 'User not found', | |
}); | |
} | |
// Case 2: Found user with that username | |
if (user.password === password) { | |
// Sign a jwt | |
const jwt = jsonwebtoken.sign({ | |
username: user.username, | |
email: user.email, | |
age: user.age, | |
}, SECRET, { | |
algorithm: 'HS256', | |
expiresIn: '1h', | |
}); | |
// Return jwt to user | |
return res.status(200).json({ | |
data: jwt, | |
message: 'Login success', | |
}); | |
} | |
return res.status(401).json({ | |
message: 'Invalid credentials', | |
}); | |
}); | |
app.get('/balance', (req, res, next) => { | |
// Get username from query string | |
const username = req.query.username; | |
// Get token from request | |
const authorizationHeader = req.headers.authorization; | |
// authorizationHeader = 'Bearer <TOKEN>' | |
// => token: authorizationHeader.substring(7) | |
const userToken = authorizationHeader.substring(7); | |
// Verify token | |
try { | |
const isTokenValid = jsonwebtoken.verify(userToken, SECRET); | |
// Authorization success | |
if (isTokenValid.username == username) { | |
const user = dbs.find(u => u.username === username); | |
return res.status(200).json({ | |
balance: user.balance, | |
}); | |
} | |
// Authorization failed | |
return res.status(401).json({ | |
message: 'unauthorized', | |
}); | |
} catch (error) { | |
return res.status(401).json({ | |
message: error.message, | |
}); | |
} | |
}); | |
app.listen(3000, () => console.log('Server is listening on PORT 3000')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment