mirror of
https://github.com/aljazceru/landscape-template.git
synced 2025-12-18 14:54:23 +01:00
chore: clean & rename some api funcs
This commit is contained in:
@@ -3,24 +3,24 @@ const crypto = require('crypto')
|
||||
const { prisma } = require('../../prisma')
|
||||
const { CONSTS } = require('../../utils')
|
||||
|
||||
async function generateSecret() {
|
||||
let secret = null
|
||||
async function generateK1() {
|
||||
let k1 = null
|
||||
const maxAttempts = 5
|
||||
let attempt = 0
|
||||
while (secret === null && attempt < maxAttempts) {
|
||||
secret = crypto.randomBytes(32).toString('hex')
|
||||
const hash = createHash(secret)
|
||||
while (k1 === null && attempt < maxAttempts) {
|
||||
k1 = crypto.randomBytes(32).toString('hex')
|
||||
const hash = createHash(k1)
|
||||
const isUsed = await isHashUsed(hash);
|
||||
if (isUsed) {
|
||||
secret = null
|
||||
k1 = null
|
||||
}
|
||||
attempt++
|
||||
}
|
||||
if (!secret) {
|
||||
const message = 'Too many failed attempts to generate unique secret'
|
||||
if (!k1) {
|
||||
const message = 'Too many failed attempts to generate unique k1'
|
||||
throw new Error(message)
|
||||
}
|
||||
return secret
|
||||
return k1
|
||||
}
|
||||
|
||||
function isHashUsed(hash) {
|
||||
@@ -58,7 +58,7 @@ function removeExpiredHashes() {
|
||||
|
||||
async function generateAuthUrl() {
|
||||
const hostname = CONSTS.LNURL_AUTH_HOST;
|
||||
const secret = await generateSecret();
|
||||
const secret = await generateK1();
|
||||
const hash = createHash(secret);
|
||||
await addHash(hash)
|
||||
const url = `${hostname}?tag=login&k1=${secret}`
|
||||
57
api/functions/get-login-url/get-login-url.js
Normal file
57
api/functions/get-login-url/get-login-url.js
Normal file
@@ -0,0 +1,57 @@
|
||||
|
||||
const LnurlAuthService = require('../../auth/services/lnurlAuth.service')
|
||||
const serverless = require('serverless-http');
|
||||
const { createExpressApp } = require('../../modules');
|
||||
const express = require('express');
|
||||
const jose = require('jose');
|
||||
const { JWT_SECRET } = require('../../utils/consts');
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
const getLoginUrl = async (req, res) => {
|
||||
try {
|
||||
const data = await LnurlAuthService.generateAuthUrl();
|
||||
const maxAge = 1000 * 60 * 3; //2 mins
|
||||
|
||||
const jwt = await new jose.SignJWT({ hash: data.secretHash })
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setIssuedAt()
|
||||
.setExpirationTime('5min')
|
||||
.sign(Buffer.from(JWT_SECRET, 'utf-8'))
|
||||
|
||||
return res
|
||||
.status(200)
|
||||
.cookie('login_session', jwt, {
|
||||
maxAge,
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: "none",
|
||||
})
|
||||
.json(data);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
res.status(500).send("Unexpected error happened, please try again")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
let app;
|
||||
|
||||
if (process.env.LOCAL) {
|
||||
app = createExpressApp()
|
||||
app.get('/get-login-url', getLoginUrl);
|
||||
}
|
||||
else {
|
||||
const router = express.Router();
|
||||
router.get('/get-login-url', getLoginUrl)
|
||||
app = createExpressApp(router)
|
||||
}
|
||||
|
||||
|
||||
const handler = serverless(app);
|
||||
exports.handler = async (event, context) => {
|
||||
return await handler(event, context);
|
||||
};
|
||||
@@ -1,28 +1,26 @@
|
||||
|
||||
const serverless = require('serverless-http');
|
||||
const { getAuthTokenByHash } = require('../../auth/services/lnurl.service');
|
||||
const { createExpressApp } = require('../../modules');
|
||||
const express = require('express');
|
||||
const jose = require('jose');
|
||||
const { JWT_SECRET } = require('../../utils/consts');
|
||||
const lnurlService = require('../../auth/services/lnurl.service');
|
||||
const lnurlAuthService = require('../../auth/services/lnurlAuth.service');
|
||||
|
||||
|
||||
const isLoggedInHandler = async (req, res) => {
|
||||
try {
|
||||
const login_session = req.cookies?.login_session;
|
||||
if (login_session) {
|
||||
|
||||
const { payload } = await jose.jwtVerify(login_session, Buffer.from(JWT_SECRET), {
|
||||
algorithms: ['HS256'],
|
||||
});
|
||||
const hash = payload.hash;
|
||||
const token = await getAuthTokenByHash(hash);
|
||||
if (!token)
|
||||
const authToken = await lnurlAuthService.getAuthTokenByHash(hash);
|
||||
if (!authToken)
|
||||
throw new Error("Not logged in yet")
|
||||
|
||||
lnurlService.removeHash(hash).catch();
|
||||
lnurlService.removeExpiredHashes().catch();
|
||||
lnurlAuthService.removeHash(hash).catch();
|
||||
lnurlAuthService.removeExpiredHashes().catch();
|
||||
|
||||
res
|
||||
.status(200)
|
||||
@@ -31,7 +29,7 @@ const isLoggedInHandler = async (req, res) => {
|
||||
httpOnly: true,
|
||||
sameSite: "none",
|
||||
})
|
||||
.cookie('Authorization', token, {
|
||||
.cookie('Authorization', authToken, {
|
||||
maxAge: 3600000 * 24 * 30,
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
@@ -42,24 +40,16 @@ const isLoggedInHandler = async (req, res) => {
|
||||
});
|
||||
} else {
|
||||
res.json({
|
||||
me: null
|
||||
logged_in: false
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
res.json({
|
||||
logged_in: false
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
// get session token
|
||||
// check DB to see if this token has an accossiated jwt auth token to it
|
||||
// if yes:
|
||||
// set the auth token to cookie
|
||||
// remove the session token
|
||||
// remove the data row
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
|
||||
const { prisma } = require('../../prisma');
|
||||
const LnurlService = require('../../auth/services/lnurl.service')
|
||||
const LnurlAuthService = require('../../auth/services/lnurlAuth.service')
|
||||
const serverless = require('serverless-http');
|
||||
const { createHash, associateTokenToHash } = require('../../auth/services/lnurl.service');
|
||||
const { createHash, associateTokenToHash } = require('../../auth/services/lnurlAuth.service');
|
||||
const { createExpressApp } = require('../../modules');
|
||||
const express = require('express');
|
||||
const jose = require('jose');
|
||||
@@ -10,46 +10,14 @@ const { JWT_SECRET } = require('../../utils/consts');
|
||||
|
||||
|
||||
|
||||
const router = express.Router();
|
||||
router.get('/login', (req, res) => {
|
||||
res.cookie('login_session', 'value', {
|
||||
maxAge: 1000 * 60 * 2, // 2 mins
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: "none",
|
||||
})
|
||||
})
|
||||
|
||||
const loginHandler = async (req, res) => {
|
||||
const { tag, k1, sig, key } = req.query;
|
||||
// Generate an auth URL
|
||||
if (!sig || !key) {
|
||||
const data = await LnurlService.generateAuthUrl();
|
||||
const maxAge = 1000 * 60 * 3; //2 mins
|
||||
|
||||
const jwt = await new jose.SignJWT({ hash: data.secretHash })
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setIssuedAt()
|
||||
.setExpirationTime('5min')
|
||||
.sign(Buffer.from(JWT_SECRET, 'utf-8'))
|
||||
|
||||
return res
|
||||
.status(200)
|
||||
.cookie('login_session', jwt, {
|
||||
maxAge,
|
||||
secure: true,
|
||||
httpOnly: true,
|
||||
sameSite: "none",
|
||||
})
|
||||
.json(data);
|
||||
}
|
||||
else {
|
||||
if (tag !== 'login')
|
||||
return res.status(400).send("Invalid tag provided")
|
||||
|
||||
return res.status(400).json({ status: 'ERROR', reason: 'Invalid Tag Provided' })
|
||||
// Verify login params
|
||||
try {
|
||||
await LnurlService.verifySig(sig, k1, key)
|
||||
await LnurlAuthService.verifySig(sig, k1, key)
|
||||
} catch (error) {
|
||||
return res.status(400).json({ status: 'ERROR', reason: 'Invalid Signature' })
|
||||
|
||||
@@ -76,7 +44,7 @@ const loginHandler = async (req, res) => {
|
||||
const hour = 3600000
|
||||
const maxAge = 30 * 24 * hour;
|
||||
|
||||
const jwt = await new jose.SignJWT({ pubKey: key })
|
||||
const authToken = await new jose.SignJWT({ pubKey: key })
|
||||
.setProtectedHeader({ alg: 'HS256' })
|
||||
.setIssuedAt()
|
||||
.setExpirationTime(maxAge)
|
||||
@@ -84,18 +52,13 @@ const loginHandler = async (req, res) => {
|
||||
.sign(Buffer.from(JWT_SECRET, 'utf-8'))
|
||||
|
||||
// associate the auth token with the hash in the db
|
||||
console.log(hash);
|
||||
await associateTokenToHash(hash, jwt);
|
||||
await associateTokenToHash(hash, authToken);
|
||||
|
||||
// LnurlService.removeHash(LnurlService.createHash(k1)).catch();
|
||||
// LnurlService.removeExpiredHashes().catch();
|
||||
|
||||
return res.status(200).json({ status: "OK" })
|
||||
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
return res.status(200).json({ status: 'ERROR', reason: 'Unexpected error happened, please try again' })
|
||||
}
|
||||
return res.status(400).json({ status: 'ERROR', reason: 'Unexpected error happened, please try again' })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,6 +24,12 @@ functions:
|
||||
- http:
|
||||
path: graphql
|
||||
method: get
|
||||
get-login-url:
|
||||
handler: api/functions/get-login-url/get-login-url.handler
|
||||
events:
|
||||
- http:
|
||||
path: get-login-url
|
||||
method: get
|
||||
login:
|
||||
handler: api/functions/login/login.handler
|
||||
events:
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import { useCallback, useEffect, useState } from "react"
|
||||
import { Helmet } from "react-helmet";
|
||||
import { BsFillLightningChargeFill } from "react-icons/bs";
|
||||
import { Grid } from "react-loader-spinner";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useMeQuery } from "src/graphql"
|
||||
import { CONSTS } from "src/utils";
|
||||
import { QRCodeSVG } from 'qrcode.react';
|
||||
import { IoQrCode, IoRocketOutline } from "react-icons/io5";
|
||||
import { IoRocketOutline } from "react-icons/io5";
|
||||
import Button from "src/Components/Button/Button";
|
||||
import { FiCopy } from "react-icons/fi";
|
||||
import useCopyToClipboard from "src/utils/hooks/useCopyToClipboard";
|
||||
@@ -14,7 +13,7 @@ import useCopyToClipboard from "src/utils/hooks/useCopyToClipboard";
|
||||
|
||||
|
||||
const fetchLnurlAuth = async () => {
|
||||
const res = await fetch(CONSTS.apiEndpoint + '/login', {
|
||||
const res = await fetch(CONSTS.apiEndpoint + '/get-login-url', {
|
||||
credentials: 'include'
|
||||
})
|
||||
const data = await res.json()
|
||||
@@ -88,8 +87,6 @@ export default function LoginPage() {
|
||||
const refetch = meQuery.refetch;
|
||||
const startPolling = useCallback(
|
||||
() => {
|
||||
console.log('HEEY');
|
||||
|
||||
const interval = setInterval(() => {
|
||||
fetch(CONSTS.apiEndpoint + '/is-logged-in', {
|
||||
credentials: 'include'
|
||||
|
||||
Reference in New Issue
Block a user