This repository has been archived on 2022-11-26. You can view files and clone it, but cannot push or open issues or pull requests.
IcyNet.eu/server/api/oauth2/controller/token.js

89 lines
2.8 KiB
JavaScript

import * as tokens from './tokens'
import { InvalidRequest, InvalidClient, UnauthorizedClient } from '../error'
import { data as dataResponse, error as errorResponse } from '../response'
import wrap from '../wrap'
export const token = wrap(async (req, res) => {
let clientId = null
let clientSecret = null
let grantType = null
if (req.body.client_id && req.body.client_secret) {
clientId = req.body.client_id
clientSecret = req.body.client_secret
console.debug('Client credentials parsed from body parameters', clientId, clientSecret)
} else {
if (!req.headers || !req.headers.authorization) {
throw new InvalidRequest('No authorization header passed')
}
let pieces = req.headers.authorization.split(' ', 2)
if (!pieces || pieces.length !== 2) {
throw new InvalidRequest('Authorization header is corrupted')
}
if (pieces[0] !== 'Basic') {
throw new InvalidRequest('Unsupported authorization method:', pieces[0])
}
pieces = Buffer.from(pieces[1], 'base64').toString('ascii').split(':', 2)
if (!pieces || pieces.length !== 2) {
throw new InvalidRequest('Authorization header has corrupted data')
}
clientId = pieces[0]
clientSecret = pieces[1]
console.debug('Client credentials parsed from basic auth header:', clientId, clientSecret)
}
if (!req.body.grant_type) {
throw new InvalidRequest('Request body does not contain grant_type parameter')
}
grantType = req.body.grant_type
console.debug('Parameter grant_type is', grantType)
const client = await req.oauth2.model.client.fetchById(clientId)
if (!client) {
throw new InvalidClient('Client not found')
}
const valid = req.oauth2.model.client.checkSecret(client, clientSecret)
if (!valid) {
throw new UnauthorizedClient('Invalid client secret')
}
if (!req.oauth2.model.client.checkGrantType(client, grantType) && grantType !== 'refresh_token') {
throw new UnauthorizedClient('Invalid grant type for the client')
} else {
console.debug('Grant type check passed')
}
let evt
try {
switch (grantType) {
case 'authorization_code':
evt = await tokens.authorizationCode(req.oauth2, client, req.body.code, req.body.redirect_uri)
break
case 'password':
evt = await tokens.password(req.oauth2, client, req.body.username, req.body.password, req.body.scope)
break
case 'client_credentials':
evt = await tokens.clientCredentials(req.oauth2, client, req.body.scope)
break
case 'refresh_token':
evt = await tokens.refreshToken(req.oauth2, client, req.body.refresh_token, req.body.scope)
break
default:
throw new error.UnsupportedGrantType('Grant type does not match any supported type')
}
if (evt) {
dataResponse(req, res, evt)
}
} catch (e) {
errorResponse(req, res, e)
}
})