Skip to content
Snippets Groups Projects

Create endpoint for user-registration

1 unresolved thread
Compare and Show latest version
6 files
+ 188
4
Compare changes
  • Side-by-side
  • Inline
Files
6
import UserModel from '../model/User.model.js';
import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';
import ENV from '../config.js'
// Middleware
export async function verifyUser(req,res, next){
try{
const { username } = req.method == 'GET' ? req.query : req.body;
// Check if user exists
let exist = await UserModel.findOne( {username } );
if(!exist) return res.status(404).send({ error: "Can't find User"});
next();
} catch (error) {
return res.status(404).send({ error: "Authentication Error"})
}
}
/** POST: http://localhost:8080/api/register
* @param : {
@@ -74,5 +94,100 @@ export async function register(req,res){
}
*/
export async function login(req,res){
res.json('login route')
}
\ No newline at end of file
const { username, password } = req.body;
try {
UserModel.findOne({ username })
.then(user => {
bcrypt.compare(password, user.password)
.then(passwordCheck => {
if(!passwordCheck) return res.status(400).send({ error: "Don't have Password"});
// create jwt token
const token = jwt.sign({
userId: user._id,
username : user.username
}, ENV.JWT_SECRET , { expiresIn : "24h"});
return res.status(200).send({
msg: "Login Successful...!",
username: user.username,
token
});
})
.catch(error =>{
return res.status(400).send({ error: "Password does not Match"})
})
})
.catch( error => {
return res.status(404).send({ error : "Username not Found"});
})
} catch (error) {
return res.status(500).send({ error});
}
}
export async function getUser(req,res){
const { username } = req.params;
try {
if(!username) return res.status(501).send({error: "Invalid Username"});
UserModel.findOne({username}, function(err, user){
if(err) return res.status(500).send({err});
if(!user) return res.status(501).send({ error: "Couldn't find the User"});
const { password, ...rest } = Object.assign({}, user.toJSON());
return res.status(201).send(rest)
})
}catch(err) {
return res.status(404).send({ error: "Cannot find User Data"});
}
}
/** PUT: http://localhost:8080/api/updateuser
*
. * @param: {
"header" : "<token>"
}
body: {
firstName: '',
address : '',
profile : ''
}
*/
export async function updateUser(req,res){
try {
const id = req.query.id;
if(id){
const body = req.body;
// update the data
UserModel.updateOne({ _id : id }, body, function(err, data){
if(err) throw err;
return res.status(201).send({ msg : "Record Updated...!"});
})
}else{
return res.status(401).send({ error : "User Not Found...!"});
}
} catch (error) {
return res.status(401).send({ error });
}
}
Loading