Skip to content

Instantly share code, notes, and snippets.

@divarvel
Last active March 12, 2023 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save divarvel/47b7665518246f0cf7b19b83b3ab81d6 to your computer and use it in GitHub Desktop.
Save divarvel/47b7665518246f0cf7b19b83b3ab81d6 to your computer and use it in GitHub Desktop.
import {Biscuit, Authorizer} from '@biscuit-auth/biscuit-wasm';
export function middleware(pubkey) {
return function(mkAuthorizer) {
return function(req, res, next) {
if(req.query.token) {
let parsed;
try {
let authorizer;
if(typeof mkAuthorizer === "function") {
authorizer = mkAuthorizer(req);
} else {
authorizer = mkAuthorizer;
}
parsed = Biscuit.fromBase64(req.query.token, pubkey);
authorizer.addToken(parsed);
const result = authorizer.authorize();
next();
} catch(e) {
console.log(JSON.stringify(e));
res.status(403).json(e);
}
} else {
res.status(401).send();
}
}
}
}
export function koa(pubkey) {
return function(mkAuthorizer) {
return function(ctx, next) {
if(ctx.query.token) {
let parsed;
try {
let authorizer;
if(typeof mkAuthorizer === "function") {
authorizer = mkAuthorizer(ctx);
} else {
authorizer = mkAuthorizer;
}
parsed = Biscuit.fromBase64(ctx.query.token, pubkey);
authorizer.addToken(parsed);
const result = authorizer.authorize();
next();
} catch(e) {
console.log(JSON.stringify(e));
ctx.status = 403;
ctx.body = e;
}
} else {
ctx.status = 401;
}
}
}
}
import express from "express";
import { biscuit, authorizer, KeyPair, Biscuit } from "@biscuit-auth/biscuit-wasm";
import { middleware } from "./biscuit.js";
import { webcrypto } from "node:crypto";
globalThis.crypto = webcrypto;
import {readdir} from "node:fs/promises";
import path from "node:path";
const app = express();
const port = 3000;
const keypair = new KeyPair();
const p = middleware(keypair.getPublicKey());
app.get(
"/protected/:dog",
p((req) => authorizer`allow if scope(${req.params.dog}, "read");`),
(req, res) => {
if(req.params.dog === 'puna') {
readdir("./assets/puna").then(files => {
const picName = files[Math.floor((Math.random()*files.length))];
res.sendFile(`${picName}`, {
root: path.resolve("assets/puna")
});
}).catch((e) => {
console.error(e);
res.send(`${req.params.dog}!`);
});
} else {
res.send(`${req.params.dog}!`);
}
}
);
app.listen(port, () => {
const b = biscuit`
scope("puna", "read");
`.build(keypair.getPrivateKey());
console.log("This token will grant you read access to /protected/puna");
console.log(b.toBase64());
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment