Skip to content

Commit

Permalink
Converted Token Generator and Updated Login (#11)
Browse files Browse the repository at this point in the history
  • Loading branch information
Nyumat committed Jan 7, 2023
1 parent 0ab2176 commit 5f175c6
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 20 deletions.
7 changes: 6 additions & 1 deletion backend/routes/auth/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,12 @@ router.post("/", async (req, res) => {
user.updatedAt = new Date();
await user.save();

const token = generateAuthToken(user);
const token = generateAuthToken({
_id: user._id,
username: user.username,
key: process.env.JWT_SECRET_KEY as string
});

res.status(200).json({
msg: `User ${user.username} logged in successfully!`,
token: token
Expand Down
19 changes: 0 additions & 19 deletions backend/utils/generateToken.js

This file was deleted.

29 changes: 29 additions & 0 deletions backend/utils/generateToken.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import jwt, { Secret } from "jsonwebtoken";
import dotenv from "dotenv";
import User from "../models/user.js";

dotenv.config();

export interface UserTokenGenerator {
_id: string;
username: string;
key: Secret;
}

const generateAuthToken = (user: UserTokenGenerator) => {
if (!process.env.JWT_SECRET_KEY) {
throw new Error("JWT_SECRET_KEY is not defined.");
}
const jwtSecretKey = process.env.JWT_SECRET_KEY as Secret;
const token = jwt.sign(
{
_id: user._id,
username: user.username
},
jwtSecretKey
);

return token;
};

export default generateAuthToken;
File renamed without changes.

0 comments on commit 5f175c6

Please sign in to comment.