|
1 |
| -const AuthLib = { |
2 |
| - async getRolesForAParticipant(participantId: number) { |
3 |
| - return participantId; //TODO: add functionality |
4 |
| - }, |
5 |
| - |
6 |
| - async getParticipantsForATarget(target: { |
7 |
| - targetId: number; |
8 |
| - target: string; |
9 |
| - }) { |
10 |
| - return target; //TODO: add functionality |
11 |
| - }, |
| 1 | +import { PartialRequest } from '@unocha/hpc-api-core/src/Request'; |
| 2 | + |
| 3 | +type BasicAuth = { |
| 4 | + username: string | null; |
| 5 | + password: string | null; |
| 6 | +}; |
| 7 | + |
| 8 | +const parseBasic = (basic: string): BasicAuth => { |
| 9 | + let pieces: (string | null)[]; |
| 10 | + |
| 11 | + const decoded = new Buffer(basic, 'base64').toString('utf8'); |
| 12 | + |
| 13 | + if (!decoded) { |
| 14 | + throw new Error('Authorization header invalid'); |
| 15 | + } |
| 16 | + |
| 17 | + const index = decoded.indexOf(':'); |
| 18 | + |
| 19 | + if (index === -1) { |
| 20 | + pieces = [decoded]; |
| 21 | + } else { |
| 22 | + pieces = [decoded.slice(0, index), decoded.slice(index + 1)]; |
| 23 | + } |
| 24 | + |
| 25 | + if (!pieces || typeof pieces[0] !== 'string') { |
| 26 | + throw new Error('Authorization header invalid'); |
| 27 | + } |
| 28 | + |
| 29 | + // Allows for usernameless authentication |
| 30 | + if (!pieces[0]) { |
| 31 | + pieces[0] = null; |
| 32 | + } |
| 33 | + |
| 34 | + // Allows for passwordless authentication |
| 35 | + if (!pieces[1]) { |
| 36 | + pieces[1] = null; |
| 37 | + } |
| 38 | + |
| 39 | + return { |
| 40 | + username: pieces[0], |
| 41 | + password: pieces[1], |
| 42 | + }; |
12 | 43 | };
|
13 | 44 |
|
14 |
| -export default AuthLib; |
| 45 | +export const getTokenFromRequest = (req: PartialRequest): string | null => { |
| 46 | + if (!req.headers?.authorization) { |
| 47 | + return null; |
| 48 | + } |
| 49 | + |
| 50 | + const pieces = req.headers.authorization.split(' ', 2); |
| 51 | + |
| 52 | + if (!pieces || pieces.length !== 2) { |
| 53 | + throw new Error('BasicAuth content is invalid'); |
| 54 | + } |
| 55 | + |
| 56 | + let basic: BasicAuth | null = null; |
| 57 | + const scheme = pieces[0]; |
| 58 | + const credentials = pieces[1]; |
| 59 | + |
| 60 | + try { |
| 61 | + switch (scheme.toLowerCase()) { |
| 62 | + case 'basic': |
| 63 | + basic = parseBasic(credentials); |
| 64 | + break; |
| 65 | + |
| 66 | + default: |
| 67 | + throw new Error('Unsupported authorization scheme'); |
| 68 | + } |
| 69 | + } catch (e2) { |
| 70 | + return null; |
| 71 | + } |
| 72 | + |
| 73 | + return basic ? basic.password : credentials; |
| 74 | +}; |
0 commit comments