users.js
2.28 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const bcrypt = require("bcryptjs");
const User = require("../../models/User");
const jwt = require("jsonwebtoken");
const { SECRET_KEY } = require("../../config");
const { UserInputError } = require("apollo-server");
const {
validateRegisterInput,
validateLoginInput
} = require("../../util/validators");
function generateToken(user) {
return jwt.sign(
{
id: user.id,
email: user.email,
username: user.username
},
SECRET_KEY,
{ expiresIn: "1h" }
);
}
module.exports = {
Mutation: {
async login(_, { username, password }) {
const { errors, valid } = validateLoginInput(username, password);
if (!valid) {
throw new UserInputError("Errors", { errors });
}
const user = await User.findOne({ username });
if (!user) {
errors.general = "User not found";
throw new UserInputError("User not found", { errors });
}
const match = await bcrypt.compare(password, user.password);
if (!match) {
errors.general = "Wrong credentials";
throw new UserInputError("Wrong credentials", { errors });
}
const token = generateToken(user);
return {
...user._doc,
id: user._id,
token
};
},
async register(
_,
{ registerInput: { username, email, password, confirmPassword } }
) {
// TODO: Validate user data
const { errors, valid } = validateRegisterInput(
username,
email,
password,
confirmPassword
);
if (!valid) {
throw new UserInputError("Errors", { errors });
}
// TODO: Make sure user doesnt already exist
const user = await User.findOne({ username });
if (user) {
throw new UserInputError("Username is taken", {
errors: {
username: "The username is taken"
}
});
}
// TODO: hash password and create an auth token
password = await bcrypt.hash(password, 12);
const newUser = new User({
email,
username,
password,
createdAt: new Date().toISOString()
});
const res = await newUser.save();
const token = generateToken(res);
return {
...res._doc,
id: res._id,
token
};
}
}
};