Redirect npub and nprofile to username if exists

This commit is contained in:
Râu Cao 2024-10-20 23:05:45 +02:00
parent 9a19f7249c
commit 0e5b4b1807
Signed by: raucao
GPG Key ID: 37036C356E56CC51
4 changed files with 35 additions and 11 deletions

View File

@ -1,6 +1,7 @@
import { Context } from "@oak/oak";
import { nip19 } from "@nostr/tools";
import { log } from "../log.ts";
import { lookupUsernameByPubkey } from "../ldap.ts";
import { fetchProfileEvent } from "../nostr.ts";
import { profilePageHtml } from "../html.ts"
@ -10,12 +11,10 @@ const nprofileHandler = async function (ctx: Context) {
try {
const r = nip19.decode(nprofile);
const profileEvent = await fetchProfileEvent(r.data.pubkey);
const username = await lookupUsernameByPubkey(r.data.pubkey);
if (profileEvent) {
const html = profilePageHtml(profileEvent);
ctx.response.body = html;
if (username) {
ctx.response.redirect(`/@${username}`);
} else {
ctx.response.status = 404;
ctx.response.body = "Not Found";

View File

@ -1,6 +1,7 @@
import { Context } from "@oak/oak";
import { nip19 } from "@nostr/tools";
import { log } from "../log.ts";
import { lookupUsernameByPubkey } from "../ldap.ts";
import { fetchProfileEvent } from "../nostr.ts";
import { profilePageHtml } from "../html.ts"
@ -10,12 +11,10 @@ const npubHandler = async function (ctx: Context) {
try {
const r = nip19.decode(npub);
const profileEvent = await fetchProfileEvent(r.data);
const username = await lookupUsernameByPubkey(r.data);
if (profileEvent) {
const html = profilePageHtml(profileEvent);
ctx.response.body = html;
if (username) {
ctx.response.redirect(`/@${username}`);
} else {
ctx.response.status = 404;
ctx.response.body = "Not Found";

View File

@ -10,6 +10,12 @@ const usernameHandler = async function (ctx: Context) {
const username = ctx.params.path.replace(/^@/, '');;
const pubkey = await lookupPubkeyByUsername(username);
if (!pubkey) {
ctx.response.status = 404;
ctx.response.body = "Not Found";
return;
}
try {
const profileEvent = await fetchProfileEvent(pubkey);

22
ldap.ts
View File

@ -14,7 +14,7 @@ const config = {
const client = new Client({ url: config.url });
export async function lookupPubkeyByUsername (username) {
export async function lookupPubkeyByUsername (username: string) {
let pubkey;
try {
@ -33,3 +33,23 @@ export async function lookupPubkeyByUsername (username) {
return pubkey;
}
}
export async function lookupUsernameByPubkey (pubkey: string) {
let username;
try {
await client.bind(config.bindDN, config.password);
const { searchEntries } = await client.search(config.searchDN, {
filter: `(nostrKey=${pubkey})`,
attributes: ['cn']
});
username = searchEntries[0]?.cn;
} catch (ex) {
log(ex, "red");
} finally {
await client.unbind();
return username;
}
}