mirror of
https://codeberg.org/timelimit/timelimit-server.git
synced 2026-08-31 19:03:45 +02:00
Add new purchase API
This commit is contained in:
+32
-10
@@ -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') } }
|
||||
|
||||
Reference in New Issue
Block a user