]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - server/lib/auth/oauth.ts
Support two factor authentication in backend
[github/Chocobozzz/PeerTube.git] / server / lib / auth / oauth.ts
CommitLineData
41fb13c3 1import express from 'express'
031bbcd2 2import OAuth2Server, {
f43db2f4
C
3 InvalidClientError,
4 InvalidGrantError,
5 InvalidRequestError,
6 Request,
7 Response,
8 UnauthorizedClientError,
9 UnsupportedGrantTypeError
031bbcd2 10} from '@node-oauth/oauth2-server'
06aad801 11import { randomBytesPromise } from '@server/helpers/core-utils'
f43db2f4 12import { MOAuthClient } from '@server/types/models'
f304a158 13import { sha1 } from '@shared/extra-utils'
56f47830
C
14import { HttpStatusCode } from '@shared/models'
15import { OAUTH_LIFETIME, OTP } from '../../initializers/constants'
f43db2f4 16import { BypassLogin, getClient, getRefreshToken, getUser, revokeToken, saveToken } from './oauth-model'
56f47830
C
17import { isOTPValid } from '@server/helpers/otp'
18
19class MissingTwoFactorError extends Error {
20 code = HttpStatusCode.UNAUTHORIZED_401
21 name = 'missing_two_factor'
22}
23
24class InvalidTwoFactorError extends Error {
25 code = HttpStatusCode.BAD_REQUEST_400
26 name = 'invalid_two_factor'
27}
f43db2f4
C
28
29/**
30 *
31 * Reimplement some functions of OAuth2Server to inject external auth methods
32 *
33 */
031bbcd2 34const oAuthServer = new OAuth2Server({
f43db2f4
C
35 accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
36 refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,
37
38 // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications
39 model: require('./oauth-model')
40})
41
42// ---------------------------------------------------------------------------
43
44async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthName?: string, bypassLogin?: BypassLogin }) {
45 const request = new Request(req)
46 const { refreshTokenAuthName, bypassLogin } = options
47
48 if (request.method !== 'POST') {
49 throw new InvalidRequestError('Invalid request: method must be POST')
50 }
51
52 if (!request.is([ 'application/x-www-form-urlencoded' ])) {
53 throw new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded')
54 }
55
56 const clientId = request.body.client_id
57 const clientSecret = request.body.client_secret
58
59 if (!clientId || !clientSecret) {
60 throw new InvalidClientError('Invalid client: cannot retrieve client credentials')
61 }
62
63 const client = await getClient(clientId, clientSecret)
64 if (!client) {
65 throw new InvalidClientError('Invalid client: client is invalid')
66 }
67
68 const grantType = request.body.grant_type
69 if (!grantType) {
70 throw new InvalidRequestError('Missing parameter: `grant_type`')
71 }
72
73 if (![ 'password', 'refresh_token' ].includes(grantType)) {
74 throw new UnsupportedGrantTypeError('Unsupported grant type: `grant_type` is invalid')
75 }
76
77 if (!client.grants.includes(grantType)) {
78 throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid')
79 }
80
81 if (grantType === 'password') {
82 return handlePasswordGrant({
83 request,
84 client,
85 bypassLogin
86 })
87 }
88
89 return handleRefreshGrant({
90 request,
91 client,
92 refreshTokenAuthName
93 })
94}
95
98ab5dc8 96function handleOAuthAuthenticate (
f43db2f4
C
97 req: express.Request,
98 res: express.Response,
99 authenticateInQuery = false
100) {
101 const options = authenticateInQuery
102 ? { allowBearerTokensInQueryString: true }
103 : {}
104
105 return oAuthServer.authenticate(new Request(req), new Response(res), options)
106}
107
108export {
56f47830
C
109 MissingTwoFactorError,
110 InvalidTwoFactorError,
111
f43db2f4
C
112 handleOAuthToken,
113 handleOAuthAuthenticate
114}
115
116// ---------------------------------------------------------------------------
117
118async function handlePasswordGrant (options: {
119 request: Request
120 client: MOAuthClient
121 bypassLogin?: BypassLogin
122}) {
123 const { request, client, bypassLogin } = options
124
125 if (!request.body.username) {
126 throw new InvalidRequestError('Missing parameter: `username`')
127 }
128
129 if (!bypassLogin && !request.body.password) {
130 throw new InvalidRequestError('Missing parameter: `password`')
131 }
132
133 const user = await getUser(request.body.username, request.body.password, bypassLogin)
134 if (!user) throw new InvalidGrantError('Invalid grant: user credentials are invalid')
135
56f47830
C
136 if (user.otpSecret) {
137 if (!request.headers[OTP.HEADER_NAME]) {
138 throw new MissingTwoFactorError('Missing two factor header')
139 }
140
141 if (isOTPValid({ secret: user.otpSecret, token: request.headers[OTP.HEADER_NAME] }) !== true) {
142 throw new InvalidTwoFactorError('Invalid two factor header')
143 }
144 }
145
f43db2f4
C
146 const token = await buildToken()
147
148 return saveToken(token, client, user, { bypassLogin })
149}
150
151async function handleRefreshGrant (options: {
152 request: Request
153 client: MOAuthClient
154 refreshTokenAuthName: string
155}) {
156 const { request, client, refreshTokenAuthName } = options
157
158 if (!request.body.refresh_token) {
159 throw new InvalidRequestError('Missing parameter: `refresh_token`')
160 }
161
162 const refreshToken = await getRefreshToken(request.body.refresh_token)
163
164 if (!refreshToken) {
165 throw new InvalidGrantError('Invalid grant: refresh token is invalid')
166 }
167
168 if (refreshToken.client.id !== client.id) {
169 throw new InvalidGrantError('Invalid grant: refresh token is invalid')
170 }
171
172 if (refreshToken.refreshTokenExpiresAt && refreshToken.refreshTokenExpiresAt < new Date()) {
173 throw new InvalidGrantError('Invalid grant: refresh token has expired')
174 }
175
176 await revokeToken({ refreshToken: refreshToken.refreshToken })
177
178 const token = await buildToken()
179
180 return saveToken(token, client, refreshToken.user, { refreshTokenAuthName })
181}
182
183function generateRandomToken () {
184 return randomBytesPromise(256)
185 .then(buffer => sha1(buffer))
186}
187
188function getTokenExpiresAt (type: 'access' | 'refresh') {
189 const lifetime = type === 'access'
190 ? OAUTH_LIFETIME.ACCESS_TOKEN
191 : OAUTH_LIFETIME.REFRESH_TOKEN
192
193 return new Date(Date.now() + lifetime * 1000)
194}
195
196async function buildToken () {
197 const [ accessToken, refreshToken ] = await Promise.all([ generateRandomToken(), generateRandomToken() ])
198
199 return {
200 accessToken,
201 refreshToken,
202 accessTokenExpiresAt: getTokenExpiresAt('access'),
203 refreshTokenExpiresAt: getTokenExpiresAt('refresh')
204 }
205}