Support logout and add id and pass tests
[oweals/peertube.git] / server / lib / auth.ts
1 import * as express from 'express'
2 import { OAUTH_LIFETIME } from '@server/initializers/constants'
3 import * as OAuthServer from 'express-oauth-server'
4 import { PluginManager } from '@server/lib/plugins/plugin-manager'
5 import { RegisterServerAuthPassOptions } from '@shared/models/plugins/register-server-auth.model'
6 import { logger } from '@server/helpers/logger'
7 import { UserRole } from '@shared/models'
8 import { revokeToken } from '@server/lib/oauth-model'
9
10 const oAuthServer = new OAuthServer({
11   useErrorHandler: true,
12   accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
13   refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,
14   continueMiddleware: true,
15   model: require('./oauth-model')
16 })
17
18 function onExternalAuthPlugin (npmName: string, username: string, email: string) {
19
20 }
21
22 async function handleIdAndPassLogin (req: express.Request, res: express.Response, next: express.NextFunction) {
23   const plugins = PluginManager.Instance.getIdAndPassAuths()
24   const pluginAuths: { npmName?: string, registerAuthOptions: RegisterServerAuthPassOptions }[] = []
25
26   for (const plugin of plugins) {
27     const auths = plugin.idAndPassAuths
28
29     for (const auth of auths) {
30       pluginAuths.push({
31         npmName: plugin.npmName,
32         registerAuthOptions: auth
33       })
34     }
35   }
36
37   pluginAuths.sort((a, b) => {
38     const aWeight = a.registerAuthOptions.getWeight()
39     const bWeight = b.registerAuthOptions.getWeight()
40
41     // DESC weight order
42     if (aWeight === bWeight) return 0
43     if (aWeight < bWeight) return 1
44     return -1
45   })
46
47   const loginOptions = {
48     id: req.body.username,
49     password: req.body.password
50   }
51
52   for (const pluginAuth of pluginAuths) {
53     const authOptions = pluginAuth.registerAuthOptions
54
55     logger.debug(
56       'Using auth method %s of plugin %s to login %s with weight %d.',
57       authOptions.authName, pluginAuth.npmName, loginOptions.id, authOptions.getWeight()
58     )
59
60     const loginResult = await authOptions.login(loginOptions)
61     if (loginResult) {
62       logger.info(
63         'Login success with auth method %s of plugin %s for %s.',
64         authOptions.authName, pluginAuth.npmName, loginOptions.id
65       )
66
67       res.locals.bypassLogin = {
68         bypass: true,
69         pluginName: pluginAuth.npmName,
70         authName: authOptions.authName,
71         user: {
72           username: loginResult.username,
73           email: loginResult.email,
74           role: loginResult.role || UserRole.USER,
75           displayName: loginResult.displayName || loginResult.username
76         }
77       }
78
79       break
80     }
81   }
82
83   return localLogin(req, res, next)
84 }
85
86 async function handleTokenRevocation (req: express.Request, res: express.Response) {
87   const token = res.locals.oauth.token
88
89   PluginManager.Instance.onLogout(token.User.pluginAuth, token.authName)
90
91   await revokeToken(token)
92     .catch(err => {
93       logger.error('Cannot revoke token.', err)
94     })
95
96   // FIXME: uncomment when https://github.com/oauthjs/node-oauth2-server/pull/289 is released
97   // oAuthServer.revoke(req, res, err => {
98   //   if (err) {
99   //     logger.warn('Error in revoke token handler.', { err })
100   //
101   //     return res.status(err.status)
102   //               .json({
103   //                 error: err.message,
104   //                 code: err.name
105   //               })
106   //               .end()
107   //   }
108   // })
109
110   return res.sendStatus(200)
111 }
112
113 // ---------------------------------------------------------------------------
114
115 export {
116   oAuthServer,
117   handleIdAndPassLogin,
118   onExternalAuthPlugin,
119   handleTokenRevocation
120 }
121
122 // ---------------------------------------------------------------------------
123
124 function localLogin (req: express.Request, res: express.Response, next: express.NextFunction) {
125   return oAuthServer.token()(req, res, err => {
126     if (err) {
127       logger.warn('Login error.', { err })
128
129       return res.status(err.status)
130                 .json({
131                   error: err.message,
132                   code: err.name
133                 })
134                 .end()
135     }
136
137     return next()
138   })
139 }