UNPKG

lightning-auth-and-payment

Version:

Lightning Network authentication and payment processing library for modern web applications

99 lines (81 loc) 2.43 kB
const express = require('express') const { LightningAuth } = require('lightning-auth-and-payment') const router = express.Router() // Initialize auth with your configuration const auth = new LightningAuth({ sessionSecret: process.env.SESSION_SECRET, cookieName: 'lightning-auth-session', cookieDomain: process.env.SESSION_COOKIE_DOMAIN, }) // Generate LNURL for authentication router.get('/lnurl', async (req, res) => { try { const k1 = await auth.generateK1Challenge() const lnurl = auth.generateLnurl(k1, `${req.protocol}://${req.get('host')}/api/auth/callback`) res.json({ k1, lnurl, qr: `lightning:${lnurl}`, }) } catch (error) { console.error('LNURL generation error:', error) res.status(500).json({ error: 'Failed to generate LNURL' }) } }) // Handle authentication callback router.get('/callback', async (req, res) => { try { const { k1, sig, key } = req.query if (!k1 || !sig || !key) { return res.status(400).json({ error: 'Missing required parameters' }) } // Verify the signature const isValid = await auth.verifyLnurlSignature(k1, sig, key) if (!isValid) { return res.status(400).json({ error: 'Invalid signature' }) } // Create session const session = await auth.createSession({ userId: key }) // Set cookie and redirect res.cookie( auth.getCookieConfig().name, session, auth.getCookieConfig() ) res.redirect('/') } catch (error) { console.error('Auth callback error:', error) res.status(500).json({ error: 'Authentication failed' }) } }) // Check authentication status router.get('/status', async (req, res) => { try { const session = await auth.verifySession(req) if (!session) { return res.json({ authenticated: false }) } res.json({ authenticated: true, userId: session.userId, }) } catch (error) { console.error('Auth status error:', error) res.status(500).json({ error: 'Failed to check authentication status' }) } }) // Logout router.post('/logout', async (req, res) => { try { res.cookie( auth.getClearCookieConfig().name, '', auth.getClearCookieConfig() ) res.json({ success: true }) } catch (error) { console.error('Logout error:', error) res.status(500).json({ error: 'Failed to logout' }) } }) module.exports = router