while I am using bcrypt.js hashSync is not accepting numbers or symbols in password, if I pass string as value of password from postman only then it works otherwise it throws error 500 along with message "Illegal arguments: undefined, string\n at bcrypt.hashSync".
I also tried const hash = await bcrypt.hashSync(req.body.password, salt, { encoding: "utf8" }); it didn't work either.
my auth.js code is
import User from "../models/User.js";
import bcrypt from "bcryptjs";
import { createError } from "../utils/error.js";
import jwt from "jsonwebtoken";
export const register = async (req, res, next) => {
try {
const salt =await bcrypt.genSaltSync(10);
const hash =await bcrypt.hashSync(req.body.password, salt);
const newUser = new User({
...req.body,
password: hash,
});
await newUser.save();
res.status(200).send("User has been created.");
} catch (err) {
next(err);
}
};
export const login = async (req, res, next) => {
try {
const user = await User.findOne({ username: req.body.username });
if (!user) return next(createError(404, "User not found!"));
const isPasswordCorrect = await bcrypt.compare(
req.body.password,
user.password
);
if (!isPasswordCorrect)
return next(createError(400, "Wrong password or username!"));
const token = jwt.sign(
{ id: user._id, isAdmin: user.isAdmin },
process.env.JWT
);
const { password, isAdmin, ...otherDetails } = user._doc;
res
.cookie("access_token", token, {
httpOnly: true,
})
.status(200)
.json({ details: { ...otherDetails }, isAdmin });
} catch (err) {
next(err);
}
};
I am trying to use numbers and symbols along with text for password
Related
When I post the data for my Auth the console throws this error ** 500 (Internal Server Error) ** I think the problem is with my server, first check the database and the data is in the cluster
but the data does not work in my client. I know that this type of problem is often on the server. I've been searching for several hours and I can't figure it out.
This is the index
import express from 'express';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import cors from 'cors';
import postRoutes from './routes/posts.js';
import userRoutes from './routes/users.js';
const app = express();
app.use(bodyParser.json({ limit: '30mb', extended: true }))
app.use(bodyParser.urlencoded({ limit: '30mb', extended: true }))
app.use(cors());
app.use('/posts', postRoutes);
app.use('/users', userRoutes);
const CONNECTION_URL = '**THIS_IS_MY_MONGO_DB;
const PORT = process.env.PORT|| 5000;
mongoose.connect(CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => app.listen(PORT, () => console.log(`Server Running on Port: http://localhost:${PORT}`)))
.catch((error) => console.log(`${error} did not connect`));
mongoose.set('useFindAndModify', false);
The users.js route
import express from 'express';
import { signin, signup } from '../controllers/user.js';
const router = express.Router();
router.post('/signin', signin);
router.post('/signup', signup);
export default router;
The user controller
import bcrypt from "bcryptjs";
import jwt from "jsonwebtoken";
import User from "../models/user.js";
export const signin = async (req, res) => {
const { email, password} = req.body;
try {
const existingUser = await User.findOne({ email });
if(!existingUser) return res.status(404).json({ message: "El usuaruio no existe."});
const isPasswordCorrect = await bcrypt.compare(password, existingUser.password);
if(!isPasswordCorrect) return res.status(400).json({ message: "Credenciales invalidas."});
const token = jwt.sing({ email: existingUser.email, id: existingUser._id }, 'test', { expiresIn: "1h" });
res.status(200).json({ result: existingUser, token});
} catch (error) {
res.status(500).json({ message: 'Algo salio mal.' });
}
}
export const signup = async (req, res) => {
const { email, password, confirmPassword, firstName, lastName } = req.body;
try {
const existingUser = await User.findOne({ email });
if(existingUser) return res.status(400).json({ message: "El usuaruio ya existe."});
if(password !== confirmPassword) return res.status(400).json({ message: "Las contraseñas no coinciden."});
const hashedPassword = await bcrypt.hash(password, 12);
const result = await User.create({ email, password: hashedPassword, name: `${firstName} ${lastName}` })
const token = jwt.sing({ email: result.email, id: result._id }, 'test', { expiresIn: "1h" });
res.status(200).json({ result, token});
} catch (error) {
res.status(500).json({ message: 'Algo salio mal.' });
}
}
The index api
import axios from 'axios';
const API = axios.create({ baseURL: 'http://localhost:5000' })
export const fetchPosts = () => API.get('/posts');
export const createPost = (newPost) => API.post('/posts', newPost);
export const likePost = (id) => API.patch(`/posts/${id}/likePost`);
export const updatePost = (id, updatedPost) => API.patch(`/posts/${id}`, updatedPost);
export const deletePost = (id) => API.delete(`/posts/${id}`);
export const signIn = (formData) => API.post('/users/signin', formData);
export const signUp = (formData) => API.post('/users/signup', formData);
export const signup = async (req, res) => {
const { email, password, confirmPassword, firstName, lastName } = req.body;
try {
const existingUser = await User.findOne({ email });
if(existingUser) return res.status(400).json({ message: "El usuaruio ya existe."});
if(password !== confirmPassword) return res.status(400).json({ message: "Las contraseñas no coinciden."});
const hashedPassword = await bcrypt.hash(password, 12);
const result = await User.create({ email, password: hashedPassword, name: `${firstName} ${lastName}` })
// you have typo in next line
const token = jwt.sing({ email: result.email, id: result._id }, 'test', { expiresIn: "1h" });
// replace it by:
const token = jwt.sign({ email: result.email, id: result._id }, 'test', { expiresIn: "1h" });
res.status(200).json({ result, token});
} catch (error) {
res.status(500).json({ message: 'Algo salio mal.' });
}
}
I have a auth.js file And a middleware named as fetchuser code given beolow
Can anyone please tell me why am i getting this error.
I am using express js and mongoose but this error is occured during sending token to the user and verify the user whether is user logged in or not.
auth.js
const express = require('express');
const User = require('../models/User');
const router = express.Router();
const { body, validationResult } = require('express-validator');
const bcrypt = require('bcryptjs'); // it is used for password hashing
const jwt = require('jsonwebtoken');
const fetchuser=require('../middleware/fetchuser');
// Route:1 - Create a User using :POST. "/api/auth/createuser". NO Login Required.
router.post('/createuser', [
body('email', 'Enter valid email').isEmail(),
body('name', 'Enter valid email').isLength({ min: 3 }),
body('password').isLength({ min: 5 })
], async (req, res) => {
// Check fo vaidation whether is any rule(defined in User model) breaked or not
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// Check Whether user with same email id exist or not
try {
let user = await User.findOne({ email: req.body.email });
if (user) {
return res.status(400).json({ error: "Sorry user with same email id already exist" });
}
// hashing of password
const salt = await bcrypt.genSalt(10);
const securePassword = await bcrypt.hash(req.body.password, salt);
// create A new User
user = await User.create({
name: req.body.name,
email: req.body.email,
password: securePassword
})
// returning user id in Token
const JWT_secret = "Rishiisa#boy";
const data = { user:{id: user.id} };
const auth_token = jwt.sign(data, JWT_secret);
res.json({ auth_token });
}
catch (error) {
console.error(error.message);
res.status(500).send("Internal server error");
}
})
// Route:2 - Login a User using credential. "/api/auth/login". NO Login Required.
router.post('/login', [
body('email', 'Enter valid email').isEmail(),
body('password', 'password can not be blank').exists(),
], async (req, res) => {
// Check for vaidation according to the rule defined at line no. 53, 54;
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
// destructure the email and password from body request
const { email, password } = req.body;
try {
// Checking whether email is exist or not
let user = await User.findOne({ email });
if (!user) {
return res.status(400).json({ error: "Please try to login using correct credentials" });
}
// Now Comparing password with help of bcryptjs
const comparepassword = await bcrypt.compare(password, user.password);
if (!comparepassword) {
return res.status(400).json({ error: "Please try to login using correct credentials" });
}
// Now if user enter coorect password and login then user got logged in;
// And We will send authtoken to user;
// returning user id in Token
const JWT_secret = "Rishiisa#boy";
const data = { user:{id: user.id} };
const auth_token = jwt.sign(data, JWT_secret);
res.json({ auth_token });
}
catch (error) {
console.error(error.message);
res.status(500).send("Internal server error");
}
})
// Route:3 - Get Loggedin User details using:POST "/api/auth/getuser" Login required
router.post('/getuser', fetchuser, async (req, res) => {
try {
const userid = req.user.id;
const user = await User.findById(userid).select("-password");
res.send(user);
} catch (error) {
console.error(error.message);
res.status(500).send("Internal server error");
}
})
module.exports = router
middleware:
fetchuser.js
const jwt = require('jsonwebtoken');
const JWT_secret = "Rishiisa#boy";
const fetchuser = (req, res, next) => {
// Get the user from jwt token and add user id to req object
const token = req.header('auth_token');
if (!token) {
res.status(401).send({ error: "Please authenticate using a valid token" });
}
try {
const data = jwt.verify(token, JWT_secret);
req.user = data.user;
next();
} catch (error) {
res.status(401).send({ error: "Please authenticate using a valid token" });
}
}
module.exports = fetchuser;
In auth.js, where you wrote: "const data = { user:{id: user.id} };" Try changing user.id to user._id, since in MongoDB the user id is referred to as '_id'.
Let me know if that works.
I've had problems sending jwt token back and even verifying it, but all is good on my side now.
Also, below is my (inspired) method of going about this:
router.post('/register', (req, res)=>{
const { username, password } = req.body;
const user = new User({
username,
password
});
bcrypt.genSalt(10, (err, salt)=>{
bcrypt.hash(user.password, salt, (err, hash)=>{
if(err) throw err;
user.password = hash;
user.save()
.then(user=>{
jwt.sign(
{ id: user._id },
process.env.jwtSecret,
{ expiresIn: 3600 },
(err, token) =>{
if(err) throw err;
res.status(200)
}
)
})
})
})
})
I am working through an authentication application from devchallenges.io. So far, I've been able to set up the basic login with email and password. I'm now trying to set up google login auth. When testing the server with Postman I get the error Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client. The app seems to stills work as a json web token is returned so not too sure why I'm getting this error.
server.js
// #route POST auth/google
// #desc auth user with google
// #access Public
app.post('/auth/google', (req, res) => {
const { token } = req.body;
const CLIENT_ID =
'1068367393637-jtuoidgq5mi5krd5q31u9ncjovt3fvgh.apps.googleusercontent.com';
const client = new OAuth2Client(CLIENT_ID);
let { email, name, picture, password } = '';
async function verify() {
const ticket = await client.verifyIdToken({
idToken: token,
audience: CLIENT_ID,
});
const payload = ticket.getPayload();
const userid = payload['sub'];
email = payload.email;
name = payload.name;
picture = payload.picture;
password = generator.generateMultiple({
length: 6,
});
try {
// See if user exists
let user = await AuthUser.findOne({ email });
if (user) {
// Return jsonwebtoken
const payload = {
user: {
id: user.id,
},
};
jwt.sign(
payload,
config.get('jwtSecret'),
{ expiresIn: '5 days' },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
}
user = new AuthUser({
name,
email,
picture,
password,
});
// Encrypt password
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
// Return jsonwebtoken
const payload = {
user: {
id: user.id,
},
};
jwt.sign(
payload,
config.get('jwtSecret'),
{ expiresIn: '5 days' },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} catch (error) {
console.error(error.message);
res.status(500).send('Server error');
}
}
verify().catch(console.error);
});
All I had to do was add an else conditional statement.
if (user) {
// Return jsonwebtoken
const payload = {
user: {
id: user.id,
},
};
jwt.sign(
payload,
config.get('jwtSecret'),
{ expiresIn: '5 days' },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
} else {
user = new AuthUser({
name,
email,
picture,
password,
});
// Encrypt password
const salt = await bcrypt.genSalt(10);
user.password = await bcrypt.hash(password, salt);
await user.save();
// Return jsonwebtoken
const payload = {
user: {
id: user.id,
},
};
jwt.sign(
payload,
config.get('jwtSecret'),
{ expiresIn: '5 days' },
(err, token) => {
if (err) throw err;
res.json({ token });
}
);
}
I created Sign up and sign in function in node.js. I am able to sign up user using postman for testing but when I sign in, user, it return error message that I set up. I can't trace what is the problem currently. Can you please help?
export const signin = async (req, res) => {
const { email, password } = req.body;
try {
const oldUser = await UserModal.findOne({ email });
if (!oldUser) return res.status(404).json({ message: "User doesn't exist" });
const isPasswordCorrect = await bcrypt.compare(password, oldUser.password);
if (!isPasswordCorrect) return res.status(400).json({ message: "Invalid credentials" });
const token = jwt.sign({ email: oldUser.email, id: oldUser._id }, secret, { expiresIn: "1h" });
res.status(200).json({ result: oldUser, token });
} catch (err) {
res.status(500).json({ message: "Something went wrong" });
}
};
below is the sign up function...
export const signup = async (req, res) => {
const { email, password, firstName, lastName } = req.body;
try {
const oldUser = await UserModal.findOne({ email });
if (oldUser) return res.status(400).json({ message: "User already exists" });
const hashedPassword = await bcrypt.hash(password, 12);
const result = await UserModal.create({ email, password: hashedPassword, name: `${firstName} ${lastName}` });
const token = jwt.sign( { email: result.email, id: result._id }, secret, { expiresIn: "1h" } );
res.status(201).json({ result, token });
} catch (error) {
res.status(500).json({ message: "Something went wrong" });
console.log(error);
}
};
I am new to MERN stack development and trying the JWT authentication. During this I am facing that my server is not working they crashed every time.
Yesterday It was working but today It's not working. Now they are showing this error.
This is error showing on console
MissingSchemaError: Schema hasn't been registered for model "users".
Here is my Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
avatar: {
type: String
},
date: {
type: Date,
default: Date.now
}
});
const User = mongoose.model('users', UserSchema);
module.exports = User;
This code is in the routes folder - user.js file
// user.js
const express = require('express');
const router = express.Router();
const gravatar = require('gravatar');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const passport = require ('passport');
const validateRegisterInput = require('../validation/register');
const validateLoginInput = require('../validation/login');
const User = require('../models/User');
//Register Post Router
router.post('/register', function(req, res){
const {errors, isValid} = validateRegisterInput(req.body);
if(!isValid){
return res.status(400).json(errors);
}
User.findOne({
email: req.body.email
}).then(user => {
if(user){
return res.status(400).json({
email: 'Email already exists'
});
}
else {
const avatar = gravatar.url(req.body.email, {
s: '200',
r: 'pg',
d: 'mm'
});
const newUser = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
avatar
});
bcrypt.genSalt(10, (err, salt) => {
if(err)
console.error('There was an error', err);
else{
bcrypt.hash(newUser.password, salt, (err, hash) => {
if(err)
console.error('There was an error', err);
else{
newUser.password = hash;
newUser
.save()
.then(user => {
res.json(user)
});
}
});
}
});
}
});
});
//Login Post Router
router.post('/login', (req, ress) => {
const {errors, isValid} = validateLoginInput(req.body);
if(isValid){
return res.status(400).json(errors);
}
const email = req.body.email;
const password = req.body.password;
User.findOne({email})
.then(user => {
if(!user) {
errors.email = 'User not found'
return res.status(404).json(errors);
}
bcrypt.compare(password, user.password)
.then(isMatch => {
if(isMatch){
const payload = {
id: user.id,
name: user.name,
avatar: user.avatar
}
jwt.sign(payload, 'secret', {
expiresIn: 3600
}, (err, token) => {
if(err)
console.error('There is some error in token', err);
else{
res.json({
success: true,
token: `Bearer ${token}`
});
}
});
}
else{
errors.password = 'Incorrect Password';
return
res.status(400).json(errors);
}
});
});
});
router.get('/me', passport.authenticate('jwt', {session: false}), (req, res) => {
return res.json({
id: req.user.id,
name: req.user.name,
email: req.user.email
});
});
module.exports = router;