-
Notifications
You must be signed in to change notification settings - Fork 10
/
auth.js
59 lines (51 loc) · 1.46 KB
/
auth.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
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
import User from "../models/User.js";
/* REGISTER USER */
export const register = async (req, res) => {
try {
const {
firstName,
lastName,
email,
password,
picturePath,
friends,
location,
occupation,
} = req.body;
const salt = await bcrypt.genSalt();
const passwordHash = await bcrypt.hash(password, salt);
const newUser = new User({
firstName,
lastName,
email,
password: passwordHash,
picturePath,
friends,
location,
occupation,
viewedProfile: Math.floor(Math.random() * 10000),
impressions: Math.floor(Math.random() * 10000),
});
const savedUser = await newUser.save();
res.status(201).json(savedUser);
} catch (err) {
res.status(500).json({ error: err.message });
}
};
/* LOGGING IN */
export const login = async (req, res) => {
try {
const { email, password } = req.body;
const user = await User.findOne({ email: email });
if (!user) return res.status(400).json({ msg: "User does not exist. " });
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) return res.status(400).json({ msg: "Invalid credentials. " });
const token = jwt.sign({ id: user._id }, process.env.JWT_SECRET);
delete user.password;
res.status(200).json({ token, user });
} catch (err) {
res.status(500).json({ error: err.message });
}
};