Express crashing silently - javascript

In my server I'm making /auth routes where I have functions for signing up and logging in. When I comment out the function login (because it isn't finished and throws errors) the app crashes silently. When I don't comment it out TypeScript tells me that the functions that haven't been implemented yet don't exist but still runs the server. After that when I try to sign up in the route /auth/signup it tells me this: Cannot GET /auth/signup. Here's my code:
controllers/auth.ts
import { Request, Response } from "express";
import { config } from "../index.js";
export async function signup(req: Request, res: Response) {
// stuff that signs you up
}
export async function login(req: Request, res: Response) {
const { email, password, userType } = req.body;
if (!email || !password || !userType)
return res.status(400).send({ message: "Please fullfil all fields." });
let user;
// helper functions below haven't been defined yet
if (userType === "student") {
user = await getStudentByEmail(email);
} else if (userType === "teacher") {
user = await getTeacherByEmail(email);
} else if (userType === "parent") {
user = await getParentByEmail(email);
} else if (userType === "schoolAdmin") {
user = await getSchoolAdminByEmail(email);
} else if (userType === "admin") {
user = await getAdminByEmail(email);
} else {
return res.status(400).send({ message: "Invalid user type" });
}
// access first user in array
user = user[0];
// check if user exists
if (!user) return res.status(400).send({ message: "User not found" });
const userPassword = user.password;
const passwordMatch = bcrypt.compareSync(password, userPassword);
if (!passwordMatch)
return res.status(400).send({ message: "Invalid password" });
const token = jwt.sign({ email: user.email }, config.serverSecret);
return res.status(200).send({ token });
}
/routes/auth.ts
import { Router } from "express";
import { signup, login } from "../controllers/auth.js";
export const router: Router = Router();
router.post("/signup", signup);
router.post("/login", login);
export const path = "/auth";
main file index.ts:
import dotenv from "dotenv";
import cors from "cors";
import path from "path";
import { fileURLToPath } from "url";
import fs from "fs";
import express, {
Express,
Request,
Response,
NextFunction,
Router,
} from "express";
import { Config } from "./interfaces/index.js";
// set __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// init dotenv
dotenv.config({ path: path.join(__dirname, "./.env") });
export const config: Config = {
nodeEnvironment: process.env.NODE_ENV,
// set cors with whitelist array
whitelistedDomains: (process.env.WHITELISTED_DOMAINS || "").split(", "),
serverPort: parseInt(process.env.SERVER_PORT || "8393"),
serverSecret: process.env.SERVER_SECRET,
databaseUsername: process.env.DATABASE_USERNAME,
databasePassword: process.env.DATABASE_PASSWORD || "",
databasePort: parseInt(process.env.DATABASE_PORT),
databaseName: process.env.DATABASE_NAME,
};
const app: Express = express();
const routesPath: string = path.join(__dirname, "routes");
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
const allowedOrigins: string[] =
config.nodeEnvironment === "production"
? config.whitelistedDomains
: ["http://localhost:3000", "http://127.0.0.1:3000"];
app.use(
cors({
origin: allowedOrigins,
optionsSuccessStatus: 200,
})
);
app.use((req: Request, res: Response, next: NextFunction) => {
const origin: string = req.headers.origin;
if (allowedOrigins.includes(origin))
res.setHeader("Access-Control-Allow-Origin", origin);
res.set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.set(
"Access-Control-Allow-Headers",
"Content-Type, X-Access-Token, Origin"
);
next();
});
// register routes
try {
await Promise.all(
fs.readdirSync(routesPath).map(async (file: string) => {
const route: { path: string; router: Router } = await import(
`./routes/${file}`
);
console.log(route);
app.use(route.path, route.router);
})
);
app.all("*", (_: Request, res: Response) =>
res.status(404).json({
message: "Not found",
})
);
} catch (err) {
console.log(err);
}
app.listen(config.serverPort, () => {
console.log(`Server is running on port ${config.serverPort}`);
});

Related

