Reputation: 147
I have a register and a login in an auth.ts. I currently test it with postman. The library I use is crypto-js and I used it before in node, but this time I am using the first time TypeScript. I have installed @types/crypto-js. When I register, the correct Data is set into MongoDb. The encrypted password, that postman populates is the same as mongo displays. But when I login, postman throws the error "wrong password". I log all password const out of the file and the const inputPassword shows the correct password, but const originalPassword shows it wrong. Although it only contains numbers that I used in the password, they are in arbitrary order and the password is twice as long. I googeled this, but found no answer. Clearing cache brought no solution.
Here my auth.ts:
import { Router, Request, Response } from "express";
const authRouter = Router();
const CryptoJS = require('crypto-js');
import * as jwt from 'jsonwebtoken';
import User from "../models/user";
//register
authRouter.post('/register', async (request:Request, response:Response)=>{
const newUser = new User({
vorname:request.body.vorname,
nachname:request.body.nachname,
email:request.body.email,
username:request.body.username,
street:request.body.street,
number:request.body.number,
plz:request.body.plz,
city:request.body.city,
password: CryptoJS.AES.encrypt(
request.body.password,
process.env.PASS_SEC
).toString(),
});
try{
const savedUser = await newUser.save();
response.status(200).json(savedUser);
} catch(error){
response.status(403)
throw new Error('Action failed');
}
});
//login
authRouter.post('/login', async (request:Request, response:Response)=>{
let sec:string = process.env.JWT_SEC as string;
try{
const user = await User.findOne({username:request.body.username});
if(!user){
return response.status(401).json("Wrong credentials");
}
const hashedPassword = CryptoJS.AES.decrypt(user?.password, process.env.PASS_SEC);
console.log(hashedPassword);
const originalPassword = hashedPassword.toString(CryptoJS.enc.UTF8);
console.log(originalPassword);
const inputPassword = request.body.password;
console.log(inputPassword);
if(originalPassword != inputPassword){
return response.status(401).json("Wrong password");
} else {
const accessToken = jwt.sign(
{id: user!._id,
isAdmin:user!.isAdmin,
},
sec,
{expiresIn:"30d"}
)
const {password, ...others} = user?._doc;
response.status(200).json({...others, accessToken});
}
} catch(error:any){
response.status(401)
throw new Error(error)
}
});
export default authRouter;
Upvotes: 0
Views: 196
Reputation: 147
I close this question, because I have thrown out crypto-js and use bcrypt, like Evert suggested it. Now it works.
Upvotes: 1