I need help with setting up a logout route in my express
backend. The idea is that when a user logs out, their JWT token should be stored in a blacklist
Mongo database to prevent reusing the same token for login.
The issue I'm facing is an error related to my blacklist
schema:
Type '{ type: StringConstructor; required: true; }' is causing a TypeScript error as it's not compatible with type 'string'.ts(2322) (property) token: { type: StringConstructor; required: true; }
This is how my blacklist
Mongo Schema looks like:
/* eslint-disable @typescript-eslint/no-unsafe-assignment */
/* eslint-disable @typescript-eslint/no-unsafe-call */
import mongoose, { Schema } from "mongoose";
import { BlacklistMongo } from "../types/blacklist";
const blacklistSchema: Schema<BlacklistMongo> = new mongoose.Schema({
token: {
type: String,
required: true
},
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}, { timestamps: true });
blacklistSchema.set('toJSON', {
transform: (_document, returnedObject) => {
returnedObject.id = returnedObject._id.toString();
delete returnedObject._id;
delete returnedObject.__v;
}
});
export default mongoose.model<BlacklistMongo>('Blacklist', blacklistSchema);
logoutRouter
:
import express from 'express';
import middleware from '../utils/middleware';
import { Response } from 'express';
import { BlacklistMongo } from '../types/blacklist';
import blacklist from '../models/blacklist';
const logoutRouter = express.Router();
logoutRouter.post('/', async (request, response, next) => {
try {
const token: string | null = middleware.getTokenFrom(request);
if (!token) {
throw new Error('Token not found');
}
const tokenid: Promise<string | Response> = middleware.tokenValidator(request, response);
if (tokenid instanceof Response) {
return tokenid;
}
const addedToken: BlacklistMongo = new blacklist({
token: token
});
await addedToken.save();
response.status(200).json('You have been successfully logged out!');
} catch (exception) {
next (exception);
}
});
export default logoutRouter;