auth-server-helper/lib/RedisData/RedisKeyStore.ts

53 lines
1.4 KiB
TypeScript
Raw Normal View History

2022-08-15 17:33:25 +02:00
/*
* Copyright (C) Sapphirecode - All Rights Reserved
* This file is part of Auth-Server-Helper which is released under MIT.
* See file 'LICENSE' for full license details.
* Created by Timo Hocker <timo@scode.ovh>, August 2022
*/
import { debug } from '../debug';
import { LabelledKey } from '../Key';
2022-08-27 16:39:07 +02:00
import { Redis } from '../Redis';
2022-08-15 17:33:25 +02:00
const logger = debug ('RedisKeyStore');
2022-08-27 16:39:07 +02:00
export class RedisKeyStore extends Redis {
2022-08-15 17:33:25 +02:00
public async set (value: LabelledKey): Promise<void> {
const log = logger.extend ('set');
log ('trying to set key %s to redis', value.index);
2022-08-27 16:39:07 +02:00
if (!this.is_active) {
2022-08-15 17:33:25 +02:00
log ('redis is inactive, skipping');
return;
}
const valid_for = Math.floor (
(value.valid_until - (new Date)
.getTime ()) / 1000
);
log ('key is valid for %d seconds', valid_for);
2022-08-27 16:39:07 +02:00
await this.redis.setex (
2022-08-15 17:33:25 +02:00
`keystore_${value.index}`,
valid_for,
JSON.stringify (value)
);
log ('saved key');
}
public async get (index: string): Promise<LabelledKey | null> {
const log = logger.extend ('get');
log ('trying to get key %s from redis', index);
2022-08-27 16:39:07 +02:00
if (!this.is_active) {
2022-08-15 17:33:25 +02:00
log ('redis is inactive, skipping');
return null;
}
2022-08-27 16:39:07 +02:00
const res = await this.redis.get (`keystore_${index}`);
2022-08-15 17:33:25 +02:00
if (res === null) {
log ('key not found in redis');
return null;
}
log ('key found');
return JSON.parse (res);
}
}
export const redis_key_store = new RedisKeyStore;