POST 504 (gateway timeout) error when trying to proxy angular app to node server

full error message : POST http://localhost:4200/api/user/login 504 (Gateway Timeout)
when trying to create a login function in my angular app and have it communicate with the express backend i get the 504 error shown above. I've included snippets of what i think is all the relevant code below.
running on localhost:4200 trying to reach localhost:3000 that the server is being run on.
app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const url = 'mongodb+srv://josh:*******#cluster0.cwv6f.mongodb.net/Unionise?retryWrites=true&w=majority';
const User = require('./models/user.model');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended : false}))
app.post('/api/user/login', (req, res) => {
mongoose.connect(url,{ useMongoClient: true }, function(err){
if(err) throw err;
User.find({
username : req.body.username, password : req.body.password
}, function(err, user){
if(err) throw err;
if(user.length === 1){
return res.status(200).json({
status: 'success',
data: user
})
} else {
return res.status(200).json({
status: 'fail',
message: 'Login Failed'
})
}
})
});
})
app.get('/api/user/login', (req, res) => {
res.send('Hello World!')
})
app.listen(3000, () => console.log('blog server running on port 3000!'))
login.component.ts
import { AppService } from './../app.service';
import { Component, OnInit } from '#angular/core';
import { LoginService } from './login.service';
import { User } from '../models/user.model';
import { response } from 'express';
import { Console } from 'console';
#Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css'],
providers: [ LoginService ]
})
export class LoginComponent implements OnInit {
public user : User;
success = "";
constructor(private loginService: LoginService, public appService: AppService) {
this.user = new User();
}
validateLogin() {
if(this.user.username && this.user.password) {
this.loginService.validateLogin(this.user).subscribe(result => {
console.log('result is ', result);
}, error => {
console.log('error is ', error);
});
} else {
alert('enter user name and password');
}
}
ngOnInit(): void {
// this.appService.login().subscribe(
// response=>{
// this.success = response.status;
// console.log(this.success);
// },
// error => {}
// );
}
}
login.service.ts
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { User } from '../models/user.model';
#Injectable()
export class LoginService {
constructor(private http: HttpClient){
}
validateLogin(user: User){
return this.http.post('/api/user/login',{
username : user.username,
password : user.password
})
}
}
routing
import { NgModule } from '#angular/core';
import { RouterModule, Routes } from '#angular/router';
import { LoginComponent } from './login/login.component';
const routes: Routes = [
{ path: '', component: LoginComponent },
];
#NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
proxy
{
"/api/*": {
"target": "http://localhost:3000",
"secure": "false"
}
}
Command console errors:
Angular app
<e> [webpack-dev-server] [HPM] Error occurred while proxying request localhost:4200/api/user/login to http://localhost:3000/ [ECONNRESET] (https://nodejs.org/api/errors.html#errors_common_system_errors)
server
C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\helpers\promiseOrCallback.js:20
throw error;
^
MongoParseError: option usemongoclient is not supported
at parseOptions (C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongodb\lib\connection_string.js:289:15)
at new MongoClient (C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongodb\lib\mongo_client.js:62:63)
at C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\connection.js:784:16
at new Promise (<anonymous>)
at NativeConnection.Connection.openUri (C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\connection.js:781:19)
at C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\index.js:340:10
at promiseOrCallback (C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\helpers\promiseOrCallback.js:10:12)
at Mongoose._promiseOrCallback (C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\index.js:1140:10)
at Mongoose.connect (C:\Users\joshk\Documents\GitHub\Unionise\server\node_modules\mongoose\lib\index.js:339:20)
at C:\Users\joshk\Documents\GitHub\Unionise\server\app.js:20:11
Node.js v17.4.0
Your problem is that You're creating connection when request comes in.
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const url = 'mongodb+srv://josh:*******#cluster0.cwv6f.mongodb.net/Unionise?retryWrites=true&w=majority';
const User = require('./models/user.model');
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended : false}))
app.post('/api/user/login', async (req, res) => {
try {
const query = {
username: req.body.username,
password: req.body.password,
};
const user = await User.findOne(query).lean();
if (!user) {
return res.status(200).json({
status: 'fail',
message: 'Login Failed'
});
}
res.status(200).json({
status: 'success',
data: user
});
}
catch (error) {
console.error(error.message);
res.status(500).end();
}
})
app.get('/api/user/login', (req, res) => {
res.send('Hello World!')
})
const PORT = process.env.PORT || 3000;
// CONNECTION MUST BE ONCE AT START!
mongoose.connect(
url, {},
(err) => {
if (err) {
console.error('DB: fail');
console.error(err.message);
process.exit(1);
}
console.log('DB: connected');
app.listen(PORT, () => console.log('blog server running on port', PORT));
});

