Files
knur-app/lib/models/garmin-auth.ts
Dominik Klarkowski 115d56cd12 init
2026-06-18 11:12:12 +02:00

66 lines
2.5 KiB
TypeScript

import type { IOauth1Token } from "garmin-connect/dist/garmin/types";
import { getDb } from "@/lib/db";
import { encrypt, decrypt } from "@/lib/crypto";
import type { GarminPendingMfa } from "@/lib/garmin/sso";
const AUTH_COLLECTION = "garmin_auth";
const PENDING_COLLECTION = "garmin_login_pending";
const CREDENTIALS_COLLECTION = "garmin_credentials";
type GarminAuthDoc = { _id: string; oauth1Token: IOauth1Token; updatedAt: Date };
type GarminPendingDoc = { _id: string; state: GarminPendingMfa; createdAt: Date };
type GarminCredentialsDoc = { _id: string; email: string; password: string };
export async function getSavedOauth1Token(userId: string): Promise<IOauth1Token | null> {
const db = await getDb();
const doc = await db.collection<GarminAuthDoc>(AUTH_COLLECTION).findOne({ _id: userId });
return doc?.oauth1Token ?? null;
}
export async function saveOauth1Token(userId: string, oauth1Token: IOauth1Token): Promise<void> {
const db = await getDb();
await db
.collection<GarminAuthDoc>(AUTH_COLLECTION)
.updateOne({ _id: userId }, { $set: { oauth1Token, updatedAt: new Date() } }, { upsert: true });
}
export async function savePendingMfaState(userId: string, state: GarminPendingMfa): Promise<void> {
const db = await getDb();
await db
.collection<GarminPendingDoc>(PENDING_COLLECTION)
.updateOne({ _id: userId }, { $set: { state, createdAt: new Date() } }, { upsert: true });
}
export async function getPendingMfaState(userId: string): Promise<GarminPendingMfa | null> {
const db = await getDb();
const doc = await db.collection<GarminPendingDoc>(PENDING_COLLECTION).findOne({ _id: userId });
return doc?.state ?? null;
}
export async function clearPendingMfaState(userId: string): Promise<void> {
const db = await getDb();
await db.collection<GarminPendingDoc>(PENDING_COLLECTION).deleteOne({ _id: userId });
}
export async function getGarminCredentials(
userId: string
): Promise<{ email: string; password: string } | null> {
const db = await getDb();
const doc = await db
.collection<GarminCredentialsDoc>(CREDENTIALS_COLLECTION)
.findOne({ _id: userId });
if (!doc) return null;
return { email: doc.email, password: decrypt(doc.password) };
}
export async function saveGarminCredentials(
userId: string,
email: string,
password: string
): Promise<void> {
const db = await getDb();
await db
.collection<GarminCredentialsDoc>(CREDENTIALS_COLLECTION)
.updateOne({ _id: userId }, { $set: { email, password: encrypt(password) } }, { upsert: true });
}