-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathserver.js
167 lines (153 loc) · 5.3 KB
/
server.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
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
const couchbase = require('couchbase')
const express = require('express')
const uuid = require('uuid')
const bodyParser = require('body-parser')
const bcrypt = require('bcryptjs')
const cors = require('cors')
const app = express()
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
const cluster = new couchbase.Cluster('couchbase://localhost', {
username: 'Administrator', password: 'password'
})
const bucket = cluster.bucket('blog')
const collection = bucket.defaultCollection()
// validation middleware
const validate = async(request, response, next) => {
const authHeader = request.headers["authorization"]
if (authHeader) {
bearerToken = authHeader.split(" ")
if (bearerToken.length == 2) {
await collection.get(bearerToken[1])
.then(async(result) => {
request.pid = result.value.pid
await collection.touch(bearerToken[1], 3600)
.then(() => next())
.catch((e) => console.error(e.message))
})
.catch((e) => response.status(401).send({ "message": "Invalid session token" }))
}
} else {
response.status(401).send({ "message": "An authorization header is required" })
}
}
// create account endpoint
app.post("/account", async (request, response) => {
if (!request.body.email && !request.body.password) {
return response.status(401).send({ "message": "An `email` and `password` are required" })
} else if (!request.body.email || !request.body.password) {
return response.status(401).send({
"message": `A ${!request.body.email ? '`email`' : '`password`'} is required`
})
}
const id = uuid.v4()
const account = {
"type": "account",
"pid": id,
"email": request.body.email,
"password": bcrypt.hashSync(request.body.password, 10)
}
const profile = {
"type": "profile",
"email": request.body.email
}
await collection.insert(id, profile)
.then(async () => {
await collection.insert(request.body.email, account)
.then((result) => {
result.pid = id
return response.send(result)
})
.catch(async (e) => {
await collection.remove(id)
.then(() => {
console.error(`account creation failed, removed: ${id}`)
return response.status(500).send(e)
})
.catch(e => response.status(500).send(e))
})
})
.catch(e => response.status(500).send(e))
})
// login user endpoint
app.post("/login", async (request, response) => {
if (!request.body.email && !request.body.password) {
return response.status(401).send({ "message": "An `email` and `password` are required" })
} else if (!request.body.email || !request.body.password) {
return response.status(401).send({
"message": `A ${!request.body.email ? '`email`' : '`password`'} is required`
})
}
await collection.get(request.body.email)
.then(async (result) => {
if (!bcrypt.compareSync(request.body.password, result.value.password)) {
return response.status(500).send({ "message": "Password invalid" })
}
var session = {
"type": "session",
"id": uuid.v4(),
"pid": result.value.pid
}
await collection.insert(session.id, session, { "expiry": 3600 })
.then(() => response.send({ "sid": session.id }))
.catch(e => response.status(500).send(e))
})
.catch(e => response.status(500).send(e))
})
// validate account endpoint
app.get("/account", validate, async (request, response) => {
try {
await collection.get(request.pid)
.then((result) => response.send(result.value))
.catch((e) => response.status(500).send(e))
} catch (e) {
console.error(e.message)
}
})
// create blog endpoint
app.post("/blog", validate, async(request, response) => {
if (!request.body.title && !request.body.content) {
return response.status(401).send({ "message": "A `title` and `content` are required for each blog post" })
} else if (!request.body.title || !request.body.content) {
return response.status(401).send({
"message": `A ${!request.body.title ? '`title`' : '`content`'} is required for each blog post`
})
}
var blog = {
"type": "blog",
"pid": request.pid,
"title": request.body.title,
"content": request.body.content,
"timestamp": (new Date()).getTime()
}
const uniqueId = uuid.v4()
collection.insert(uniqueId, blog)
.then(() => response.send(blog))
.catch((e) => response.status(500).send(e))
})
// get blog posts endpoint
app.get("/blogs", validate, async(request, response) => {
try {
const query = `SELECT * FROM \`blog\` WHERE type = 'blog' AND pid = $PID;`
const options = { parameters: { PID: request.pid } }
await cluster.query(query, options)
.then((result) => {
console.log(result.rows)
response.send(result.rows)
})
.catch((e) => response.status(500).send(e))
} catch (e) {
console.error(e.message)
}
})
// get profile endpoint (bonus example, not covered in tutorial)
app.get("/profile/:pid", async(request, response) => {
try {
const result = await collection.get(request.params.pid)
response.send(result)
} catch (e) {
return response.status(500).send(e.message)
}
})
const server = app.listen(3000, () => console.info(`Running on port ${server.address().port}...`))