aboutsummaryrefslogtreecommitdiff
path: root/web/ui/src/routes/dashboard/keys/+page.server.ts
blob: 5491283a9d56ef671130db283f3104d4a30d9f23 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { fail, type Actions } from '@sveltejs/kit';

import {
  createKey,
  listKeys,
  revokeKey,
  countActiveKeys
} from '$lib/server/keys';
import { PLANS } from '$lib/plans';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ locals }) => {
  const account = locals.account!;
  const keys = listKeys(account.id);
  return {
    keys,
    activeCount: countActiveKeys(account.id),
    plan: PLANS[account.plan]
  };
};

export const actions: Actions = {
  create: async ({ request, locals }) => {
    const account = locals.account!;
    const form = await request.formData();
    const name = ((form.get('name') ?? '') as string).trim();
    const scopes = form.getAll('scopes').map((s) => s.toString());

    if (!name) {
      return fail(400, { error: 'Give the key a name so you can recognize it later.' });
    }

    const plan = PLANS[account.plan];
    const active = countActiveKeys(account.id);
    if (Number.isFinite(plan.maxKeys) && active >= plan.maxKeys) {
      return fail(403, {
        error: `Your ${plan.name} plan allows ${plan.maxKeys} active key${
          plan.maxKeys === 1 ? '' : 's'
        }. Revoke one or upgrade your plan first.`
      });
    }

    const created = createKey({
      accountId: account.id,
      name,
      scopes
    });

    return {
      created: {
        id: created.id,
        plaintext: created.plaintext,
        name: created.name
      }
    };
  },

  revoke: async ({ request, locals }) => {
    const account = locals.account!;
    const form = await request.formData();
    const id = (form.get('id') ?? '').toString();
    if (!id) return fail(400, { error: 'Missing key id.' });

    const ok = revokeKey(account.id, id);
    if (!ok) return fail(404, { error: 'Key not found.' });
    return { revokedId: id };
  }
};