This repository has been archived by the owner on Jun 20, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.ts
215 lines (184 loc) · 5.84 KB
/
api.ts
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import type { AuthRequestHandler } from '../auth'
import type { Context } from '../types'
import type { RequestHandler } from 'express'
import type { WithId } from 'mongodb'
import { prepareAccount } from './http'
import { password as validatePassword } from '../validate'
import type { Account, AccountCreate, AccountUpdate } from './types'
import { http, validate as v } from '@edge/misc-utils'
/** Create an account. */
export function createAccount({ model }: Context): RequestHandler {
interface RequestData {
account: AccountCreate
}
interface ResponseData {
account: WithId<Partial<Account>>
}
const readRequestData = v.validate<RequestData>({
account: {
email: v.email,
password: validatePassword,
},
})
return async function (req, res, next) {
try {
const input = readRequestData(req.body)
const account = await model.account.create(input.account)
if (!account) return http.notFound(res, next, { reason: 'unexpectedly failed to get new account' })
const output: ResponseData = { account: prepareAccount(account) }
res.send(output)
next()
} catch (err) {
const name = (err as Error).name
if (name === 'ValidateError') {
const ve = err as v.ValidateError
return http.badRequest(res, next, { param: ve.param, reason: ve.message })
}
return next(err)
}
}
}
/** Delete an account. */
export function deleteAccount({ model }: Context): AuthRequestHandler {
interface ResponseData {
account: WithId<Partial<Account>>
herds: {
deletedCount: number
}
tasks: {
deletedCount: number
}
}
return async function (req, res, next) {
if (!req.account) return http.unauthorized(res, next)
// Get account ID and assert access
const id = req.params.id || req.account._id
if (!id) return http.badRequest(res, next)
if (!req.account._id.equals(id)) return http.forbidden(res, next)
try {
// Delete account
const { account, deletedHerds, deletedTasks } = await model.account.delete(id)
if (!account) return http.notFound(res, next)
// Send output
const output: ResponseData = {
account: prepareAccount(account),
herds: {
deletedCount: deletedHerds,
},
tasks: {
deletedCount: deletedTasks,
},
}
res.send(output)
next()
} catch (err) {
next(err)
}
}
}
/** Get an account. */
export function getAccount(): AuthRequestHandler {
interface ResponseData {
account: WithId<Partial<Account>>
}
return async function (req, res, next) {
if (!req.account) return http.unauthorized(res, next)
// Get account ID and assert access
const id = req.params.id || req.account._id
if (!req.account._id.equals(id)) return http.forbidden(res, next)
try {
// Send output
const output: ResponseData = { account: prepareAccount(req.account) }
res.send(output)
next()
} catch (err) {
return next(err)
}
}
}
/**
* Log in to an account.
* The token returned should be added to the authorization header of subsequent requests.
*/
export function loginAccount({ auth, model }: Context): RequestHandler {
interface RequestData {
account: Pick<Account, 'email' | 'password'>
}
interface ResponseData {
token: string
account: WithId<Partial<Account>>
}
const readRequestData = v.validate<RequestData>({
account: {
email: v.email,
password: v.seq(v.minLength(8)),
},
})
return async function (req, res, next) {
try {
// Read input
const input = readRequestData(req.body)
// Get account
const account = await model.account.collection.findOne({ email: input.account.email })
if (!account) return http.notFound(res, next)
// Validate password
const password = model.account.hashPassword(input.account.password, account.passwordSalt)
if (password !== account.password) return http.badRequest(res, next, { reason: 'invalid password' })
// Create JWT
const token = await auth.sign(account._id)
// Send output
const output: ResponseData = { token, account: prepareAccount(account) }
res.send(output)
next()
} catch (err) {
const name = (err as Error).name
if (name === 'ValidateError') {
const ve = err as v.ValidateError
return http.badRequest(res, next, { param: ve.param, reason: ve.message })
}
return next(err)
}
}
}
/** Update an account. */
export function updateAccount({ model }: Context): AuthRequestHandler {
interface RequestData {
account: AccountUpdate
}
interface ResponseData {
account: WithId<Partial<Account>>
}
const readRequestData = v.validate<RequestData>({
account: {
email: v.seq(v.optional, v.email),
password: v.seq(v.optional, validatePassword),
},
})
return async function (req, res, next) {
if (!req.account) return http.unauthorized(res, next)
// Get account ID and assert access
const id = req.params.id || req.account._id
if (!req.account._id.equals(id)) return http.forbidden(res, next)
try {
// Read input
const input = readRequestData(req.body)
if (!input.account.email && !input.account.password) {
return http.badRequest(res, next, { reason: 'no changes' })
}
// Update account
const account = await model.account.update(id, input.account)
if (!account) return http.notFound(res, next)
// Send output
const output: ResponseData = { account: prepareAccount(account) }
res.send(output)
next()
} catch (err) {
const name = (err as Error).name
if (name === 'ValidateError') {
const ve = err as v.ValidateError
return http.badRequest(res, next, { param: ve.param, reason: ve.message })
}
return next(err)
}
}
}