Last active
August 3, 2023 20:35
-
-
Save 1travelintexan/a7ac7b8b3cdc9761491e6df59459eeea 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
// ℹ️ Gets access to environment variables/settings | |
// https://www.npmjs.com/package/dotenv | |
require('dotenv').config() | |
// ℹ️ Connects to the database | |
require('./db') | |
// Handles http requests (express is node js framework) | |
// https://www.npmjs.com/package/express | |
const express = require('express') | |
const app = express() | |
// ℹ️ This function is getting exported from the config folder. It runs most pieces of middleware | |
require('./config')(app) | |
// 👇 Start handling routes here | |
const indexRoutes = require('./routes/index.routes') | |
app.use('/api', indexRoutes) | |
const authRoutes = require('./routes/auth.routes') | |
app.use('/auth', authRoutes) | |
// ❗ To handle errors. Routes that don't exist or errors that you handle in specific routes | |
require('./error-handling')(app) | |
module.exports = app |
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 router = require('express').Router() | |
const bcrypt = require('bcryptjs') | |
const jwt = require('jsonwebtoken') | |
const User = require('../models/User.model') | |
const { isAuthenticated } = require('../middlewares/jwt.middleware') | |
router.get('/', (req, res, next) => { | |
res.json('All good in auth') | |
}) | |
/* POST route to signup */ | |
router.post('/signup', async (req, res) => { | |
const payload = req.body // { email: 'someEmail', password '1234'} | |
const salt = bcrypt.genSaltSync(13) | |
const passwordHash = bcrypt.hashSync(payload.password, salt) | |
try { | |
await User.create({ username: payload.username, email: payload.email, password: passwordHash }) | |
res.status(201).json({ message: 'User created' }) | |
} catch (error) { | |
console.log(error) | |
res.status(500).json(error) | |
} | |
}) | |
/* POST route to login */ | |
router.post('/login', async (req, res) => { | |
const payload = req.body // { email: 'someEmail', password '1234'} | |
/* Check if the user exists */ | |
const potentialUser = await User.findOne({ email: payload.email }) | |
if (potentialUser) { | |
const doPasswordsMatch = bcrypt.compareSync(payload.password, potentialUser.password) | |
/* Check if the password is correct */ | |
if (doPasswordsMatch) { | |
/* Sign the JWT */ | |
//this jwt.sign method is what actually creates the token for us. | |
const authToken = jwt.sign({ userId: potentialUser._id }, process.env.TOKEN_SECRET, { | |
algorithm: 'HS256', | |
expiresIn: '6h', | |
}) | |
// Sending back the token to the front and you can send more data if you want. | |
res.status(202).json({ token: authToken, EmiliesKey:'something cool',Hameds:'blah'}) | |
} else { | |
/* Incorrect password */ | |
res.status(403).json({errorMessage: 'Password invalid'}) | |
} | |
} else { | |
/* No user found */ | |
res.status(403).json({errorMessage: 'No user found'}) | |
} | |
}) | |
/* GET route to verify the token */ | |
router.get('/verify', isAuthenticated, async(req, res) => { | |
console.log('here is after the middleware, what JWT is giving us', req.payload) | |
const currentUser = await User.findById(req.payload.userId) | |
//never send the password, hashed or not to the front end | |
currentUser.password = '****' | |
res.status(200).json({message: 'Token is valid', currentUser}) | |
}) | |
module.exports = router |
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 { expressjwt } = require('express-jwt') | |
// Instantiate the JWT token validation middleware | |
const isAuthenticated = expressjwt({ | |
secret: process.env.TOKEN_SECRET, | |
algorithms: ['HS256'], | |
requestProperty: 'payload', | |
getToken: getTokenFromHeaders, | |
}) | |
// Function used to extracts the JWT token from the request's 'Authorization' Headers | |
function getTokenFromHeaders(req) { | |
// Check if the token is available on the request Headers | |
//"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2NGNhMzVkNDUzY2IzYzJlMTU3NTBkOTUiLCJpYXQiOjE2OTA5Nzg0MDUsImV4cCI6MTY5MTAwMDAwNX0.JIEW6x1ZSBiAdpNhxyB5O9Y2S68bl38fvxGfM3Bp3NU" | |
if (req.headers.authorization && req.headers.authorization.split(' ')[0] === 'Bearer') { | |
// Get the encoded token string and return it | |
const token = req.headers.authorization.split(' ')[1] | |
return token | |
} | |
return null | |
} | |
// Export the middleware so that we can use it to create a protected routes | |
module.exports = { | |
isAuthenticated, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment