1 import express from 'express'
8 UnauthorizedClientError,
9 UnsupportedGrantTypeError
10 } from '@node-oauth/oauth2-server'
11 import { randomBytesPromise } from '@server/helpers/core-utils'
12 import { MOAuthClient } from '@server/types/models'
13 import { sha1 } from '@shared/extra-utils'
14 import { HttpStatusCode } from '@shared/models'
15 import { OAUTH_LIFETIME, OTP } from '../../initializers/constants'
16 import { BypassLogin, getClient, getRefreshToken, getUser, revokeToken, saveToken } from './oauth-model'
17 import { isOTPValid } from '@server/helpers/otp'
19 class MissingTwoFactorError extends Error {
20 code = HttpStatusCode.UNAUTHORIZED_401
21 name = 'missing_two_factor'
24 class InvalidTwoFactorError extends Error {
25 code = HttpStatusCode.BAD_REQUEST_400
26 name = 'invalid_two_factor'
31 * Reimplement some functions of OAuth2Server to inject external auth methods
34 const oAuthServer = new OAuth2Server({
35 accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
36 refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,
38 // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications
39 model: require('./oauth-model')
42 // ---------------------------------------------------------------------------
44 async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthName?: string, bypassLogin?: BypassLogin }) {
45 const request = new Request(req)
46 const { refreshTokenAuthName, bypassLogin } = options
48 if (request.method !== 'POST') {
49 throw new InvalidRequestError('Invalid request: method must be POST')
52 if (!request.is([ 'application/x-www-form-urlencoded' ])) {
53 throw new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded')
56 const clientId = request.body.client_id
57 const clientSecret = request.body.client_secret
59 if (!clientId || !clientSecret) {
60 throw new InvalidClientError('Invalid client: cannot retrieve client credentials')
63 const client = await getClient(clientId, clientSecret)
65 throw new InvalidClientError('Invalid client: client is invalid')
68 const grantType = request.body.grant_type
70 throw new InvalidRequestError('Missing parameter: `grant_type`')
73 if (![ 'password', 'refresh_token' ].includes(grantType)) {
74 throw new UnsupportedGrantTypeError('Unsupported grant type: `grant_type` is invalid')
77 if (!client.grants.includes(grantType)) {
78 throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid')
81 if (grantType === 'password') {
82 return handlePasswordGrant({
89 return handleRefreshGrant({
96 function handleOAuthAuthenticate (
98 res: express.Response,
99 authenticateInQuery = false
101 const options = authenticateInQuery
102 ? { allowBearerTokensInQueryString: true }
105 return oAuthServer.authenticate(new Request(req), new Response(res), options)
109 MissingTwoFactorError,
110 InvalidTwoFactorError,
113 handleOAuthAuthenticate
116 // ---------------------------------------------------------------------------
118 async function handlePasswordGrant (options: {
121 bypassLogin?: BypassLogin
123 const { request, client, bypassLogin } = options
125 if (!request.body.username) {
126 throw new InvalidRequestError('Missing parameter: `username`')
129 if (!bypassLogin && !request.body.password) {
130 throw new InvalidRequestError('Missing parameter: `password`')
133 const user = await getUser(request.body.username, request.body.password, bypassLogin)
134 if (!user) throw new InvalidGrantError('Invalid grant: user credentials are invalid')
136 if (user.otpSecret) {
137 if (!request.headers[OTP.HEADER_NAME]) {
138 throw new MissingTwoFactorError('Missing two factor header')
141 if (isOTPValid({ secret: user.otpSecret, token: request.headers[OTP.HEADER_NAME] }) !== true) {
142 throw new InvalidTwoFactorError('Invalid two factor header')
146 const token = await buildToken()
148 return saveToken(token, client, user, { bypassLogin })
151 async function handleRefreshGrant (options: {
154 refreshTokenAuthName: string
156 const { request, client, refreshTokenAuthName } = options
158 if (!request.body.refresh_token) {
159 throw new InvalidRequestError('Missing parameter: `refresh_token`')
162 const refreshToken = await getRefreshToken(request.body.refresh_token)
165 throw new InvalidGrantError('Invalid grant: refresh token is invalid')
168 if (refreshToken.client.id !== client.id) {
169 throw new InvalidGrantError('Invalid grant: refresh token is invalid')
172 if (refreshToken.refreshTokenExpiresAt && refreshToken.refreshTokenExpiresAt < new Date()) {
173 throw new InvalidGrantError('Invalid grant: refresh token has expired')
176 await revokeToken({ refreshToken: refreshToken.refreshToken })
178 const token = await buildToken()
180 return saveToken(token, client, refreshToken.user, { refreshTokenAuthName })
183 function generateRandomToken () {
184 return randomBytesPromise(256)
185 .then(buffer => sha1(buffer))
188 function getTokenExpiresAt (type: 'access' | 'refresh') {
189 const lifetime = type === 'access'
190 ? OAUTH_LIFETIME.ACCESS_TOKEN
191 : OAUTH_LIFETIME.REFRESH_TOKEN
193 return new Date(Date.now() + lifetime * 1000)
196 async function buildToken () {
197 const [ accessToken, refreshToken ] = await Promise.all([ generateRandomToken(), generateRandomToken() ])
202 accessTokenExpiresAt: getTokenExpiresAt('access'),
203 refreshTokenExpiresAt: getTokenExpiresAt('refresh')