File size: 1,521 Bytes
d2b36e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { createCookieSessionStorage, redirect } from '@remix-run/cloudflare';
import { env } from 'node:process';

const USER_SESSION_KEY = 'userId';

function createSessionStorage(cloudflareEnv: Env) {
  return createCookieSessionStorage({
    cookie: {
      name: '__session',
      httpOnly: true,
      path: '/',
      sameSite: 'lax',
      secrets: [env.SESSION_SECRET || cloudflareEnv.SESSION_SECRET],
      secure: false,
    },
  });
}

export async function getSession(request: Request, env: Env) {
  const sessionStorage = createSessionStorage(env);
  const cookie = request.headers.get('Cookie');

  return { session: await sessionStorage.getSession(cookie), sessionStorage };
}

export async function logout(request: Request, env: Env) {
  const { session, sessionStorage } = await getSession(request, env);

  return redirect('/login', {
    headers: {
      'Set-Cookie': await sessionStorage.destroySession(session),
    },
  });
}

export async function isAuthenticated(request: Request, env: Env) {
  const { session } = await getSession(request, env);
  const userId = session.get(USER_SESSION_KEY);

  return !!userId;
}

export async function createUserSession(request: Request, env: Env): Promise<ResponseInit> {
  const { session, sessionStorage } = await getSession(request, env);

  session.set(USER_SESSION_KEY, 'anonymous_user');

  return {
    headers: {
      'Set-Cookie': await sessionStorage.commitSession(session, {
        maxAge: 60 * 60 * 24 * 7, // 7 days,
      }),
    },
  };
}