feat: continue work

Signed-off-by: Avior <github@avior.me>
This commit is contained in:
2023-06-28 01:15:56 +02:00
parent d76f412b82
commit 9530be5c43
16 changed files with 148 additions and 86 deletions

11
src/env.d.ts vendored
View File

@ -1,6 +1,5 @@
/// <reference path="../.astro/types.d.ts" />
/// <reference types="astro/client" />
/// <reference types="./libs/ResponseBuilder" />
interface ImportMetaEnv {
PRUSASLICER_PATH?: string
@ -21,6 +20,14 @@ declare namespace App {
* authentification key is the api key or the session token
*/
authKey?: string
responseBuilder?: ResponseBuilder
responseBuilder: {
body(body: string | Buffer | object | null | undefined): this
headers(headers: HeadersInit ): this
addHeader(key: string, value: string): this
addHeaders(headers: Record<string, string>): this
removeHeader(key: string): this
status(status: number): this
build(): Response
} // ./libs/ResponseBuilder object
}
}

View File

@ -24,7 +24,7 @@ export default class RateLimiter {
/**
* timeSpan in seconds
*/
public static timeSpan = 600
public static timeSpan = 60
private static instance: RateLimiter = new RateLimiter()
public static getInstance(): RateLimiter {

View File

@ -6,10 +6,12 @@ import { objectLoop } from '@dzeio/object-util'
export default class ResponseBuilder {
private _body: BodyInit | null | undefined
public body(body: string | object | null | undefined) {
if (typeof body === 'object') {
public body(body: string | Buffer | object | null | undefined) {
if (typeof body === 'object' && !(body instanceof Buffer)) {
this._body = JSON.stringify(body)
this.addHeader('Content-Type', 'application/json')
} else if (body instanceof Buffer) {
this._body = body.toString()
} else {
this._body = body
}

View File

@ -2,7 +2,7 @@ import DaoFactory from '../models/DaoFactory'
import CookieManager from './CookieManager'
import { buildRFC7807 } from './RFCs/RFC7807'
interface Permission {
export interface Permission {
name: string
/**
* if set it will be usable by users

View File

@ -1,16 +1,43 @@
import { objectLoop } from '@dzeio/object-util'
import URLManager from '@dzeio/url-manager'
import { defineMiddleware } from "astro/middleware"
import { validateAuth } from '../libs/validateAuth'
import { buildRFC7807 } from '../libs/RFCs/RFC7807'
import { Permission, validateAuth } from '../libs/validateAuth'
const endpointsPermissions: Record<string, Permission> = {
'/api/v1/users/[userId]/configs/[configId]/files/[fileName]': {
api: true,
cookie: true,
name: 'configs.get'
}
}
function objectFind(obj: object, fn: (value: any, key: any) => boolean): {key: string, value: any} | null {
let res: {key: string, value: any} | null = null
objectLoop(obj, (value, key) => {
const tmp = fn(value, key)
if (tmp) {
res = {
key, value
}
}
return tmp
})
return res
}
// `context` and `next` are automatically typed
export default defineMiddleware(async (context, next) => {
if (!context.request.url.includes('api')) {
return next()
}
const auth = await validateAuth(context.request, {
name: 'slicing.slice',
api: true,
cookie: true
})
const permission = objectFind(endpointsPermissions, (_, key) => new URLManager(key).toString(context.params as any) === context.url.pathname)
if (!permission) {
return buildRFC7807({
type: 'idk'
})
}
const auth = await validateAuth(context.request, permission.value)
if (typeof auth === 'object') {
return auth
}

View File

@ -1,9 +1,21 @@
import { defineMiddleware } from "astro/middleware"
import { buildRFC7807 } from '../libs/RFCs/RFC7807'
import ResponseBuilder from '../libs/ResponseBuilder'
// `context` and `next` are automatically typed
export default defineMiddleware(async (context, next) => {
context.locals.responseBuilder = new ResponseBuilder()
export default defineMiddleware(async ({ request, locals }, next) => {
locals.responseBuilder = new ResponseBuilder()
console.log(`[${new Date().toISOString()}] ${request.headers.get('user-agent')?.slice(0, 32).padEnd(32)} ${request.method.padEnd(7)} ${request.url}`)
return next()
try {
const res = await next()
console.log(`[${new Date().toISOString()}] ${request.headers.get('user-agent')?.slice(0, 32).padEnd(32)} ${request.method.padEnd(7)} ${res.status} ${request.url}`)
return res
} catch (e) {
console.error(e)
return buildRFC7807({
type: '/docs/errors/global-error',
status: 500
})
}
})

View File

@ -1,25 +0,0 @@
import type { APIRoute } from 'astro'
import crypto from 'node:crypto'
import { validateAuth } from '../../../../../libs/validateAuth'
import DaoFactory from '../../../../../models/DaoFactory'
export const post: APIRoute = async ({ params, request }) => {
validateAuth(request, {
name: 'keys.create',
cookie: true,
api: false
})
const userId = params.userId as string
const dao = await DaoFactory.get('apiKey').create({
user: userId,
key: crypto.randomUUID(),
permissions: [
'admin.user.list'
]
})
return {
status: 201,
body: JSON.stringify(dao)
}
}

View File

@ -1,17 +0,0 @@
import type { APIRoute } from 'astro'
import { validateAuth } from '../../../libs/validateAuth'
export const get: APIRoute = async ({ params, request }) => {
const requestInvalid = await validateAuth(request, {
name: 'user.list',
api: false,
cookie: true
})
if (requestInvalid) {
return requestInvalid
}
return {
status: 200,
body: JSON.stringify({iam: true})
}
}

View File

@ -1,10 +1,8 @@
import { objectOmit } from '@dzeio/object-util'
import type { APIRoute } from 'astro'
import { buildRFC7807 } from '../../../../../../../libs/RFCs/RFC7807'
import DaoFactory from '../../../../../../../models/DaoFactory'
import { buildRFC7807 } from '../../../../../../../../libs/RFCs/RFC7807'
import DaoFactory from '../../../../../../../../models/DaoFactory'
export const get: APIRoute = async ({ params, request }) => {
const userId = params.userId as string
export const get: APIRoute = async ({ params, locals }) => {
const configId = params.configId as string
const fileName = params.fileName as string
@ -19,8 +17,8 @@ export const get: APIRoute = async ({ params, request }) => {
const file = dao.files.find((it) => it.name === fileName)
return {
status: 200,
body: file?.data
}
return locals.responseBuilder
.status(200)
.body(file?.data)
.build()
}

View File

@ -1,9 +1,10 @@
import { objectOmit } from '@dzeio/object-util'
import type { APIRoute } from 'astro'
import { buildRFC7807 } from '../../../../../libs/RFCs/RFC7807'
import DaoFactory from '../../../../../models/DaoFactory'
import { buildRFC7807 } from '../../../../../../libs/RFCs/RFC7807'
import StatusCode from '../../../../../../libs/StatusCode'
import DaoFactory from '../../../../../../models/DaoFactory'
export const post: APIRoute = async ({ params, request }) => {
export const post: APIRoute = async ({ params, request, locals }) => {
const userId = params.userId as string
const body = request.body
@ -37,8 +38,8 @@ export const post: APIRoute = async ({ params, request }) => {
data: buffer
}]
})
return {
status: 201,
body: JSON.stringify(objectOmit(dao ?? {}, 'files'))
}
return locals.responseBuilder
.status(StatusCode.CREATED)
.body(objectOmit(dao ?? {}, 'files'))
.build()
}

View File

@ -0,0 +1,20 @@
import type { APIRoute } from 'astro'
import crypto from 'node:crypto'
import StatusCode from '../../../../../../libs/StatusCode'
import DaoFactory from '../../../../../../models/DaoFactory'
export const post: APIRoute = async ({ params, locals }) => {
const userId = params.userId as string
const dao = await DaoFactory.get('apiKey').create({
user: userId,
key: crypto.randomUUID(),
permissions: [
'admin.user.list'
]
})
return locals.responseBuilder
.status(StatusCode.CREATED)
.body(dao)
.build()
}

View File

@ -0,0 +1,17 @@
import type { APIRoute } from 'astro'
import { buildRFC7807 } from '../../../../libs/RFCs/RFC7807'
import StatusCode from '../../../../libs/StatusCode'
export const get: APIRoute = async ({ locals }) => {
return locals.responseBuilder
.status(200)
.body({iam: true})
.build()
}
export const options: APIRoute = async () => {
return buildRFC7807({
status: StatusCode.METHOD_NOT_ALLOWED,
details: 'Allowed methods: "GET"'
})
}