0.1.3Updated 10 days ago
import { Draco } from "@draco/connect";

enum Permissions {
  /** Whether the user is allowed to do fake tasks */
  FAKE_PERM = "fake_permission",
  /** Whether the user is allowed to do fake tasks with genuine intent */
  REAL_FAKE_PERM = "real_fake_permission",
  /** Whether the user is allowed to do genuine tasks with fake intent */
  FAKE_REAL_PERM = "fake_real_permission"
}
await Draco.Configure({
  permissions: Permissions
})

Deno.serve({ port: 9000 }, async (req, _info) => {
  const draco_cookie = Draco.GetCookie(req);
  if(!draco_cookie) return Draco.CookieRedirect(req);

  const url = new URL(req.url);
  const pathname = url.pathname;

  const user = await Draco.GetUser(req);

  if(pathname === '/') { return Render(HomePage(user)) }
  if(pathname === '/sign-in') {
    if(!user) return await Draco.LoginRedirect(draco_cookie, 'http://localhost:9000');
    return Redirect('/');
  }
  if(pathname === '/sign-out') {
    if(user) return Draco.LogoutRedirect();
    return Redirect('/');
  }

  return Render(`<h1>404 Not Found</h1>`);
})

const HomePage = (user?: Draco.User.Class | null) => `
    <div> ${UserComponent(user)} </div>
    <div>
      ${user ? `
        <a href="/sign-out">
          <button>Sign Out</button>
        </a>
        ` : `
        <a href="/sign-in">
          <button>Sign In</button>
        </a>
      ` }
    </div>

`.replace(/\s{2,}/g, ' ').trim();

const UserComponent = (user?: Draco.User.Class | null) => `
  <h1>
    Hello, 
      ${user ? `
        ${user.name} ${user.surname}
      ` : `
        Guest
      `}
  </h1>
  ${ user ? `
    <br />
    <p>You can ${user.is_super_admin ? 'do it all!' : user.permissions.join(', ')}</p>
  ` : ''}
`.replace(/\s{2,}/g, ' ').trim();

const Layout = (body: string) => `
  <!DOCTYPE html>
  <html>
    <head>
      <title>@draco/connect test</title>
      <meta charset="UTF-8" />
      <meta name="description" content="Free Web tutorials" />
      <meta name="keywords" content="HTML, CSS, JavaScript" />
      <meta name="author" content="John Doe" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    </head>
    <body>
      <div style="margin: 0 auto; max-width: 800px;">
        ${body}
      </div>
    </body>
  </html>
`.replace(/\s{2,}/g, ' ').trim();

const Render = (body: string) => new Response(Layout(body), {
  headers: {
    'Content-Type': 'text/html'
  }
})

const Redirect = (url: string) => new Response(null, {
  headers: {
    Location: url
  },
  status: 307
});