Settings page for adding verified nostr pubkeys
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import { bech32 } from "bech32"
|
||||
|
||||
function hexToBytes (hex) {
|
||||
let bytes = []
|
||||
for (let c = 0; c < hex.length; c += 2) {
|
||||
bytes.push(parseInt(hex.substr(c, 2), 16))
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
// Connects to data-controller="settings--nostr-pubkey"
|
||||
export default class extends Controller {
|
||||
static targets = [ "noExtension", "setPubkey", "pubkeyBech32Input" ]
|
||||
static values = { userAddress: String, pubkeyHex: String, sharedSecret: String }
|
||||
|
||||
connect () {
|
||||
if (this.hasPubkeyHexValue && this.pubkeyHexValue.length > 0) {
|
||||
this.pubkeyBech32InputTarget.value = this.pubkeyBech32
|
||||
}
|
||||
|
||||
if (window.nostr) {
|
||||
this.setPubkeyTarget.disabled = false
|
||||
} else {
|
||||
this.noExtensionTarget.classList.remove("hidden")
|
||||
}
|
||||
}
|
||||
|
||||
async setPubkey () {
|
||||
this.setPubkeyTarget.disabled = true
|
||||
|
||||
try {
|
||||
const signedEvent = await window.nostr.signEvent({
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 1,
|
||||
tags: [],
|
||||
content: `Connect my public key to ${this.userAddressValue} (confirmation ${this.sharedSecretValue})`
|
||||
})
|
||||
|
||||
const res = await fetch("/settings/set_nostr_pubkey", {
|
||||
method: "POST", credentials: "include", headers: {
|
||||
"Accept": "application/json", 'Content-Type': 'application/json',
|
||||
"X-CSRF-Token": this.csrfToken
|
||||
}, body: JSON.stringify({ signed_event: signedEvent })
|
||||
});
|
||||
|
||||
window.location.reload()
|
||||
} catch (error) {
|
||||
console.warn('Unable to verify pubkey:', error.message)
|
||||
this.setPubkeyTarget.disabled = false
|
||||
}
|
||||
}
|
||||
|
||||
get pubkeyBech32 () {
|
||||
const words = bech32.toWords(hexToBytes(this.pubkeyHexValue))
|
||||
return bech32.encode('npub', words)
|
||||
}
|
||||
|
||||
get csrfToken () {
|
||||
const element = document.head.querySelector('meta[name="csrf-token"]')
|
||||
return element.getAttribute("content")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user