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