Test a POST Http request from a local node server in REACT

I need to make unit tests for some post requests but i dont understand how.I tried with mswjs but the test passes because i'm missing something and i dont know what.I tried to test the requests in an usual way but i wasnt able to put my conditions there and it was sending only 200 status code..
To start with,this is my folder structure:
+main folder
++nodeServer
+++public
+++routes
++public
++src
+++tests
This is my try for testing the post request to /subscribe endpoint,where i should send an email as a payload and get the response that the payload was received succesefully.
subscribeFetch.test.js:
import {setupServer} from 'msw/node'
import {rest} from 'msw'
const handlers = [
rest.post("/api/subscribe",(req,res,context)=>{
if (!req.body || !req.body.email) {
return res(context.status(400).json({ error: "Wrong payload" }));
}
if (req.body.email === 'forbidden#email.com') {
return res(context.status(422).json({ error: "Email is already in use" }));
}
return res(
context.status(200),
context.json({email:'gigi#gmail.com'})
)
})
]
const server = setupServer(...handlers)
beforeAll(()=>server.listen())
afterAll(()=>server.close())
afterEach(()=>server.resetHandlers())
test('should send post request to the server',async()=>{
server.use(
rest.post('/api/subscribe',(req,res,ctx)=>{
return res(
expect (ctx.status()).toBe(200)
)
}
)
)
})
//export {handlers,rest}
This is the subscribe post request function that i need to test:
import { validateEmail } from './email-validator.js'
export const sendSubscribe = (emailInput) => {
const isValidEmail = validateEmail(emailInput)
if (isValidEmail === true) {
sendData(emailInput)
}
}
export const sendHttpRequest = (method, url, data) => {
return fetch(url, {
method: method,
body: JSON.stringify(data),
headers: data
? {
'Content-Type': 'application/json'
}
: {}
}).then(response => {
if (response.status >= 400) {
return response.json().then(errResData => {
const error = new Error('Something went wrong!')
error.data = errResData
throw error
})
}
return response.json()
})
}
const sendData = (emailInput) => {
sendHttpRequest('POST', '/api/subscribe', {
email: emailInput
}).then(responseData => {
return responseData
}).catch(err => {
console.log(err, err.data)
window.alert(err.data.error)
})
}
Files from the server:
app.js:
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const indexRouter = require('./routes/index');
const communityRouter = require('./routes/community');
const analyticsRouter = require('./routes/analytics');
const app = express();
global.appRoot = path.resolve(__dirname);
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/community', communityRouter);
app.use('/analytics', analyticsRouter);
module.exports = app;
index.js from routes folder in the server folder:
const express = require('express');
const router = express.Router();
const FileStorage = require('../services/FileStorage');
/* POST /subscribe */
router.post('/subscribe', async function (req, res) {
try {
if (!req.body || !req.body.email) {
return res.status(400).json({ error: "Wrong payload" });
}
if (req.body.email === 'forbidden#email.com') {
return res.status(422).json({ error: "Email is already in use" });
}
const data = {email: req.body.email};
await FileStorage.writeFile('user.json', data);
await res.json({success: true})
} catch (e) {
console.log(e);
res.status(500).send('Internal error');
}
});
/* GET /unsubscribe */
router.post('/unsubscribe', async function (req, res) {
try {
await FileStorage.deleteFile('user.json');
await FileStorage.writeFile('user-analytics.json', []);
await FileStorage.writeFile('performance-analytics.json', []);
await res.json({success: true})
} catch (e) {
console.log(e);
res.status(500).send('Internal error');
}
});
module.exports = router;
Please guys,help me write unit test for subscribe endpoint to match the conditions from index.js file from routes folder in the server folder,thank you in advance!
So,i got the expected result without any library,but i dont know if its a good aproach,but at least it works :
const app = require('../../../personal-website-server/app')
const request = require('supertest')
describe('POST /subscribe', () => {
it('should give 400 status code when email is empty', async () => {
const email = { email: '' }
const response = await request(app).post('/subscribe').send(email)
if (!request.body || !request.body.email) {
expect(response.status).toBe(400)
}
})
it('should give 422 status code when email is forbidden', async () => {
const email = { email: 'forbidden#gmail.com' }
const response = await request(app).post('/subscribe').send(email)
if (request.body === 'forbidden#gmail.com') {
expect(response.status).toBe(422)
}
})
it('should give 200 status code when email is valid', async () => {
const email = { email: 'gigi#gmail.com' }
const response = await request(app).post('/subscribe').send(email)
expect(response.error).toBe(false)
expect(response.status).toBe(200)
expect(response.body.body).not.toBeNull()
})
})

