59 lines
1.6 KiB
TypeScript
59 lines
1.6 KiB
TypeScript
import { ArcaWsaaTokensAdapterMongoose } from "./ArcaWsaaTokens.Adapter.Mongoose";
|
|
import {
|
|
ArcaWsaaTokenLookupParams,
|
|
IArcaWsaaToken,
|
|
IArcaWsaaTokensManager,
|
|
UpsertArcaWsaaTokenParams,
|
|
} from "./ArcaWsaaTokens.Interface";
|
|
|
|
const TOKEN_REUSE_SKEW_MS = 10 * 60 * 1000;
|
|
|
|
class ArcaWsaaTokensManager implements IArcaWsaaTokensManager {
|
|
arcaWsaaTokens: ArcaWsaaTokensAdapterMongoose;
|
|
|
|
constructor() {
|
|
this.arcaWsaaTokens = new ArcaWsaaTokensAdapterMongoose();
|
|
}
|
|
|
|
public async getValidToken(data: ArcaWsaaTokenLookupParams): Promise<IArcaWsaaToken | null> {
|
|
const existingToken = await this.arcaWsaaTokens.findOne(data);
|
|
|
|
if (!existingToken) {
|
|
return null;
|
|
}
|
|
|
|
const reuseUntil = Date.now() + TOKEN_REUSE_SKEW_MS;
|
|
if (new Date(existingToken.expirationTime).getTime() <= reuseUntil) {
|
|
return null;
|
|
}
|
|
|
|
return existingToken;
|
|
}
|
|
|
|
public async saveToken(data: UpsertArcaWsaaTokenParams): Promise<IArcaWsaaToken> {
|
|
const now = new Date();
|
|
return await this.arcaWsaaTokens.create({
|
|
...data,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
});
|
|
}
|
|
|
|
public async upsertToken(data: UpsertArcaWsaaTokenParams): Promise<IArcaWsaaToken> {
|
|
const now = new Date();
|
|
const token = await this.arcaWsaaTokens.upsert({
|
|
...data,
|
|
createdAt: now,
|
|
updatedAt: now,
|
|
});
|
|
|
|
if (!token) {
|
|
throw new Error("No se pudo guardar el token WSAA de ARCA");
|
|
}
|
|
|
|
return token;
|
|
}
|
|
}
|
|
|
|
export default new ArcaWsaaTokensManager();
|