Add new purchase API

This commit is contained in:
Jonas Lochmann
2022-09-26 02:00:00 +02:00
parent 35acd05d08
commit 58a6359a3e
18 changed files with 534 additions and 22 deletions
+32 -10
View File
@@ -15,21 +15,16 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { SignJWT } from 'jose'
import { SignJWT, jwtVerify } from 'jose'
import { config } from '../config'
import { IdentityTokenPayload, IdentityTokenCreatePayload } from '../api/schema'
import { isIdentityTokenPayload } from '../api/validator'
export async function createIdentityToken({ purpose, familyId, userId, mail }: {
purpose: string
familyId: string
userId: string
mail: string
}) {
if (config.signSecret === '') throw new MissingSignSecretException()
export async function createIdentityToken({ purpose, familyId, userId, mail }: IdentityTokenCreatePayload) {
const jwt = await new SignJWT({ purpose, familyId, userId, mail })
.setExpirationTime('7d')
.setProtectedHeader({ alg: 'HS512' })
.sign(Buffer.from(config.signSecret, 'utf8'))
.sign(getSignSecret())
return Buffer.from(jwt, 'ascii')
.toString('base64')
@@ -38,4 +33,31 @@ export async function createIdentityToken({ purpose, familyId, userId, mail }: {
.join('\n')
}
export async function verifyIdentitifyToken(token: string): Promise<IdentityTokenPayload> {
try {
const { payload } = await jwtVerify(
Buffer.from(token, 'base64').toString('ascii'),
getSignSecret(),
{ algorithms: ['HS512'] }
)
if (!isIdentityTokenPayload(payload)) throw new BadPayloadException()
return payload
} catch (ex) {
if (ex instanceof TokenValidationException) throw ex
else if (ex instanceof Error) throw new TokenValidationException(ex.message)
else throw ex
}
}
function getSignSecret(): Buffer {
if (config.signSecret === '') throw new MissingSignSecretException()
return Buffer.from(config.signSecret, 'utf8')
}
export class MissingSignSecretException extends Error {}
export class TokenValidationException extends Error {}
class BadPayloadException extends TokenValidationException { constructor() { super('bad payload') } }