CRUD Node JS (Cannot Post)

I'm currently trying my hand at "basic authentication" for users. I can't now get a http response back to my query. The path of the request is 'AuthenticationService' --> 'UserService'. But from 'UserService' I can't get to 'UserRoute' and therefore not to 'httpServer'. The correct order should be: AuthenticationService -->UserService --->Userroute-->httpServer If I change in AuthenticationRoute.js router.post('/', authenticate); to router.post('/authenticate', authenticate) I get a http response, but I dont transmit any data....What do I have to do ?
UserService.js
async function authenticate({ username, password }) {
const user= User.find({userName:username} && {password:password})
/* const user = User.find(u => u.userName === so && u.password === password); */
if (user) {
const { password, ...userWithoutPassword } = user;
return userWithoutPassword;
}
}
module.exports = {
authenticate
}
UserRoute.js
var userService = require('./UserService')
router.post('/', authenticate);
function authenticate(req, res, next) {
userService.authenticate(req.body)
.then(user => user ? res.json(user) : res.status(400).json({ message: 'Username or password is incorrect' }))
.catch(err => next(err));
}
module.exports = router;
AuthenticationService.js
async function basicAuth(req, res, next) {
// make authenticate path public
if (req.path === '/') {
return next();
}
if (!req.headers.authorization || req.headers.authorization.indexOf('Basic ') === -1) {
return res.status(401).json({ message: 'Missing Authorization Header' });
}
// verify auth credentials
const base64Credentials = req.headers.authorization.split(' ')[1];
const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
const [username, password] = credentials.split(':');
console.log(username+password);
const user = await userService.authenticate({ username, password });
if (!user) {
return res.status(401).json({ message: 'Invalid Authentication Credentials' });
}
req.user=user
next();
}
module.exports = {
basicAuth
}
AuthenticationRoute.js
var express = require('express');
var router = express.Router();
var authenticationService=require('./AuthenticationService')
router.post('/authenticate', authenticationService.basicAuth);
module.exports=router;
httpServer.js
const userRoutes = require('./endpoints/user/UserRoute')
const authenticationRoutes= require('./endpoints/authentication/AuthenticationRoute')
var axios = require('axios');
app.use(authenticationRoutes);
app.use(userRoutes);
The request I try to send is:
POST http://localhost:8080/authenticate
Authorization: Basic YWRtaW46MTIz

How do i send a success status code to the front end using node.js?

