Skip to content

Commit

Permalink
a
Browse files Browse the repository at this point in the history
  • Loading branch information
Janson Bunce committed Oct 2, 2024
1 parent 85ba586 commit a0446be
Showing 1 changed file with 26 additions and 13 deletions.
39 changes: 26 additions & 13 deletions backend/src/tools/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,28 +80,41 @@ export class Logger {
}

async parseToken() {
const atoapk = this.request.headers.authorization;
// Test if API key, e.g. a 32 digit hex string
if (atoapk && /^[A-Fa-f0-9]{32}$/.test(atoapk ?? '')) {
const authorizationHeader = this.request.headers.authorization;

if (!authorizationHeader) {
throw 'Missing token/api key';
}

if (/^[A-Fa-f0-9]{32}$/.test(authorizationHeader)) {
// API Key Logic
const hashedKey = createHash('sha256')
.update(authorizationHeader)
.digest('hex');
const apiKey = await ApiKey.findOne(
{
hashedKey: createHash('sha256').update(atoapk).digest('hex')
},
{ hashedKey },
{ relations: ['user'] }
);
if (!apiKey) throw 'Invalid API key';
this.token = { id: apiKey.user.id };

if (!apiKey) {
throw 'Invalid API key';
}

// Update last used and assign token
apiKey.lastUsed = new Date();
apiKey.save();
await apiKey.save();

this.token = { id: apiKey.user.id };
} else {
if (atoapk) {
// JWT Logic
try {
const parsedUserFromJwt = jwt.verify(
atoapk,
authorizationHeader,
process.env.JWT_SECRET!
) as UserToken;
this.token = { id: parsedUserFromJwt.id };
} else {
return 'Missing token/api key';
} catch (err) {
throw 'Invalid JWT token';
}
}
}
Expand Down

0 comments on commit a0446be

Please sign in to comment.