chore: clean & rename some api funcs

This commit is contained in:
MTG2000
2022-06-11 12:05:16 +03:00
parent dc6d462c18
commit 28549df6d4
6 changed files with 123 additions and 110 deletions

View File

@@ -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}`

View 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);
};

View File

@@ -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
}

View File

@@ -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,92 +10,55 @@ 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 })
if (tag !== 'login')
return res.status(400).json({ status: 'ERROR', reason: 'Invalid Tag Provided' })
// Verify login params
try {
await LnurlAuthService.verifySig(sig, k1, key)
} catch (error) {
return res.status(400).json({ status: 'ERROR', reason: 'Invalid Signature' })
}
try {
//Create user if not already existing
const user = await prisma.user.findFirst({ where: { pubKey: key } })
if (user === null) {
await prisma.user.create({
data: {
pubKey: key,
name: key,
avatar: `https://avatars.dicebear.com/api/bottts/${key}.svg`
}
})
}
// calc the hash of k1
const hash = createHash(k1);
// generate the auth jwt token
const hour = 3600000
const maxAge = 30 * 24 * hour;
const authToken = await new jose.SignJWT({ pubKey: key })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime('5min')
.setExpirationTime(maxAge)
//TODO: Set audience, issuer
.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")
// Verify login params
try {
await LnurlService.verifySig(sig, k1, key)
} catch (error) {
return res.status(400).json({ status: 'ERROR', reason: 'Invalid Signature' })
}
// associate the auth token with the hash in the db
await associateTokenToHash(hash, authToken);
try {
//Create user if not already existing
const user = await prisma.user.findFirst({ where: { pubKey: key } })
if (user === null) {
await prisma.user.create({
data: {
pubKey: key,
name: key,
avatar: `https://avatars.dicebear.com/api/bottts/${key}.svg`
}
})
}
return res.status(200).json({ status: "OK" })
// calc the hash of k1
const hash = createHash(k1);
// generate the auth jwt token
const hour = 3600000
const maxAge = 30 * 24 * hour;
const jwt = await new jose.SignJWT({ pubKey: key })
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt()
.setExpirationTime(maxAge)
//TODO: Set audience, issuer
.sign(Buffer.from(JWT_SECRET, 'utf-8'))
// associate the auth token with the hash in the db
console.log(hash);
await associateTokenToHash(hash, jwt);
// 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' })
}
} catch (error) {
return res.status(400).json({ status: 'ERROR', reason: 'Unexpected error happened, please try again' })
}
}