I have recently started using node.js as my backend and I have successfully posted data to the database, the problem that I am facing now is telling the front end that data has been successfully saved. Below is my user route with all the things I have tried commented out.
import { Router } from 'express';
import { IUser } from '../models/user.model';
const User = require('../models/user.model');
// import bcrypt from 'bcrypt';
const bcrypt = require('bcrypt');
const bodyParser = require('body-parser');
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
const userRouter = Router();
userRouter.get('/', (req, res) => {
return res.json('This is the user route');
})
userRouter.post("/register", (req, res: any, next) => {
const user: IUser = new User({
email: res.email,
firstName: res.firstName,
lastName: res.lastName,
password: res.password,
displayName: res.displayName,
cellNumber: res.cellNumber,
});
user.save()
.then((result: any) => {
res.status(201).json({
message: 'Successfully created a new user!',
result: result
});
// res.sendCode(201);
// console.log(res);
// res.status(201).send("User has been successfully created");
//return 'User has been successfully created';
// return Object({ message: "User has been successfully created" });
// return res.status(201).send({
// message: "User has been successfully created",
// statusCode: 201
// })
// return res;
})
.catch((err: any) => {
res.status(500).json({
error: err
})
})
// bcrypt.hash(req.body.password, 10)
// .then((hash: string) => {
// const user = new User({
// email: req.body.email,
// firstName: req.body.firstName,
// lastName: req.body.lastName,
// password: hash,
// displayName: req.body.displayName,
// cellNumber: req.body.cellNumber,
// });
// user.save()
// .then((res: any) => {
// res.status(201).json({
// message: 'Successfully created a new user!',
// result: res
// });
// })
// .catch((err: any) => {
// debugger;
// res.status(500).json({
// error: Error
// })
// })
// })
})
export default userRouter;
which I then export to the server.ts file which is below
import express = require('express');
//import cors from 'cors';
const cors = require('cors');
const bodyParser = require('body-parser')
import { Router } from 'express';
import mongoose from "mongoose";
import "dotenv/config"
//routes
import userRouter from './routes/user.routes';
//Create a new express instance
const app: express.Application = express();
app.get('/', function (req, res) {
res.send('Hello World');
});
// //get router
// var router = express.Router();
//Database
mongoose.connect(`${process.env.MONGO_URI}`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => {
console.log("Connected to MongoDB")
})
.catch(() => {
console.log("Connection to Database has failed")
})
var corsOptions = {
origin: '*',
credentials: true,
methods: '*'
};
const routes = Router();
export default routes;
app.use(routes);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors(corsOptions));
app.use("/user", userRouter);
routes.use('/user', userRouter);
routes.use(cors(corsOptions));
//use cors middleware
// router.use(cors(options));
app.listen(3000, function () {
console.log('App is listening on port 3000!');
})
What is strange is that when I set breakpoints and analyse the res file, i can see the data that I would have posted from the front end. But the front end gets the 500 status code instead of the 201 that I want to be sending, even though it passes right over that code. I have googled the keys of my keyboard for three days now. So I am at a loss now.
All The latest changes can be found in the GitLab repository below
https://gitlab.com/ShanahJr/SuperiorBallers
You just need to make use of res variable provided by express.
Example -
module.exports.updateData = async (req, res, next) => {
try {
const data = await Editor.edit(req.body.query);
res.status(200).json({ "status": true, "result": 'Edit successful!' })
} catch (error) {
console.log(error)
res.status(200).json({ "status": false, "result": "Request Failed!" })
}
}
This statement - res.status(200).json({ "status": true, "result": 'Edit successful!' })
Nowadays, express also suggests using res.sendStatus(200) over res.status(200)
You can lookup for status codes here
Use res.status(201).send(), res.status().json usually gets blocked by http rules especially when you activate https

Nodejs App works locally but only two route is working on Heroku

