forked from danielstern/express-react-fullstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathauthenticate.js
More file actions
68 lines (53 loc) · 1.81 KB
/
authenticate.js
File metadata and controls
68 lines (53 loc) · 1.81 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
import uuid from 'uuid';
import md5 from 'md5';
import { connectDB } from './connect-db'
import { assembleUserState } from './utility';
const authenticationTokens = [];
export const authenticationRoute = app => {
app.post('/authenticate',async (req,res)=>{
let { username, password } = req.body;
let db = await connectDB();
let collection = db.collection(`users`);
let user = await collection.findOne({name:username});
if (!user) {
return res.status(500).send(`User not found`);
}
let hash = md5(password);
let passwordCorrect = hash === user.passwordHash;
if (!passwordCorrect) {
return res.status(500).send('Password incorrect');
}
let token = uuid();
authenticationTokens.push({
token,
userID: user.id
});
let state = await assembleUserState(user);
res.send({token,state});
});
app.post('/user/create',async(req,res)=>{
let {username,password} = req.body;
console.log(username,password);
let db = await connectDB();
let collection = db.collection(`users`);
let user = await collection.findOne({name:username});
if (user) {
res.status(500).send({message:"A user with that account name already exists."});
return;
};
let userID = uuid();
let groupID = uuid();
await collection.insertOne({
name:username,
id:userID,
passwordHash:md5(password)
});
await db.collection(`groups`).insertOne({
id:groupID,
owner:userID,
name: `To Do`
});
let state = await assembleUserState({id:userID,name:username});
res.status(200).send({userID,state});
});
};