feat: store logged account
This commit is contained in:
64
web/src/repository/account.ts
Normal file
64
web/src/repository/account.ts
Normal file
@ -0,0 +1,64 @@
|
||||
import { useDbContext } from "@/context/db/db";
|
||||
import { deriveDeviceKey, getDeviceId } from "@/util/deviceId";
|
||||
import { useCallback } from "react";
|
||||
|
||||
export interface LocalAccount {
|
||||
accountId: string;
|
||||
label: string;
|
||||
email: string;
|
||||
access: { data: number[]; iv: number[] };
|
||||
refresh: { data: number[]; iv: number[] };
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface CreateAccountRequest {
|
||||
accountId: string;
|
||||
label: string;
|
||||
email: string;
|
||||
access: string;
|
||||
refresh: string;
|
||||
}
|
||||
|
||||
export const useAccountRepo = () => {
|
||||
const { db } = useDbContext();
|
||||
|
||||
const encryptToken = useCallback(async (token: string) => {
|
||||
const encoder = new TextEncoder();
|
||||
|
||||
const iv = crypto.getRandomValues(new Uint8Array(12));
|
||||
|
||||
const deviceId = await getDeviceId();
|
||||
const deviceKey = await deriveDeviceKey(deviceId);
|
||||
|
||||
const cipherText = await crypto.subtle.encrypt(
|
||||
{ name: "AES-GCM", iv },
|
||||
deviceKey,
|
||||
encoder.encode(token)
|
||||
);
|
||||
|
||||
return {
|
||||
data: Array.from(new Uint8Array(cipherText)),
|
||||
iv: Array.from(iv),
|
||||
};
|
||||
}, []);
|
||||
|
||||
const save = useCallback(
|
||||
async (req: CreateAccountRequest) => {
|
||||
console.log({ db });
|
||||
const access = await encryptToken(req.access);
|
||||
const refresh = await encryptToken(req.refresh);
|
||||
|
||||
await db?.put?.("accounts", {
|
||||
accountId: req.accountId,
|
||||
label: req.label,
|
||||
email: req.email,
|
||||
access,
|
||||
refresh,
|
||||
updatedAt: new Date().toISOString(),
|
||||
});
|
||||
},
|
||||
[db, encryptToken]
|
||||
);
|
||||
|
||||
return { save };
|
||||
};
|
Reference in New Issue
Block a user