7755f6c2ba4a37e6e635557eb152c5ef76c01d2e
[oweals/peertube.git] / server / controllers / api / clients.js
1 'use strict'
2
3 const express = require('express')
4 const mongoose = require('mongoose')
5
6 const constants = require('../../initializers/constants')
7 const logger = require('../../helpers/logger')
8
9 const Client = mongoose.model('OAuthClient')
10
11 const router = express.Router()
12
13 router.get('/local', getLocalClient)
14
15 // Get the client credentials for the PeerTube front end
16 function getLocalClient (req, res, next) {
17   const serverHostname = constants.CONFIG.WEBSERVER.HOSTNAME
18   const serverPort = constants.CONFIG.WEBSERVER.PORT
19   let headerHostShouldBe = serverHostname
20   if (serverPort !== 80 && serverPort !== 443) {
21     headerHostShouldBe += ':' + serverPort
22   }
23
24   // Don't make this check if this is a test instance
25   if (process.env.NODE_ENV !== 'test' && req.get('host') !== headerHostShouldBe) {
26     logger.info('Getting client tokens for host %s is forbidden (expected %s).', req.get('host'), headerHostShouldBe)
27     return res.type('json').status(403).end()
28   }
29
30   Client.loadFirstClient(function (err, client) {
31     if (err) return next(err)
32     if (!client) return next(new Error('No client available.'))
33
34     res.json({
35       client_id: client._id,
36       client_secret: client.clientSecret
37     })
38   })
39 }
40
41 // ---------------------------------------------------------------------------
42
43 module.exports = router