Hello all first and foremost this issue may seem like a duplicate but it is not as I have gone through other SO post relating to mine but it still didnt help and hence the reason I am making another. Please I need help, I have a nodejs back-end that is working locally without any issue. I uploaded it to heroku and now only two routes is working. All other routes are not working. I am able register, login and add new users.
This is for my add users routes that is working both locally and on heroku.
import mongoose from 'mongoose';
import { Router } from 'express';
import bodyParser from 'body-parser';
import User from '../model/user';
import { authenticate } from '../middleware/authMiddleware';
export default({ config, db }) => {
let api = Router();
// '/v1/user/add' - Create
api.post('/add', authenticate, (req, res) => {
let newUser = new User();
newUser.username = req.body.username;
newUser.email = req.body.email;
newUser.phonenumber = req.body.phonenumber;
newUser.profilepicurlicUrl = req.body.profilepicurl;
newUser.save(err => {
if (err) {
res.status(500).json({ message: err });
return;
}
res.status(200).json(newUser);
});
});
This is for my register user and login user that is working both locally and on heroku
import mongoose from 'mongoose';
import { Router } from 'express';
import bodyParser from 'body-parser';
import passport from 'passport';
import config from '../config';
import Account from '../model/account';
import UserDataExt from './extensions/userData-ext';
import async from 'async';
import crypto from 'crypto';
import { generateAccessToken, respond, authenticate } from '../middleware/authMiddleware';
var nodeMailer = require('nodemailer');
export default ({ config, db }) => {
let api = Router();
// '/v1/account/register'
api.post('/register', (req, res) => {
UserDataExt.findUserByEmail(req.body.email, (err, userData) => {
if (err) {
res.status(409).json({ message: `An error occured: ${err.message}`});
return;
} else if (userData) {
res.status(300).json({ message: `Email ${req.body.email} is already registered`});
}
// else {
Account.register(new Account({username: req.body.email}), req.body.password, function(err, account) {
if(err) {
res.status(500).json({ message: err });
return;
}
console.log("Registering new account");
passport.authenticate('local', { session: false })(req, res, () => {
res.status(200).send('Successfully created new account');
});
});
// }
});
});
// '/v1/account/login'
api.post('/login', (req, res, next) => {
UserDataExt.findUserByEmail(req.body.email, (err, userData) => {
if (err) {
res.status(409).json({ message: `An error occured: ${err.message}`});
return;
} else {
next();
}
});
}, passport.authenticate('local', { session: false, scope: [] }), (err, req, res, next) => {
if (err) {
res.status(401).json({ message: `Password is incorrect`});
return;
}
}, generateAccessToken, respond);
This is for my category route that is not working on heroku, but is working locally
import mongoose from 'mongoose';
import { Router } from 'express';
import Category from '../model/category';
import bodyParser from 'body-parser';
import { authenticate } from '../middleware/authMiddleware';
export default({ config, db }) => {
let api = Router();
// /v1/category/add Create
api.post('/add', authenticate, (req, res) => {
let newCategory = new Category();
newCategory.submittedById = req.body.submittedById;
newCategory.categoryTitle = req.body.categoryTitle;
newCategory.categoryDescription = req.body.categoryDescription;
newCategory.recommended = req.body.recommended;
newCategory.save(err => {
if (err) {
res.status(500).json({message: err});
return;
}
res.status(200).json({message: 'Category saved successfully'});
});
});
// /v1/category/ Read
api.get('/', authenticate, (req, res) => {
Category.find({}, (err, category) => {
if (err) {
res.status(500).json({message: `An erro has occured ${err.message}`});
return;
}
res.status(200).json(category);
});
});
This is my authenticate middleware code
import jwt from 'jsonwebtoken';
import expressJwt from 'express-jwt';
const TOKENTIME = 60*60*24*90;
const SECRET = "#######";
let authenticate = expressJwt({ secret: SECRET });
let generateAccessToken = (req, res, next) => {
req.token = req.token || {};
req.token = jwt.sign ({
id: req.user.id,
}, SECRET, {
expiresIn: TOKENTIME // 90 days
});
next();
}
let respond = (req, res) => {
res.status(200).json({
user: req.user.username,
token: req.token,
id: req.user._id
});
}
module.exports = {
authenticate,
generateAccessToken,
respond
}

Categories