Add login via nostr (web extension)
This commit is contained in:
53
app/javascript/controllers/nostr_login_controller.js
Normal file
53
app/javascript/controllers/nostr_login_controller.js
Normal file
@@ -0,0 +1,53 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
|
||||
// Connects to data-controller="nostr-login"
|
||||
export default class extends Controller {
|
||||
static targets = [ "loginForm", "loginButton" ]
|
||||
static values = { site: String, sharedSecret: String }
|
||||
|
||||
connect() {
|
||||
if (window.nostr) {
|
||||
this.loginButtonTarget.disabled = false
|
||||
this.loginFormTarget.classList.remove("hidden")
|
||||
}
|
||||
}
|
||||
|
||||
async login () {
|
||||
this.loginButtonTarget.disabled = true
|
||||
|
||||
try {
|
||||
// Auth based on NIP-42
|
||||
const signedEvent = await window.nostr.signEvent({
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 22242,
|
||||
tags: [
|
||||
["site", this.siteValue],
|
||||
["challenge", this.sharedSecretValue]
|
||||
],
|
||||
content: ""
|
||||
})
|
||||
|
||||
const res = await fetch("/users/nostr_login", {
|
||||
method: "POST", credentials: "include", headers: {
|
||||
"Accept": "application/json", 'Content-Type': 'application/json',
|
||||
"X-CSRF-Token": this.csrfToken
|
||||
}, body: JSON.stringify({ signed_event: signedEvent })
|
||||
})
|
||||
|
||||
if (res.status === 200) {
|
||||
res.json().then(r => { window.location.href = r.redirect_url })
|
||||
} else {
|
||||
window.location.reload()
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Unable to authenticate:', error.message)
|
||||
} finally {
|
||||
this.loginButtonTarget.disabled = false
|
||||
}
|
||||
}
|
||||
|
||||
get csrfToken () {
|
||||
const element = document.head.querySelector('meta[name="csrf-token"]')
|
||||
return element.getAttribute("content")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user