aboutsummaryrefslogtreecommitdiffhomepage
path: root/server/lib/auth/oauth.ts
blob: fa18873158fca4f174c644301b2b5bbcc8cb5e25 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
import express from 'express'
import OAuth2Server, {
  InvalidClientError,
  InvalidGrantError,
  InvalidRequestError,
  Request,
  Response,
  UnauthorizedClientError,
  UnsupportedGrantTypeError
} from '@node-oauth/oauth2-server'
import { randomBytesPromise } from '@server/helpers/core-utils'
import { MOAuthClient } from '@server/types/models'
import { sha1 } from '@shared/extra-utils'
import { OAUTH_LIFETIME } from '../../initializers/constants'
import { BypassLogin, getClient, getRefreshToken, getUser, revokeToken, saveToken } from './oauth-model'

/**
 *
 * Reimplement some functions of OAuth2Server to inject external auth methods
 *
 */
const oAuthServer = new OAuth2Server({
  accessTokenLifetime: OAUTH_LIFETIME.ACCESS_TOKEN,
  refreshTokenLifetime: OAUTH_LIFETIME.REFRESH_TOKEN,

  // See https://github.com/oauthjs/node-oauth2-server/wiki/Model-specification for the model specifications
  model: require('./oauth-model')
})

// ---------------------------------------------------------------------------

async function handleOAuthToken (req: express.Request, options: { refreshTokenAuthName?: string, bypassLogin?: BypassLogin }) {
  const request = new Request(req)
  const { refreshTokenAuthName, bypassLogin } = options

  if (request.method !== 'POST') {
    throw new InvalidRequestError('Invalid request: method must be POST')
  }

  if (!request.is([ 'application/x-www-form-urlencoded' ])) {
    throw new InvalidRequestError('Invalid request: content must be application/x-www-form-urlencoded')
  }

  const clientId = request.body.client_id
  const clientSecret = request.body.client_secret

  if (!clientId || !clientSecret) {
    throw new InvalidClientError('Invalid client: cannot retrieve client credentials')
  }

  const client = await getClient(clientId, clientSecret)
  if (!client) {
    throw new InvalidClientError('Invalid client: client is invalid')
  }

  const grantType = request.body.grant_type
  if (!grantType) {
    throw new InvalidRequestError('Missing parameter: `grant_type`')
  }

  if (![ 'password', 'refresh_token' ].includes(grantType)) {
    throw new UnsupportedGrantTypeError('Unsupported grant type: `grant_type` is invalid')
  }

  if (!client.grants.includes(grantType)) {
    throw new UnauthorizedClientError('Unauthorized client: `grant_type` is invalid')
  }

  if (grantType === 'password') {
    return handlePasswordGrant({
      request,
      client,
      bypassLogin
    })
  }

  return handleRefreshGrant({
    request,
    client,
    refreshTokenAuthName
  })
}

function handleOAuthAuthenticate (
  req: express.Request,
  res: express.Response,
  authenticateInQuery = false
) {
  const options = authenticateInQuery
    ? { allowBearerTokensInQueryString: true }
    : {}

  return oAuthServer.authenticate(new Request(req), new Response(res), options)
}

export {
  handleOAuthToken,
  handleOAuthAuthenticate
}

// ---------------------------------------------------------------------------

async function handlePasswordGrant (options: {
  request: Request
  client: MOAuthClient
  bypassLogin?: BypassLogin
}) {
  const { request, client, bypassLogin } = options

  if (!request.body.username) {
    throw new InvalidRequestError('Missing parameter: `username`')
  }

  if (!bypassLogin && !request.body.password) {
    throw new InvalidRequestError('Missing parameter: `password`')
  }

  const user = await getUser(request.body.username, request.body.password, bypassLogin)
  if (!user) throw new InvalidGrantError('Invalid grant: user credentials are invalid')

  const token = await buildToken()

  return saveToken(token, client, user, { bypassLogin })
}

async function handleRefreshGrant (options: {
  request: Request
  client: MOAuthClient
  refreshTokenAuthName: string
}) {
  const { request, client, refreshTokenAuthName } = options

  if (!request.body.refresh_token) {
    throw new InvalidRequestError('Missing parameter: `refresh_token`')
  }

  const refreshToken = await getRefreshToken(request.body.refresh_token)

  if (!refreshToken) {
    throw new InvalidGrantError('Invalid grant: refresh token is invalid')
  }

  if (refreshToken.client.id !== client.id) {
    throw new InvalidGrantError('Invalid grant: refresh token is invalid')
  }

  if (refreshToken.refreshTokenExpiresAt && refreshToken.refreshTokenExpiresAt < new Date()) {
    throw new InvalidGrantError('Invalid grant: refresh token has expired')
  }

  await revokeToken({ refreshToken: refreshToken.refreshToken })

  const token = await buildToken()

  return saveToken(token, client, refreshToken.user, { refreshTokenAuthName })
}

function generateRandomToken () {
  return randomBytesPromise(256)
    .then(buffer => sha1(buffer))
}

function getTokenExpiresAt (type: 'access' | 'refresh') {
  const lifetime = type === 'access'
    ? OAUTH_LIFETIME.ACCESS_TOKEN
    : OAUTH_LIFETIME.REFRESH_TOKEN

  return new Date(Date.now() + lifetime * 1000)
}

async function buildToken () {
  const [ accessToken, refreshToken ] = await Promise.all([ generateRandomToken(), generateRandomToken() ])

  return {
    accessToken,
    refreshToken,
    accessTokenExpiresAt: getTokenExpiresAt('access'),
    refreshTokenExpiresAt: getTokenExpiresAt('refresh')
  }
}