Add video channels
[oweals/peertube.git] / server / controllers / api / users.ts
1 import * as express from 'express'
2
3 import { database as db } from '../../initializers/database'
4 import { USER_ROLES, CONFIG } from '../../initializers'
5 import { logger, getFormattedObjects, retryTransactionWrapper } from '../../helpers'
6 import {
7   authenticate,
8   ensureIsAdmin,
9   ensureUserRegistrationAllowed,
10   usersAddValidator,
11   usersRegisterValidator,
12   usersUpdateValidator,
13   usersUpdateMeValidator,
14   usersRemoveValidator,
15   usersVideoRatingValidator,
16   usersGetValidator,
17   paginationValidator,
18   setPagination,
19   usersSortValidator,
20   setUsersSort,
21   token
22 } from '../../middlewares'
23 import {
24   UserVideoRate as FormattedUserVideoRate,
25   UserCreate,
26   UserUpdate,
27   UserUpdateMe
28 } from '../../../shared'
29 import { createUserAuthorAndChannel } from '../../lib'
30 import { UserInstance } from '../../models'
31
32 const usersRouter = express.Router()
33
34 usersRouter.get('/me',
35   authenticate,
36   getUserInformation
37 )
38
39 usersRouter.get('/me/videos/:videoId/rating',
40   authenticate,
41   usersVideoRatingValidator,
42   getUserVideoRating
43 )
44
45 usersRouter.get('/',
46   paginationValidator,
47   usersSortValidator,
48   setUsersSort,
49   setPagination,
50   listUsers
51 )
52
53 usersRouter.get('/:id',
54   usersGetValidator,
55   getUser
56 )
57
58 usersRouter.post('/',
59   authenticate,
60   ensureIsAdmin,
61   usersAddValidator,
62   createUserRetryWrapper
63 )
64
65 usersRouter.post('/register',
66   ensureUserRegistrationAllowed,
67   usersRegisterValidator,
68   registerUser
69 )
70
71 usersRouter.put('/me',
72   authenticate,
73   usersUpdateMeValidator,
74   updateMe
75 )
76
77 usersRouter.put('/:id',
78   authenticate,
79   ensureIsAdmin,
80   usersUpdateValidator,
81   updateUser
82 )
83
84 usersRouter.delete('/:id',
85   authenticate,
86   ensureIsAdmin,
87   usersRemoveValidator,
88   removeUser
89 )
90
91 usersRouter.post('/token', token, success)
92 // TODO: Once https://github.com/oauthjs/node-oauth2-server/pull/289 is merged, implement revoke token route
93
94 // ---------------------------------------------------------------------------
95
96 export {
97   usersRouter
98 }
99
100 // ---------------------------------------------------------------------------
101
102 function createUserRetryWrapper (req: express.Request, res: express.Response, next: express.NextFunction) {
103   const options = {
104     arguments: [ req, res ],
105     errorMessage: 'Cannot insert the user with many retries.'
106   }
107
108   retryTransactionWrapper(createUser, options)
109     .then(() => {
110       // TODO : include Location of the new user -> 201
111       res.type('json').status(204).end()
112     })
113     .catch(err => next(err))
114 }
115
116 function createUser (req: express.Request, res: express.Response, next: express.NextFunction) {
117   const body: UserCreate = req.body
118   const user = db.User.build({
119     username: body.username,
120     password: body.password,
121     email: body.email,
122     displayNSFW: false,
123     role: USER_ROLES.USER,
124     videoQuota: body.videoQuota
125   })
126
127   return createUserAuthorAndChannel(user)
128     .then(() => logger.info('User %s with its channel and author created.', body.username))
129     .catch((err: Error) => {
130       logger.debug('Cannot insert the user.', err)
131       throw err
132     })
133 }
134
135 function registerUser (req: express.Request, res: express.Response, next: express.NextFunction) {
136   const body: UserCreate = req.body
137
138   const user = db.User.build({
139     username: body.username,
140     password: body.password,
141     email: body.email,
142     displayNSFW: false,
143     role: USER_ROLES.USER,
144     videoQuota: CONFIG.USER.VIDEO_QUOTA
145   })
146
147   return createUserAuthorAndChannel(user)
148     .then(() => res.type('json').status(204).end())
149     .catch(err => next(err))
150 }
151
152 function getUserInformation (req: express.Request, res: express.Response, next: express.NextFunction) {
153   db.User.loadByUsernameAndPopulateChannels(res.locals.oauth.token.user.username)
154     .then(user => res.json(user.toFormattedJSON()))
155     .catch(err => next(err))
156 }
157
158 function getUser (req: express.Request, res: express.Response, next: express.NextFunction) {
159   return res.json(res.locals.user.toFormattedJSON())
160 }
161
162 function getUserVideoRating (req: express.Request, res: express.Response, next: express.NextFunction) {
163   const videoId = +req.params.videoId
164   const userId = +res.locals.oauth.token.User.id
165
166   db.UserVideoRate.load(userId, videoId, null)
167     .then(ratingObj => {
168       const rating = ratingObj ? ratingObj.type : 'none'
169       const json: FormattedUserVideoRate = {
170         videoId,
171         rating
172       }
173       res.json(json)
174     })
175     .catch(err => next(err))
176 }
177
178 function listUsers (req: express.Request, res: express.Response, next: express.NextFunction) {
179   db.User.listForApi(req.query.start, req.query.count, req.query.sort)
180     .then(resultList => {
181       res.json(getFormattedObjects(resultList.data, resultList.total))
182     })
183     .catch(err => next(err))
184 }
185
186 function removeUser (req: express.Request, res: express.Response, next: express.NextFunction) {
187   db.User.loadById(req.params.id)
188     .then(user => user.destroy())
189     .then(() => res.sendStatus(204))
190     .catch(err => {
191       logger.error('Errors when removed the user.', err)
192       return next(err)
193     })
194 }
195
196 function updateMe (req: express.Request, res: express.Response, next: express.NextFunction) {
197   const body: UserUpdateMe = req.body
198
199   // FIXME: user is not already a Sequelize instance?
200   db.User.loadByUsername(res.locals.oauth.token.user.username)
201     .then(user => {
202       if (body.password !== undefined) user.password = body.password
203       if (body.email !== undefined) user.email = body.email
204       if (body.displayNSFW !== undefined) user.displayNSFW = body.displayNSFW
205
206       return user.save()
207     })
208     .then(() => res.sendStatus(204))
209     .catch(err => next(err))
210 }
211
212 function updateUser (req: express.Request, res: express.Response, next: express.NextFunction) {
213   const body: UserUpdate = req.body
214   const user: UserInstance = res.locals.user
215
216   if (body.email !== undefined) user.email = body.email
217   if (body.videoQuota !== undefined) user.videoQuota = body.videoQuota
218
219   return user.save()
220     .then(() => res.sendStatus(204))
221     .catch(err => next(err))
222 }
223
224 function success (req: express.Request, res: express.Response, next: express.NextFunction) {
225   res.end()
226 }