Skip to content

Commit

Permalink
Merge pull request #35 from biscuit-auth/authorizer-merge
Browse files Browse the repository at this point in the history
Add middleware auth support for express
  • Loading branch information
divarvel committed Apr 24, 2023
2 parents a6ab128 + 8a468ce commit 46e97e5
Show file tree
Hide file tree
Showing 9 changed files with 1,107 additions and 36 deletions.
5 changes: 5 additions & 0 deletions CHANGELOG.md
@@ -1,3 +1,8 @@
# Not released

- Add `merge` and `mergeBlock` to `Authorizer` (#35) (Clément Delafargue)
- Add an express middleware for proctecting endpoints (#35) (Clément Delafargue)

# `0.4.0-beta2`

- Fix `appendThirdPartyBlock` (#34) (Clément Delafargue)
Expand Down
43 changes: 43 additions & 0 deletions examples/node/express.js
@@ -0,0 +1,43 @@
import express from "express";
import { biscuit, authorizer, KeyPair, middleware, PrivateKey } from "@biscuit-auth/biscuit-wasm";
import { readdir } from "node:fs/promises";
import path from "node:path";

const app = express();
const port = 3000;

const pk = "510fa4152b316a29c16e9459553e34abe891f006175bd61b7daca8b19f14ab90";
const keypair = KeyPair.fromPrivateKey(PrivateKey.fromString(pk));
const p = middleware({
publicKey: keypair.getPublicKey(),
priorityAuthorizer: req => authorizer`allow if ${req.headers.prio ?? ""} == "true";`,
fallbackAuthorizer: req => authorizer`allow if ${req.headers.fall ?? ""} == "true";`,
});

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());
});

0 comments on commit 46e97e5

Please sign in to comment.