-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuser.js
83 lines (61 loc) · 1.76 KB
/
user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
const express =require('express')
const router = express.Router();
const User = require('./Userschema.js');
const bcrypt = require('bcrypt');
//register
router.post('/register', async (req,res)=>{
try{
//generate new password
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(req.body.password, salt);
const newuser = new User({
username:req.body.username,
password:hashedPassword,
name:req.body.name,
phoneNumber:req.body.phoneNumber,
})
const user=await newuser.save();
res.status(200).json(user);
} catch(err){
res.status(500).json(err);
}
})
//update credentials of user
router.put("/:username", async (req, res) => {
if (req.body.password) {
try {
const salt = await bcrypt.genSalt(10);
req.body.password = await bcrypt.hash(req.body.password, salt);
} catch (err) {
return res.status(500).json(err);
}
}
try {
const user = await User.findOneAndUpdate({username:req.params.username}, {
$set: req.body,
});
res.status(200).json("Account has been updated");
} catch (err) {
return res.status(500).json(err);
}
});
//delete user
router.delete("/:username", async (req, res) => {
await User.findOneAndDelete({username:req.params.username}, (err, user) => {
if (!err) {
res.json({ msg: "customer deleted", deleted: user });
} else {
console.log("Error:" + err);
}
});
});
//get a user
router.get("/:username", async (req, res) => {
try {
const user = await User.find({username:req.params.username});
res.status(200).json(user);
} catch (err) {
res.status(500).json(err);
}
});
module.exports =router;