forked from geolba/tethys.backend
- update to AdonisJS 6
This commit is contained in:
parent
f828ca4491
commit
cb51a4136f
16
ace
16
ace
|
@ -1,16 +0,0 @@
|
|||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Ace Commands
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| This file is the entry point for running ace commands.
|
||||
|
|
||||
*/
|
||||
|
||||
require('reflect-metadata')
|
||||
require('source-map-support').install({ handleUncaughtExceptions: false })
|
||||
|
||||
const { Ignitor } = require('@adonisjs/core/build/standalone')
|
||||
new Ignitor(__dirname)
|
||||
.ace()
|
||||
.handle(process.argv.slice(2))
|
|
@ -1,628 +0,0 @@
|
|||
{
|
||||
"commands": {
|
||||
"index:datasets": {
|
||||
"settings": {
|
||||
"loadApp": true,
|
||||
"stayAlive": false
|
||||
},
|
||||
"commandPath": "./commands/IndexDatasets",
|
||||
"commandName": "index:datasets",
|
||||
"description": "Index datasets based on publish_id",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "publish-id",
|
||||
"propertyName": "publish_id",
|
||||
"type": "number",
|
||||
"alias": "p"
|
||||
}
|
||||
]
|
||||
},
|
||||
"validate:checksum": {
|
||||
"settings": {
|
||||
"loadApp": true,
|
||||
"stayAlive": false
|
||||
},
|
||||
"commandPath": "./commands/ValidateChecksum",
|
||||
"commandName": "validate:checksum",
|
||||
"description": "",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": []
|
||||
},
|
||||
"dump:rcfile": {
|
||||
"settings": {},
|
||||
"commandPath": "@adonisjs/core/build/commands/DumpRc",
|
||||
"commandName": "dump:rcfile",
|
||||
"description": "Dump contents of .adonisrc.json file along with defaults",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": []
|
||||
},
|
||||
"list:routes": {
|
||||
"settings": {
|
||||
"loadApp": true,
|
||||
"stayAlive": true
|
||||
},
|
||||
"commandPath": "@adonisjs/core/build/commands/ListRoutes/index",
|
||||
"commandName": "list:routes",
|
||||
"description": "List application routes",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "verbose",
|
||||
"propertyName": "verbose",
|
||||
"type": "boolean",
|
||||
"description": "Display more information"
|
||||
},
|
||||
{
|
||||
"name": "reverse",
|
||||
"propertyName": "reverse",
|
||||
"type": "boolean",
|
||||
"alias": "r",
|
||||
"description": "Reverse routes display"
|
||||
},
|
||||
{
|
||||
"name": "methods",
|
||||
"propertyName": "methodsFilter",
|
||||
"type": "array",
|
||||
"alias": "m",
|
||||
"description": "Filter routes by method"
|
||||
},
|
||||
{
|
||||
"name": "patterns",
|
||||
"propertyName": "patternsFilter",
|
||||
"type": "array",
|
||||
"alias": "p",
|
||||
"description": "Filter routes by the route pattern"
|
||||
},
|
||||
{
|
||||
"name": "names",
|
||||
"propertyName": "namesFilter",
|
||||
"type": "array",
|
||||
"alias": "n",
|
||||
"description": "Filter routes by route name"
|
||||
},
|
||||
{
|
||||
"name": "json",
|
||||
"propertyName": "json",
|
||||
"type": "boolean",
|
||||
"description": "Output as JSON"
|
||||
},
|
||||
{
|
||||
"name": "table",
|
||||
"propertyName": "table",
|
||||
"type": "boolean",
|
||||
"description": "Output as Table"
|
||||
},
|
||||
{
|
||||
"name": "max-width",
|
||||
"propertyName": "maxWidth",
|
||||
"type": "number",
|
||||
"description": "Specify maximum rendering width. Ignored for JSON Output"
|
||||
}
|
||||
]
|
||||
},
|
||||
"generate:key": {
|
||||
"settings": {},
|
||||
"commandPath": "@adonisjs/core/build/commands/GenerateKey",
|
||||
"commandName": "generate:key",
|
||||
"description": "Generate a new APP_KEY secret",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": []
|
||||
},
|
||||
"repl": {
|
||||
"settings": {
|
||||
"loadApp": true,
|
||||
"environment": "repl",
|
||||
"stayAlive": true
|
||||
},
|
||||
"commandPath": "@adonisjs/repl/build/commands/AdonisRepl",
|
||||
"commandName": "repl",
|
||||
"description": "Start a new REPL session",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": []
|
||||
},
|
||||
"ssr:build": {
|
||||
"settings": {
|
||||
"stayAlive": true
|
||||
},
|
||||
"commandPath": "@eidellev/inertia-adonisjs/build/commands/Build",
|
||||
"commandName": "ssr:build",
|
||||
"description": "Build and watch files for changes",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": []
|
||||
},
|
||||
"ssr:watch": {
|
||||
"settings": {
|
||||
"stayAlive": true
|
||||
},
|
||||
"commandPath": "@eidellev/inertia-adonisjs/build/commands/Watch",
|
||||
"commandName": "ssr:watch",
|
||||
"description": "Build and watch files for changes",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": []
|
||||
},
|
||||
"db:seed": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/DbSeed",
|
||||
"commandName": "db:seed",
|
||||
"description": "Execute database seeders",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "Define a custom database connection for the seeders",
|
||||
"alias": "c"
|
||||
},
|
||||
{
|
||||
"name": "interactive",
|
||||
"propertyName": "interactive",
|
||||
"type": "boolean",
|
||||
"description": "Run seeders in interactive mode",
|
||||
"alias": "i"
|
||||
},
|
||||
{
|
||||
"name": "files",
|
||||
"propertyName": "files",
|
||||
"type": "array",
|
||||
"description": "Define a custom set of seeders files names to run",
|
||||
"alias": "f"
|
||||
},
|
||||
{
|
||||
"name": "compact-output",
|
||||
"propertyName": "compactOutput",
|
||||
"type": "boolean",
|
||||
"description": "A compact single-line output"
|
||||
}
|
||||
]
|
||||
},
|
||||
"db:wipe": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/DbWipe",
|
||||
"commandName": "db:wipe",
|
||||
"description": "Drop all tables, views and types in database",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "Define a custom database connection",
|
||||
"alias": "c"
|
||||
},
|
||||
{
|
||||
"name": "drop-views",
|
||||
"propertyName": "dropViews",
|
||||
"type": "boolean",
|
||||
"description": "Drop all views"
|
||||
},
|
||||
{
|
||||
"name": "drop-types",
|
||||
"propertyName": "dropTypes",
|
||||
"type": "boolean",
|
||||
"description": "Drop all custom types (Postgres only)"
|
||||
},
|
||||
{
|
||||
"name": "force",
|
||||
"propertyName": "force",
|
||||
"type": "boolean",
|
||||
"description": "Explicitly force command to run in production"
|
||||
}
|
||||
]
|
||||
},
|
||||
"db:truncate": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/DbTruncate",
|
||||
"commandName": "db:truncate",
|
||||
"description": "Truncate all tables in database",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "Define a custom database connection",
|
||||
"alias": "c"
|
||||
},
|
||||
{
|
||||
"name": "force",
|
||||
"propertyName": "force",
|
||||
"type": "boolean",
|
||||
"description": "Explicitly force command to run in production"
|
||||
}
|
||||
]
|
||||
},
|
||||
"make:model": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/MakeModel",
|
||||
"commandName": "make:model",
|
||||
"description": "Make a new Lucid model",
|
||||
"args": [
|
||||
{
|
||||
"type": "string",
|
||||
"propertyName": "name",
|
||||
"name": "name",
|
||||
"required": true,
|
||||
"description": "Name of the model class"
|
||||
}
|
||||
],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "migration",
|
||||
"propertyName": "migration",
|
||||
"type": "boolean",
|
||||
"alias": "m",
|
||||
"description": "Generate the migration for the model"
|
||||
},
|
||||
{
|
||||
"name": "controller",
|
||||
"propertyName": "controller",
|
||||
"type": "boolean",
|
||||
"alias": "c",
|
||||
"description": "Generate the controller for the model"
|
||||
},
|
||||
{
|
||||
"name": "factory",
|
||||
"propertyName": "factory",
|
||||
"type": "boolean",
|
||||
"alias": "f",
|
||||
"description": "Generate a factory for the model"
|
||||
}
|
||||
]
|
||||
},
|
||||
"make:migration": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/MakeMigration",
|
||||
"commandName": "make:migration",
|
||||
"description": "Make a new migration file",
|
||||
"args": [
|
||||
{
|
||||
"type": "string",
|
||||
"propertyName": "name",
|
||||
"name": "name",
|
||||
"required": true,
|
||||
"description": "Name of the migration file"
|
||||
}
|
||||
],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "The connection flag is used to lookup the directory for the migration file"
|
||||
},
|
||||
{
|
||||
"name": "folder",
|
||||
"propertyName": "folder",
|
||||
"type": "string",
|
||||
"description": "Pre-select a migration directory"
|
||||
},
|
||||
{
|
||||
"name": "create",
|
||||
"propertyName": "create",
|
||||
"type": "string",
|
||||
"description": "Define the table name for creating a new table"
|
||||
},
|
||||
{
|
||||
"name": "table",
|
||||
"propertyName": "table",
|
||||
"type": "string",
|
||||
"description": "Define the table name for altering an existing table"
|
||||
}
|
||||
]
|
||||
},
|
||||
"make:seeder": {
|
||||
"settings": {},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/MakeSeeder",
|
||||
"commandName": "make:seeder",
|
||||
"description": "Make a new Seeder file",
|
||||
"args": [
|
||||
{
|
||||
"type": "string",
|
||||
"propertyName": "name",
|
||||
"name": "name",
|
||||
"required": true,
|
||||
"description": "Name of the seeder class"
|
||||
}
|
||||
],
|
||||
"aliases": [],
|
||||
"flags": []
|
||||
},
|
||||
"make:factory": {
|
||||
"settings": {},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/MakeFactory",
|
||||
"commandName": "make:factory",
|
||||
"description": "Make a new factory",
|
||||
"args": [
|
||||
{
|
||||
"type": "string",
|
||||
"propertyName": "model",
|
||||
"name": "model",
|
||||
"required": true,
|
||||
"description": "The name of the model"
|
||||
}
|
||||
],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "model-path",
|
||||
"propertyName": "modelPath",
|
||||
"type": "string",
|
||||
"description": "The path to the model"
|
||||
},
|
||||
{
|
||||
"name": "exact",
|
||||
"propertyName": "exact",
|
||||
"type": "boolean",
|
||||
"description": "Create the factory with the exact name as provided",
|
||||
"alias": "e"
|
||||
}
|
||||
]
|
||||
},
|
||||
"migration:run": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/Migration/Run",
|
||||
"commandName": "migration:run",
|
||||
"description": "Migrate database by running pending migrations",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "Define a custom database connection",
|
||||
"alias": "c"
|
||||
},
|
||||
{
|
||||
"name": "force",
|
||||
"propertyName": "force",
|
||||
"type": "boolean",
|
||||
"description": "Explicitly force to run migrations in production"
|
||||
},
|
||||
{
|
||||
"name": "dry-run",
|
||||
"propertyName": "dryRun",
|
||||
"type": "boolean",
|
||||
"description": "Do not run actual queries. Instead view the SQL output"
|
||||
},
|
||||
{
|
||||
"name": "compact-output",
|
||||
"propertyName": "compactOutput",
|
||||
"type": "boolean",
|
||||
"description": "A compact single-line output"
|
||||
},
|
||||
{
|
||||
"name": "disable-locks",
|
||||
"propertyName": "disableLocks",
|
||||
"type": "boolean",
|
||||
"description": "Disable locks acquired to run migrations safely"
|
||||
}
|
||||
]
|
||||
},
|
||||
"migration:rollback": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/Migration/Rollback",
|
||||
"commandName": "migration:rollback",
|
||||
"description": "Rollback migrations to a specific batch number",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "Define a custom database connection",
|
||||
"alias": "c"
|
||||
},
|
||||
{
|
||||
"name": "force",
|
||||
"propertyName": "force",
|
||||
"type": "boolean",
|
||||
"description": "Explictly force to run migrations in production"
|
||||
},
|
||||
{
|
||||
"name": "dry-run",
|
||||
"propertyName": "dryRun",
|
||||
"type": "boolean",
|
||||
"description": "Do not run actual queries. Instead view the SQL output"
|
||||
},
|
||||
{
|
||||
"name": "batch",
|
||||
"propertyName": "batch",
|
||||
"type": "number",
|
||||
"description": "Define custom batch number for rollback. Use 0 to rollback to initial state"
|
||||
},
|
||||
{
|
||||
"name": "compact-output",
|
||||
"propertyName": "compactOutput",
|
||||
"type": "boolean",
|
||||
"description": "A compact single-line output"
|
||||
},
|
||||
{
|
||||
"name": "disable-locks",
|
||||
"propertyName": "disableLocks",
|
||||
"type": "boolean",
|
||||
"description": "Disable locks acquired to run migrations safely"
|
||||
}
|
||||
]
|
||||
},
|
||||
"migration:status": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/Migration/Status",
|
||||
"commandName": "migration:status",
|
||||
"description": "View migrations status",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "Define a custom database connection",
|
||||
"alias": "c"
|
||||
}
|
||||
]
|
||||
},
|
||||
"migration:reset": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/Migration/Reset",
|
||||
"commandName": "migration:reset",
|
||||
"description": "Rollback all migrations",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "Define a custom database connection",
|
||||
"alias": "c"
|
||||
},
|
||||
{
|
||||
"name": "force",
|
||||
"propertyName": "force",
|
||||
"type": "boolean",
|
||||
"description": "Explicitly force command to run in production"
|
||||
},
|
||||
{
|
||||
"name": "dry-run",
|
||||
"propertyName": "dryRun",
|
||||
"type": "boolean",
|
||||
"description": "Do not run actual queries. Instead view the SQL output"
|
||||
},
|
||||
{
|
||||
"name": "disable-locks",
|
||||
"propertyName": "disableLocks",
|
||||
"type": "boolean",
|
||||
"description": "Disable locks acquired to run migrations safely"
|
||||
}
|
||||
]
|
||||
},
|
||||
"migration:refresh": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/Migration/Refresh",
|
||||
"commandName": "migration:refresh",
|
||||
"description": "Rollback and migrate database",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "Define a custom database connection",
|
||||
"alias": "c"
|
||||
},
|
||||
{
|
||||
"name": "force",
|
||||
"propertyName": "force",
|
||||
"type": "boolean",
|
||||
"description": "Explicitly force command to run in production"
|
||||
},
|
||||
{
|
||||
"name": "dry-run",
|
||||
"propertyName": "dryRun",
|
||||
"type": "boolean",
|
||||
"description": "Do not run actual queries. Instead view the SQL output"
|
||||
},
|
||||
{
|
||||
"name": "seed",
|
||||
"propertyName": "seed",
|
||||
"type": "boolean",
|
||||
"description": "Run seeders"
|
||||
},
|
||||
{
|
||||
"name": "disable-locks",
|
||||
"propertyName": "disableLocks",
|
||||
"type": "boolean",
|
||||
"description": "Disable locks acquired to run migrations safely"
|
||||
}
|
||||
]
|
||||
},
|
||||
"migration:fresh": {
|
||||
"settings": {
|
||||
"loadApp": true
|
||||
},
|
||||
"commandPath": "@adonisjs/lucid/build/commands/Migration/Fresh",
|
||||
"commandName": "migration:fresh",
|
||||
"description": "Drop all tables and re-migrate the database",
|
||||
"args": [],
|
||||
"aliases": [],
|
||||
"flags": [
|
||||
{
|
||||
"name": "connection",
|
||||
"propertyName": "connection",
|
||||
"type": "string",
|
||||
"description": "Define a custom database connection",
|
||||
"alias": "c"
|
||||
},
|
||||
{
|
||||
"name": "force",
|
||||
"propertyName": "force",
|
||||
"type": "boolean",
|
||||
"description": "Explicitly force command to run in production"
|
||||
},
|
||||
{
|
||||
"name": "seed",
|
||||
"propertyName": "seed",
|
||||
"type": "boolean",
|
||||
"description": "Run seeders"
|
||||
},
|
||||
{
|
||||
"name": "drop-views",
|
||||
"propertyName": "dropViews",
|
||||
"type": "boolean",
|
||||
"description": "Drop all views"
|
||||
},
|
||||
{
|
||||
"name": "drop-types",
|
||||
"propertyName": "dropTypes",
|
||||
"type": "boolean",
|
||||
"description": "Drop all custom types (Postgres only)"
|
||||
},
|
||||
{
|
||||
"name": "disable-locks",
|
||||
"propertyName": "disableLocks",
|
||||
"type": "boolean",
|
||||
"description": "Disable locks acquired to run migrations safely"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
"aliases": {}
|
||||
}
|
24
ace.js
Normal file
24
ace.js
Normal file
|
@ -0,0 +1,24 @@
|
|||
/*
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| JavaScript entrypoint for running ace commands
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Since, we cannot run TypeScript source code using "node" binary, we need
|
||||
| a JavaScript entrypoint to run ace commands.
|
||||
|
|
||||
| This file registers the "ts-node/esm" hook with the Node.js module system
|
||||
| and then imports the "bin/console.ts" file.
|
||||
|
|
||||
*/
|
||||
|
||||
/**
|
||||
* Register hook to process TypeScript files using ts-node
|
||||
*/
|
||||
import { register } from 'node:module'
|
||||
register('ts-node/esm', import.meta.url)
|
||||
|
||||
/**
|
||||
* Import ace console entrypoint
|
||||
*/
|
||||
await import('./bin/console.js')
|
100
adonisrc.ts
Normal file
100
adonisrc.ts
Normal file
|
@ -0,0 +1,100 @@
|
|||
import { defineConfig } from '@adonisjs/core/app'
|
||||
|
||||
export default defineConfig({
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Commands
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| List of ace commands to register from packages. The application commands
|
||||
| will be scanned automatically from the "./commands" directory.
|
||||
|
||||
*/
|
||||
commands: [
|
||||
() => import('@adonisjs/core/commands'),
|
||||
() => import('@adonisjs/lucid/commands')
|
||||
],
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Preloads
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| List of modules to import before starting the application.
|
||||
|
|
||||
*/
|
||||
preloads: [
|
||||
() => import('./start/routes.js'),
|
||||
() => import('./start/kernel.js'),
|
||||
// {
|
||||
// file: () => import('./start/inertia.js'),
|
||||
// environment: ["web"],
|
||||
// },
|
||||
// () => import('#start/events'),
|
||||
// {
|
||||
// file: () => import('./start/validator.js'),
|
||||
// environment: ["web"],
|
||||
// }
|
||||
],
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Service providers
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| List of service providers to import and register when booting the
|
||||
| application
|
||||
|
|
||||
*/
|
||||
providers: [
|
||||
// () => import('./providers/AppProvider.js'),
|
||||
() => import('@adonisjs/core/providers/app_provider'),
|
||||
() => import('@adonisjs/core/providers/hash_provider'),
|
||||
{
|
||||
file: () => import('@adonisjs/core/providers/repl_provider'),
|
||||
environment: ['repl', 'test'],
|
||||
},
|
||||
() => import('@adonisjs/session/session_provider'),
|
||||
() => import('@adonisjs/core/providers/edge_provider'),
|
||||
() => import('@adonisjs/shield/shield_provider'),
|
||||
// () => import('@eidellev/inertia-adonisjs'),
|
||||
// () => import('@adonisjs/inertia/inertia_provider'),
|
||||
() => import('#providers/inertia_provider'),
|
||||
() => import('@adonisjs/lucid/database_provider'),
|
||||
() => import('@adonisjs/auth/auth_provider'),
|
||||
// () => import('@eidellev/adonis-stardust'),
|
||||
() => import('@adonisjs/redis/redis_provider'),
|
||||
() => import('@adonisjs/encore/encore_provider'),
|
||||
() => import('@adonisjs/static/static_provider'),
|
||||
() => import('#providers/stardust_provider'),
|
||||
() => import('#providers/query_builder_provider'),
|
||||
() => import('#providers/TokenWorkerProvider'),
|
||||
() => import('#providers/validator_provider'),
|
||||
],
|
||||
metaFiles: [
|
||||
{
|
||||
pattern: 'public/**',
|
||||
reloadServer: false,
|
||||
},
|
||||
{
|
||||
pattern: 'resources/views/**/*.edge',
|
||||
reloadServer: false,
|
||||
},
|
||||
],
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Tests
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| List of test suites to organize tests by their type. Feel free to remove
|
||||
| and add additional suites.
|
||||
|
|
||||
*/
|
||||
tests: {
|
||||
suites: [
|
||||
{
|
||||
name: 'functional',
|
||||
files: ['tests/functional/**/*.spec(.ts|.js)'],
|
||||
timeout: 60000,
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
|
@ -1,17 +1,17 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
|
||||
export default class HomeController {
|
||||
public async index({}: HttpContextContract) {}
|
||||
public async index({}: HttpContext) {}
|
||||
|
||||
public async create({}: HttpContextContract) {}
|
||||
public async create({}: HttpContext) {}
|
||||
|
||||
public async store({}: HttpContextContract) {}
|
||||
public async store({}: HttpContext) {}
|
||||
|
||||
public async show({}: HttpContextContract) {}
|
||||
public async show({}: HttpContext) {}
|
||||
|
||||
public async edit({}: HttpContextContract) {}
|
||||
public async edit({}: HttpContext) {}
|
||||
|
||||
public async update({}: HttpContextContract) {}
|
||||
public async update({}: HttpContext) {}
|
||||
|
||||
public async destroy({}: HttpContextContract) {}
|
||||
public async destroy({}: HttpContext) {}
|
||||
}
|
||||
|
|
|
@ -1,14 +1,14 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import Role from 'App/Models/Role';
|
||||
import Permission from 'App/Models/Permission';
|
||||
import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm';
|
||||
import CreateRoleValidator from 'App/Validators/CreateRoleValidator';
|
||||
import UpdateRoleValidator from 'App/Validators/UpdateRoleValidator';
|
||||
import { RenderResponse } from '@ioc:EidelLev/Inertia';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import Role from '#app/Models/Role';
|
||||
import Permission from '#app/Models/Permission';
|
||||
import CreateRoleValidator from '#app/Validators/CreateRoleValidator';
|
||||
import UpdateRoleValidator from '#app/Validators/UpdateRoleValidator';
|
||||
import type { ModelQueryBuilderContract } from "@adonisjs/lucid/types/model";
|
||||
|
||||
// import { schema, rules } from '@ioc:Adonis/Core/Validator';
|
||||
|
||||
export default class RoleController {
|
||||
public async index({ auth, request, inertia }: HttpContextContract) {
|
||||
public async index({ auth, request, inertia }: HttpContext) {
|
||||
let roles: ModelQueryBuilderContract<typeof Role, Role> = Role.query();
|
||||
|
||||
if (request.input('search')) {
|
||||
|
@ -48,14 +48,14 @@ export default class RoleController {
|
|||
});
|
||||
}
|
||||
|
||||
public async create({ inertia }: HttpContextContract) {
|
||||
public async create({ inertia }: HttpContext) {
|
||||
const permissions = await Permission.query().select('id', 'name').pluck('name', 'id');
|
||||
return inertia.render('Admin/Role/Create', {
|
||||
permissions: permissions,
|
||||
});
|
||||
}
|
||||
|
||||
public async store({ request, response, session }: HttpContextContract) {
|
||||
public async store({ request, response, session }: HttpContext) {
|
||||
// node ace make:validator CreateUser
|
||||
try {
|
||||
// Step 2 - Validate request body against the schema
|
||||
|
@ -79,7 +79,7 @@ export default class RoleController {
|
|||
return response.redirect().toRoute('role.index');
|
||||
}
|
||||
|
||||
public async show({ request, inertia }: HttpContextContract): RenderResponse {
|
||||
public async show({ request, inertia }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
const role = await Role.query().where('id', id).firstOrFail();
|
||||
|
||||
|
@ -94,7 +94,7 @@ export default class RoleController {
|
|||
});
|
||||
}
|
||||
|
||||
public async edit({ request, inertia }: HttpContextContract) {
|
||||
public async edit({ request, inertia }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
const role = await Role.query().where('id', id).firstOrFail();
|
||||
|
||||
|
@ -109,7 +109,7 @@ export default class RoleController {
|
|||
});
|
||||
}
|
||||
|
||||
public async update({ request, response, session }: HttpContextContract) {
|
||||
public async update({ request, response, session }: HttpContext) {
|
||||
// node ace make:validator UpdateUser
|
||||
const id = request.param('id');
|
||||
const role = await Role.query().where('id', id).firstOrFail();
|
||||
|
@ -132,7 +132,7 @@ export default class RoleController {
|
|||
return response.redirect().toRoute('settings.role.index');
|
||||
}
|
||||
|
||||
public async destroy({ request, response, session }: HttpContextContract) {
|
||||
public async destroy({ request, response, session }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
const role = await Role.findOrFail(id);
|
||||
await role.delete();
|
||||
|
|
|
@ -1,16 +1,15 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import User from 'App/Models/User';
|
||||
import Role from 'App/Models/Role';
|
||||
import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm';
|
||||
import CreateUserValidator from 'App/Validators/CreateUserValidator';
|
||||
import UpdateUserValidator from 'App/Validators/UpdateUserValidator';
|
||||
// import { RenderResponse } from '@ioc:EidelLev/Inertia';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import User from '#app/Models/User';
|
||||
import Role from '#app/Models/Role';
|
||||
import { ModelQueryBuilderContract } from "@adonisjs/lucid/types/model";
|
||||
import CreateUserValidator from '#app/Validators/CreateUserValidator';
|
||||
import UpdateUserValidator from '#app/Validators/UpdateUserValidator';
|
||||
// import { schema, rules } from '@ioc:Adonis/Core/Validator';
|
||||
// import Hash from '@ioc:Adonis/Core/Hash';
|
||||
// import { schema, rules } from '@ioc:Adonis/Core/Validator';
|
||||
|
||||
export default class UsersController {
|
||||
public async index({ auth, request, inertia }: HttpContextContract) {
|
||||
export default class AdminUserController {
|
||||
public async index({ auth, request, inertia }: HttpContext) {
|
||||
const page = request.input('page', 1);
|
||||
// const limit = 10
|
||||
|
||||
|
@ -63,7 +62,7 @@ export default class UsersController {
|
|||
});
|
||||
}
|
||||
|
||||
public async create({ inertia }: HttpContextContract) {
|
||||
public async create({ inertia }: HttpContext) {
|
||||
// let rolesPluck = {};
|
||||
// (await Role.query().select('id', 'name')).forEach((user) => {
|
||||
// rolesPluck[user.id] = user.name;
|
||||
|
@ -75,7 +74,7 @@ export default class UsersController {
|
|||
});
|
||||
}
|
||||
|
||||
public async store({ request, response, session }: HttpContextContract) {
|
||||
public async store({ request, response, session }: HttpContext) {
|
||||
// node ace make:validator CreateUser
|
||||
try {
|
||||
// Step 2 - Validate request body against the schema
|
||||
|
@ -97,7 +96,7 @@ export default class UsersController {
|
|||
return response.redirect().toRoute('user.index');
|
||||
}
|
||||
|
||||
public async show({ request, inertia }: HttpContextContract) {
|
||||
public async show({ request, inertia }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
|
||||
|
@ -112,7 +111,7 @@ export default class UsersController {
|
|||
});
|
||||
}
|
||||
|
||||
public async edit({ request, inertia }: HttpContextContract) {
|
||||
public async edit({ request, inertia }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
|
||||
|
@ -127,7 +126,7 @@ export default class UsersController {
|
|||
});
|
||||
}
|
||||
|
||||
public async update({ request, response, session }: HttpContextContract) {
|
||||
public async update({ request, response, session }: HttpContext) {
|
||||
// node ace make:validator UpdateUser
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
|
@ -154,7 +153,7 @@ export default class UsersController {
|
|||
return response.redirect().toRoute('settings.user.index');
|
||||
}
|
||||
|
||||
public async destroy({ request, response, session }: HttpContextContract) {
|
||||
public async destroy({ request, response, session }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
const user = await User.findOrFail(id);
|
||||
await user.delete();
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import Person from 'App/Models/Person';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import Person from '#app/Models/Person';
|
||||
// import Dataset from 'App/Models/Dataset';
|
||||
|
||||
// node ace make:controller Author
|
||||
export default class AuthorsController {
|
||||
public async index({}: HttpContextContract) {
|
||||
public async index({}: HttpContext) {
|
||||
// select * from gba.persons
|
||||
// where exists (select * from gba.documents inner join gba.link_documents_persons on "documents"."id" = "link_documents_persons"."document_id"
|
||||
// where ("link_documents_persons"."role" = 'author') and ("persons"."id" = "link_documents_persons"."person_id"));
|
||||
|
@ -19,7 +19,7 @@ export default class AuthorsController {
|
|||
return authors;
|
||||
}
|
||||
|
||||
public async persons({ request }: HttpContextContract) {
|
||||
public async persons({ request }: HttpContext) {
|
||||
const authors = Person.query().where('status', true);
|
||||
|
||||
if (request.input('filter')) {
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
// import * as fs from 'fs';
|
||||
// import * as path from 'path';
|
||||
|
@ -7,7 +7,7 @@ const prefixes = ['von', 'van'];
|
|||
|
||||
// node ace make:controller Author
|
||||
export default class AvatarController {
|
||||
public async generateAvatar({ request, response }: HttpContextContract) {
|
||||
public async generateAvatar({ request, response }: HttpContext) {
|
||||
try {
|
||||
const { name, background, textColor, size } = request.only(['name', 'background', 'textColor', 'size']);
|
||||
|
||||
|
@ -40,7 +40,7 @@ export default class AvatarController {
|
|||
}
|
||||
}
|
||||
|
||||
private getInitials(name) {
|
||||
private getInitials(name: string) {
|
||||
const parts = name.split(' ');
|
||||
let initials = '';
|
||||
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
// import Person from 'App/Models/Person';
|
||||
import Dataset from 'App/Models/Dataset';
|
||||
import Dataset from '#app/Models/Dataset';
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
|
||||
// node ace make:controller Author
|
||||
export default class DatasetController {
|
||||
public async index({}: HttpContextContract) {
|
||||
public async index({}: HttpContext) {
|
||||
// select * from gba.persons
|
||||
// where exists (select * from gba.documents inner join gba.link_documents_persons on "documents"."id" = "link_documents_persons"."document_id"
|
||||
// where ("link_documents_persons"."role" = 'author') and ("persons"."id" = "link_documents_persons"."person_id"));
|
||||
|
@ -14,7 +14,7 @@ export default class DatasetController {
|
|||
return datasets;
|
||||
}
|
||||
|
||||
public async findAll({ response }: HttpContextContract) {
|
||||
public async findAll({ response }: HttpContext) {
|
||||
try {
|
||||
const datasets = await Dataset.query()
|
||||
.where('server_state', 'published')
|
||||
|
@ -29,7 +29,7 @@ export default class DatasetController {
|
|||
}
|
||||
}
|
||||
|
||||
public async findOne({ params }: HttpContextContract) {
|
||||
public async findOne({ params }: HttpContext) {
|
||||
const datasets = await Dataset.query()
|
||||
.where('publish_id', params.publish_id)
|
||||
.preload('titles')
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import File from 'App/Models/File';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import File from '#app/Models/File';
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
@ -7,7 +7,7 @@ import * as path from 'path';
|
|||
// node ace make:controller Author
|
||||
export default class FileController {
|
||||
// @Get("download/:id")
|
||||
public async findOne({ response, params }: HttpContextContract) {
|
||||
public async findOne({ response, params }: HttpContext) {
|
||||
const id = params.id;
|
||||
const file = await File.findOrFail(id);
|
||||
// const file = await File.findOne({
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import Database from '@ioc:Adonis/Lucid/Database';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import db from '@adonisjs/lucid/services/db';
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
|
||||
export default class HomeController {
|
||||
public async findDocumentsPerYear({ response, params }: HttpContextContract) {
|
||||
public async findDocumentsPerYear({ response, params }: HttpContext) {
|
||||
const year = params.year;
|
||||
const from = parseInt(year);
|
||||
const serverState = 'published';
|
||||
|
@ -17,8 +17,8 @@ export default class HomeController {
|
|||
// .preload('authors')
|
||||
// .orderBy('server_date_published');
|
||||
|
||||
const datasets = await Database.from('documents as doc')
|
||||
.select(['publish_id', 'server_date_published', Database.raw(`date_part('year', server_date_published) as pub_year`)])
|
||||
const datasets = await db.from('documents as doc')
|
||||
.select(['publish_id', 'server_date_published', db.raw(`date_part('year', server_date_published) as pub_year`)])
|
||||
.where('server_state', serverState)
|
||||
.innerJoin('link_documents_persons as ba', 'doc.id', 'ba.document_id')
|
||||
.andWhereRaw(`date_part('year', server_date_published) = ?`, [from])
|
||||
|
@ -32,17 +32,17 @@ export default class HomeController {
|
|||
}
|
||||
}
|
||||
|
||||
public async findYears({ response }: HttpContextContract) {
|
||||
public async findYears({ response }: HttpContext) {
|
||||
const serverState = 'published';
|
||||
// Use raw SQL queries to select all cars which belongs to the user
|
||||
try {
|
||||
const datasets = await Database.rawQuery(
|
||||
const datasets = await db.rawQuery(
|
||||
'SELECT distinct EXTRACT(YEAR FROM server_date_published) as published_date FROM gba.documents WHERE server_state = ?',
|
||||
[serverState],
|
||||
);
|
||||
|
||||
// Pluck the ids of the cars
|
||||
const years = datasets.rows.map((dataset) => dataset.published_date);
|
||||
const years = datasets.rows.map((dataset: any) => dataset.published_date);
|
||||
// check if the cars is returned
|
||||
// if (years.length > 0) {
|
||||
return response.status(StatusCodes.OK).json(years);
|
||||
|
@ -54,7 +54,7 @@ export default class HomeController {
|
|||
}
|
||||
}
|
||||
|
||||
public async findPublicationsPerMonth({ response }: HttpContextContract) {
|
||||
public async findPublicationsPerMonth({ response }: HttpContext) {
|
||||
const serverState = 'published';
|
||||
// const year = params.year;
|
||||
// const from = parseInt(year);
|
||||
|
@ -70,11 +70,11 @@ export default class HomeController {
|
|||
|
||||
const years = [2021, 2022, 2023]; // Add the second year
|
||||
|
||||
const result = await Database.from('documents as doc')
|
||||
const result = await db.from('documents as doc')
|
||||
.select([
|
||||
Database.raw(`date_part('year', server_date_published) as pub_year`),
|
||||
Database.raw(`date_part('month', server_date_published) as pub_month`),
|
||||
Database.raw('COUNT(*) as count'),
|
||||
db.raw(`date_part('year', server_date_published) as pub_year`),
|
||||
db.raw(`date_part('month', server_date_published) as pub_month`),
|
||||
db.raw('COUNT(*) as count'),
|
||||
])
|
||||
.where('server_state', serverState)
|
||||
// .innerJoin('link_documents_persons as ba', 'doc.id', 'ba.document_id')
|
||||
|
|
|
@ -1,15 +1,15 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
// import TotpSecret from 'App/Models/TotpSecret';
|
||||
import User from 'App/Models/User';
|
||||
import TwoFactorAuthProvider from 'App/Services/TwoFactorAuthProvider';
|
||||
import User from '#app/Models/User';
|
||||
import TwoFactorAuthProvider from '#app/Services/TwoFactorAuthProvider';
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
import { InvalidArgumentException } from 'node-exceptions';
|
||||
import { TotpState } from 'Contracts/enums';
|
||||
import { TotpState } from '#contracts/enums';
|
||||
|
||||
|
||||
// Here we are generating secret and recovery codes for the user that’s enabling 2FA and storing them to our database.
|
||||
export default class UserController {
|
||||
public async enable({ auth, response, request }: HttpContextContract) {
|
||||
public async enable({ auth, response, request }: HttpContext) {
|
||||
const user = (await User.find(auth.user?.id)) as User;
|
||||
// await user.load('totp_secret');
|
||||
// if (!user.totp_secret) {
|
||||
|
|
|
@ -1,16 +1,20 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import User from 'App/Models/User';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import User from '#models/User';
|
||||
// import Hash from '@ioc:Adonis/Core/Hash';
|
||||
// import InvalidCredentialException from 'App/Exceptions/InvalidCredentialException';
|
||||
import AuthValidator from 'App/Validators/AuthValidator';
|
||||
import AuthValidator from '#app/Validators/AuthValidator';
|
||||
|
||||
import TwoFactorAuthProvider from 'App/Services/TwoFactorAuthProvider';
|
||||
import TwoFactorAuthProvider from '#app/Services/TwoFactorAuthProvider';
|
||||
// import { Authenticator } from '@adonisjs/auth';
|
||||
// import { LoginState } from 'Contracts/enums';
|
||||
// import { StatusCodes } from 'http-status-codes';
|
||||
|
||||
// interface MyHttpsContext extends HttpContext {
|
||||
// auth: Authenticator<User>
|
||||
// }
|
||||
export default class AuthController {
|
||||
// login function
|
||||
public async login({ request, response, auth, session }: HttpContextContract) {
|
||||
// login function{ request, auth, response }:HttpContext
|
||||
public async login({ request, response, auth, session }: HttpContext) {
|
||||
// console.log({
|
||||
// registerBody: request.body(),
|
||||
// });
|
||||
|
@ -25,7 +29,9 @@ export default class AuthController {
|
|||
// // attempt to verify credential and login user
|
||||
// await auth.use('web').attempt(email, plainPassword);
|
||||
|
||||
const user = await auth.use('web').verifyCredentials(email, password);
|
||||
// const user = await auth.use('web').verifyCredentials(email, password);
|
||||
const user = await User.verifyCredentials(email, password)
|
||||
|
||||
if (user.isTwoFactorEnabled) {
|
||||
// session.put("login.id", user.id);
|
||||
// return view.render("pages/two-factor-challenge");
|
||||
|
@ -39,7 +45,8 @@ export default class AuthController {
|
|||
// new_user_id: user.id,
|
||||
// });
|
||||
}
|
||||
await auth.login(user);
|
||||
|
||||
await auth.use('web').login(user);
|
||||
} catch (error) {
|
||||
// if login fails, return vague form message and redirect back
|
||||
session.flash('message', 'Your username, email, or password is incorrect');
|
||||
|
@ -50,7 +57,7 @@ export default class AuthController {
|
|||
response.redirect('/apps/dashboard');
|
||||
}
|
||||
|
||||
public async twoFactorChallenge({ request, session, auth, response }) {
|
||||
public async twoFactorChallenge({ request, session, auth, response }: HttpContext) {
|
||||
const { code, recoveryCode, login_id } = request.only(['code', 'recoveryCode', 'login_id']);
|
||||
// const user = await User.query().where('id', session.get('login.id')).firstOrFail();
|
||||
const user = await User.query().where('id', login_id).firstOrFail();
|
||||
|
@ -59,7 +66,7 @@ export default class AuthController {
|
|||
const isValid = await TwoFactorAuthProvider.validate(user, code);
|
||||
if (isValid) {
|
||||
// login user and redirect to dashboard
|
||||
await auth.login(user);
|
||||
await auth.use('web').login(user);
|
||||
response.redirect('/apps/dashboard');
|
||||
} else {
|
||||
session.flash('message', 'Your tow factor code is incorrect');
|
||||
|
@ -70,17 +77,17 @@ export default class AuthController {
|
|||
if (codes.includes(recoveryCode)) {
|
||||
user.twoFactorRecoveryCodes = codes.filter((c) => c !== recoveryCode);
|
||||
await user.save();
|
||||
await auth.login(user);
|
||||
await auth.use('web').login(user);
|
||||
response.redirect('/apps/dashboard');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// logout function
|
||||
public async logout({ auth, response }: HttpContextContract) {
|
||||
public async logout({ auth, response }: HttpContext) {
|
||||
// await auth.logout();
|
||||
await auth.use('web').logout();
|
||||
response.redirect('/app/login');
|
||||
return response.redirect('/app/login');
|
||||
// return response.status(200);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,9 +1,9 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import User from 'App/Models/User';
|
||||
import { RenderResponse } from '@ioc:EidelLev/Inertia';
|
||||
import TwoFactorAuthProvider from 'App/Services/TwoFactorAuthProvider';
|
||||
import Hash from '@ioc:Adonis/Core/Hash';
|
||||
import { schema, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import User from '#app/Models/User';
|
||||
// import { RenderResponse } from '@ioc:EidelLev/Inertia';
|
||||
import TwoFactorAuthProvider from '#app/Services/TwoFactorAuthProvider';
|
||||
import hash from '@adonisjs/core/services/hash';
|
||||
import { schema, rules } from '@adonisjs/validator';
|
||||
|
||||
// Here we are generating secret and recovery codes for the user that’s enabling 2FA and storing them to our database.
|
||||
export default class UserController {
|
||||
|
@ -12,7 +12,7 @@ export default class UserController {
|
|||
*
|
||||
* @return — \Inertia\Response
|
||||
*/
|
||||
public async accountInfo({ inertia, auth }: HttpContextContract): RenderResponse {
|
||||
public async accountInfo({ inertia, auth }: HttpContext) {
|
||||
// const user = auth.user;
|
||||
const user = (await User.find(auth.user?.id)) as User;
|
||||
// const id = request.param('id');
|
||||
|
@ -25,7 +25,7 @@ export default class UserController {
|
|||
});
|
||||
}
|
||||
|
||||
public async accountInfoStore({ auth, request, response, session }) {
|
||||
public async accountInfoStore({ auth, request, response, session }: HttpContext) {
|
||||
const passwordSchema = schema.create({
|
||||
old_password: schema.string({ trim: true }, [rules.required()]),
|
||||
new_password: schema.string({ trim: true }, [rules.minLength(8), rules.maxLength(255), rules.confirmed('confirm_password')]),
|
||||
|
@ -39,7 +39,7 @@ export default class UserController {
|
|||
}
|
||||
|
||||
try {
|
||||
const user = await auth.user;
|
||||
const user = await auth.user as User;
|
||||
const { old_password, new_password } = request.only(['old_password', 'new_password']);
|
||||
|
||||
// if (!(old_password && new_password && confirm_password)) {
|
||||
|
@ -47,9 +47,9 @@ export default class UserController {
|
|||
// }
|
||||
|
||||
// Verify if the provided old password matches the user's current password
|
||||
const isSame = await Hash.verify(user.password, old_password);
|
||||
const isSame = await hash.verify(user.password, old_password);
|
||||
if (!isSame) {
|
||||
return response.flash({ warning: 'Old password is incorrect.' }).redirect().back();
|
||||
return response.flash('warning', 'Old password is incorrect.').redirect().back();
|
||||
}
|
||||
|
||||
// Hash the new password before updating the user's password
|
||||
|
@ -57,7 +57,7 @@ export default class UserController {
|
|||
await user.save();
|
||||
|
||||
// return response.status(200).send({ message: 'Password updated successfully.' });
|
||||
session.flash('Password updated successfully.');
|
||||
session.flash({ message: 'Password updated successfully.' });
|
||||
return response.redirect().toRoute('settings.user.index');
|
||||
} catch (error) {
|
||||
// return response.status(500).send({ message: 'Internal server error.' });
|
||||
|
@ -65,7 +65,7 @@ export default class UserController {
|
|||
}
|
||||
}
|
||||
|
||||
public async enableTwoFactorAuthentication({ auth, response, session }: HttpContextContract): Promise<void> {
|
||||
public async enableTwoFactorAuthentication({ auth, response, session }: HttpContext): Promise<void> {
|
||||
// const user: User | undefined = auth?.user;
|
||||
const user = (await User.find(auth.user?.id)) as User;
|
||||
|
||||
|
@ -87,7 +87,7 @@ export default class UserController {
|
|||
// });
|
||||
}
|
||||
|
||||
public async disableTwoFactorAuthentication({ auth, response, session }): Promise<void> {
|
||||
public async disableTwoFactorAuthentication({ auth, response, session }: HttpContext): Promise<void> {
|
||||
const user = auth?.user;
|
||||
|
||||
user.twoFactorSecret = null;
|
||||
|
|
|
@ -1,22 +1,23 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import { Client } from '@opensearch-project/opensearch';
|
||||
import User from 'App/Models/User';
|
||||
import Dataset from 'App/Models/Dataset';
|
||||
import DatasetIdentifier from 'App/Models/DatasetIdentifier';
|
||||
import XmlModel from 'App/Library/XmlModel';
|
||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces';
|
||||
import User from '#app/Models/User';
|
||||
import Dataset from '#app/Models/Dataset';
|
||||
import DatasetIdentifier from '#app/Models/DatasetIdentifier';
|
||||
import XmlModel from '#app/Library/XmlModel';
|
||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
|
||||
import { create } from 'xmlbuilder2';
|
||||
import { readFileSync } from 'fs';
|
||||
import { transform } from 'saxon-js';
|
||||
import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm';
|
||||
import { schema, CustomMessages } from '@ioc:Adonis/Core/Validator';
|
||||
import SaxonJS from 'saxon-js';
|
||||
import { schema } from '@adonisjs/validator';
|
||||
import { DateTime } from 'luxon';
|
||||
import Index from 'App/Library/Utils/Index';
|
||||
import { getDomain } from 'App/Utils/utility-functions';
|
||||
import { DoiClient } from 'App/Library/Doi/DoiClient';
|
||||
import DoiClientException from 'App/Exceptions/DoiClientException';
|
||||
import Logger from '@ioc:Adonis/Core/Logger';
|
||||
import Index from '#app/Library/Utils/Index';
|
||||
import { getDomain } from '#app/Utils/utility-functions';
|
||||
import { DoiClient } from '#app/Library/Doi/DoiClient';
|
||||
import DoiClientException from '#app/Exceptions/DoiClientException';
|
||||
import logger from '@adonisjs/core/services/logger';
|
||||
import { HttpException } from 'node-exceptions';
|
||||
import { ModelQueryBuilderContract } from "@adonisjs/lucid/types/model";
|
||||
import { CustomMessages } from "@adonisjs/validator/types";
|
||||
|
||||
// Create a new instance of the client
|
||||
const client = new Client({ node: 'http://localhost:9200' }); // replace with your OpenSearch endpoint
|
||||
|
@ -37,7 +38,7 @@ export default class DatasetsController {
|
|||
}
|
||||
|
||||
// public async index({}: HttpContextContract) {}
|
||||
public async index({ auth, request, inertia }: HttpContextContract) {
|
||||
public async index({ auth, request, inertia }: HttpContext) {
|
||||
const user = (await User.find(auth.user?.id)) as User;
|
||||
const page = request.input('page', 1);
|
||||
let datasets: ModelQueryBuilderContract<typeof Dataset, Dataset> = Dataset.query();
|
||||
|
@ -92,7 +93,7 @@ export default class DatasetsController {
|
|||
});
|
||||
}
|
||||
|
||||
public async receive({ request, inertia, response }: HttpContextContract) {
|
||||
public async receive({ request, inertia, response }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
const dataset = await Dataset.query()
|
||||
.where('id', id)
|
||||
|
@ -121,7 +122,7 @@ export default class DatasetsController {
|
|||
});
|
||||
}
|
||||
|
||||
public async receiveUpdate({ auth, request, response }) {
|
||||
public async receiveUpdate({ auth, request, response }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
// const { id } = params;
|
||||
const dataset = await Dataset.findOrFail(id);
|
||||
|
@ -153,7 +154,7 @@ export default class DatasetsController {
|
|||
}
|
||||
}
|
||||
|
||||
public async approve({ request, inertia, response }) {
|
||||
public async approve({ request, inertia, response }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
// $dataset = Dataset::with('user:id,login')->findOrFail($id);
|
||||
const dataset = await Dataset.findOrFail(id);
|
||||
|
@ -182,7 +183,7 @@ export default class DatasetsController {
|
|||
});
|
||||
}
|
||||
|
||||
public async approveUpdate({ request, response }) {
|
||||
public async approveUpdate({ request, response }: HttpContext) {
|
||||
const approveDatasetSchema = schema.create({
|
||||
reviewer_id: schema.number(),
|
||||
});
|
||||
|
@ -221,7 +222,7 @@ export default class DatasetsController {
|
|||
}
|
||||
}
|
||||
|
||||
public async publish({ request, inertia, response }) {
|
||||
public async publish({ request, inertia, response }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
|
||||
const dataset = await Dataset.query()
|
||||
|
@ -250,7 +251,7 @@ export default class DatasetsController {
|
|||
});
|
||||
}
|
||||
|
||||
public async publishUpdate({ request, response }) {
|
||||
public async publishUpdate({ request, response }: HttpContext) {
|
||||
const publishDatasetSchema = schema.create({
|
||||
publisher_name: schema.string({ trim: true }),
|
||||
});
|
||||
|
@ -287,7 +288,7 @@ export default class DatasetsController {
|
|||
}
|
||||
}
|
||||
|
||||
public async doiCreate({ request, inertia }: HttpContextContract) {
|
||||
public async doiCreate({ request, inertia }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
const dataset = await Dataset.query()
|
||||
.where('id', id)
|
||||
|
@ -301,7 +302,7 @@ export default class DatasetsController {
|
|||
});
|
||||
}
|
||||
|
||||
public async doiStore({ request, response }: HttpContextContract) {
|
||||
public async doiStore({ request, response }: HttpContext) {
|
||||
const dataId = request.param('publish_id');
|
||||
const dataset = await Dataset.query()
|
||||
// .preload('xmlCache')
|
||||
|
@ -338,7 +339,7 @@ export default class DatasetsController {
|
|||
const index_name = 'tethys-records';
|
||||
await Index.indexDocument(dataset, index_name);
|
||||
} catch (error) {
|
||||
Logger.error(`${__filename}: Indexing document ${dataset.id} failed: ${error.message}`);
|
||||
logger.error(`${__filename}: Indexing document ${dataset.id} failed: ${error.message}`);
|
||||
// Log the error or handle it as needed
|
||||
throw new HttpException(error.message);
|
||||
}
|
||||
|
@ -351,12 +352,12 @@ export default class DatasetsController {
|
|||
// return response.toRoute('editor.dataset.list').flash('message', xmlMeta);
|
||||
}
|
||||
|
||||
public async show({}: HttpContextContract) {}
|
||||
public async show({}: HttpContext) {}
|
||||
|
||||
public async edit({}: HttpContextContract) {}
|
||||
public async edit({}: HttpContext) {}
|
||||
|
||||
// public async update({}: HttpContextContract) {}
|
||||
public async update({ response }) {
|
||||
public async update({ response }: HttpContext) {
|
||||
const id = 273; //request.param('id');
|
||||
const dataset = await Dataset.query().preload('xmlCache').where('id', id).firstOrFail();
|
||||
// add xml elements
|
||||
|
@ -374,7 +375,7 @@ export default class DatasetsController {
|
|||
const xmlString = xml.end({ prettyPrint: false });
|
||||
let doc = '';
|
||||
try {
|
||||
const result = await transform({
|
||||
const result = await SaxonJS.transform({
|
||||
// stylesheetFileName: `${config.TMP_BASE_DIR}/data-quality/rules/iati.sef.json`,
|
||||
stylesheetText: this.proc,
|
||||
destination: 'serialized',
|
||||
|
@ -472,7 +473,7 @@ export default class DatasetsController {
|
|||
}
|
||||
}
|
||||
|
||||
public async destroy({}: HttpContextContract) {}
|
||||
public async destroy({}: HttpContext) {}
|
||||
|
||||
private async createXmlRecord(dataset: Dataset, datasetNode: XMLBuilder) {
|
||||
const domNode = await this.getDatasetXmlDomNode(dataset);
|
||||
|
|
|
@ -1,27 +1,31 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import { RequestContract } from '@ioc:Adonis/Core/Request';
|
||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
// import { RequestContract } from '@ioc:Adonis/Core/Request';
|
||||
import { Request } from '@adonisjs/core/http';
|
||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
|
||||
import { create } from 'xmlbuilder2';
|
||||
import dayjs, { Dayjs } from 'dayjs';
|
||||
import utc from 'dayjs/plugin/utc';
|
||||
import timezone from 'dayjs/plugin/timezone';
|
||||
import utc from 'dayjs/plugin/utc.js';
|
||||
import timezone from 'dayjs/plugin/timezone.js';
|
||||
import { readFileSync } from 'fs';
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
import { transform } from 'saxon-js';
|
||||
import SaxonJS from 'saxon-js';
|
||||
// import { Xslt, xmlParse } from 'xslt-processor'
|
||||
import { OaiErrorCodes, OaiModelError } from 'App/Exceptions/OaiErrorCodes';
|
||||
import { OaiModelException, BadOaiModelException } from 'App/Exceptions/OaiModelException';
|
||||
import Dataset from 'App/Models/Dataset';
|
||||
import Collection from 'App/Models/Collection';
|
||||
import { getDomain, preg_match } from 'App/Utils/utility-functions';
|
||||
import XmlModel from 'App/Library/XmlModel';
|
||||
import Logger from '@ioc:Adonis/Core/Logger';
|
||||
import ResumptionToken from 'App/Library/Oai/ResumptionToken';
|
||||
import { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Config from '@ioc:Adonis/Core/Config';
|
||||
import { inject } from '@adonisjs/fold';
|
||||
import { OaiErrorCodes, OaiModelError } from '#app/Exceptions/OaiErrorCodes';
|
||||
import { OaiModelException, BadOaiModelException } from '#app/Exceptions/OaiModelException';
|
||||
import Dataset from '#app/Models/Dataset';
|
||||
import Collection from '#app/Models/Collection';
|
||||
import { getDomain, preg_match } from '#app/Utils/utility-functions';
|
||||
import XmlModel from '#app/Library/XmlModel';
|
||||
import logger from '@adonisjs/core/services/logger';
|
||||
import ResumptionToken from '#app/Library/Oai/ResumptionToken';
|
||||
// import Config from '@ioc:Adonis/Core/Config';
|
||||
import config from '@adonisjs/core/services/config'
|
||||
// import { inject } from '@adonisjs/fold';
|
||||
import { inject } from '@adonisjs/core'
|
||||
// import { TokenWorkerContract } from "MyApp/Models/TokenWorker";
|
||||
import TokenWorkerContract from 'App/Library/Oai/TokenWorker';
|
||||
import TokenWorkerContract from '#library/Oai/TokenWorkerContract';
|
||||
import { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model';
|
||||
|
||||
|
||||
interface XslTParameter {
|
||||
[key: string]: any;
|
||||
|
@ -39,7 +43,7 @@ interface ListParameter {
|
|||
metadataPrefix: string;
|
||||
}
|
||||
|
||||
@inject(['App/Library/Oai/TokenWorkerContract'])
|
||||
@inject()
|
||||
export default class OaiController {
|
||||
private deliveringDocumentStates = ['published', 'deleted'];
|
||||
private sampleRegEx = /^[A-Za-zäüÄÜß0-9\-_.!~]+$/;
|
||||
|
@ -53,6 +57,7 @@ export default class OaiController {
|
|||
private xml: XMLBuilder;
|
||||
private proc;
|
||||
|
||||
|
||||
constructor(public tokenWorker: TokenWorkerContract) {
|
||||
// Load the XSLT file
|
||||
this.proc = readFileSync('public/assets2/datasetxml2oai.sef.json');
|
||||
|
@ -60,12 +65,12 @@ export default class OaiController {
|
|||
dayjs.extend(timezone);
|
||||
}
|
||||
|
||||
public async index({ response, request }: HttpContextContract): Promise<void> {
|
||||
public async index({ response, request }: HttpContext): Promise<void> {
|
||||
this.xml = create({ version: '1.0', encoding: 'UTF-8', standalone: true }, '<root></root>');
|
||||
|
||||
// this.proc = new XSLTProcessor();
|
||||
// const stylesheet = readFileSync(__dirname + "/datasetxml2oai.sef.json");
|
||||
const xsltParameter = (this.xsltParameter = {});
|
||||
const xsltParameter: XslTParameter = (this.xsltParameter = {});
|
||||
|
||||
let oaiRequest: Dictionary = {};
|
||||
if (request.method() === 'POST') {
|
||||
|
@ -106,7 +111,7 @@ export default class OaiController {
|
|||
|
||||
let xmlOutput; // = xmlString;
|
||||
try {
|
||||
const result = await transform({
|
||||
const result = await SaxonJS.transform({
|
||||
// stylesheetFileName: `${config.TMP_BASE_DIR}/data-quality/rules/iati.sef.json`,
|
||||
stylesheetText: this.proc,
|
||||
destination: 'serialized',
|
||||
|
@ -130,7 +135,7 @@ export default class OaiController {
|
|||
response.status(StatusCodes.OK).send(xmlOutput);
|
||||
}
|
||||
|
||||
protected async handleRequest(oaiRequest: Dictionary, request: RequestContract) {
|
||||
protected async handleRequest(oaiRequest: Dictionary, request: Request) {
|
||||
// Setup stylesheet
|
||||
// $this->loadStyleSheet('datasetxml2oai-pmh.xslt');
|
||||
|
||||
|
@ -258,14 +263,14 @@ export default class OaiController {
|
|||
protected async handleListIdentifiers(oaiRequest: Dictionary) {
|
||||
!this.tokenWorker.isConnected && (await this.tokenWorker.connect());
|
||||
|
||||
const maxIdentifier: number = Config.get('oai.max.listidentifiers', 100);
|
||||
const maxIdentifier: number = config.get('oai.max.listidentifiers', 100);
|
||||
await this.handleLists(oaiRequest, maxIdentifier);
|
||||
}
|
||||
|
||||
protected async handleListRecords(oaiRequest) {
|
||||
protected async handleListRecords(oaiRequest: Dictionary) {
|
||||
!this.tokenWorker.isConnected && (await this.tokenWorker.connect());
|
||||
|
||||
const maxRecords: number = Config.get('oai.max.listrecords', 100);
|
||||
const maxRecords: number = config.get('oai.max.listrecords', 100);
|
||||
await this.handleLists(oaiRequest, maxRecords);
|
||||
}
|
||||
|
||||
|
@ -335,7 +340,7 @@ export default class OaiController {
|
|||
}
|
||||
}
|
||||
|
||||
private async handleResumptionToken(oaiRequest: Dictionary, maxRecords: number, numWrapper) {
|
||||
private async handleResumptionToken(oaiRequest: Dictionary, maxRecords: number, numWrapper: ListParameter) {
|
||||
const resParam = oaiRequest['resumptionToken']; //e.g. "158886496600000"
|
||||
const token = await this.tokenWorker.get(resParam);
|
||||
|
||||
|
@ -352,7 +357,7 @@ export default class OaiController {
|
|||
this.xsltParameter['oai_metadataPrefix'] = numWrapper.metadataPrefix;
|
||||
}
|
||||
|
||||
private async handleNoResumptionToken(oaiRequest: Dictionary, numWrapper) {
|
||||
private async handleNoResumptionToken(oaiRequest: Dictionary, numWrapper: ListParameter) {
|
||||
// no resumptionToken is given
|
||||
if ('metadataPrefix' in oaiRequest) {
|
||||
numWrapper.metadataPrefix = oaiRequest['metadataPrefix'];
|
||||
|
@ -622,7 +627,7 @@ export default class OaiController {
|
|||
const msg = `Invalid SetSpec (data-type='${dataset.type}').
|
||||
Allowed characters are [${this.sampleRegEx}].`;
|
||||
// Log::error("OAI-PMH: $msg");
|
||||
Logger.error(`OAI-PMH: ${msg}`);
|
||||
logger.error(`OAI-PMH: ${msg}`);
|
||||
return;
|
||||
}
|
||||
const setSpec = 'data-type:' + dataset.type;
|
||||
|
|
|
@ -1,14 +1,19 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import User from 'App/Models/User';
|
||||
import Dataset from 'App/Models/Dataset';
|
||||
import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Field from 'App/Library/Field';
|
||||
import BaseModel from 'App/Models/BaseModel';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import User from '#app/Models/User';
|
||||
import Dataset from '#app/Models/Dataset';
|
||||
import Field from '#app/Library/Field';
|
||||
import BaseModel from '#app/Models/BaseModel';
|
||||
import { DateTime } from 'luxon';
|
||||
import { schema, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import { schema, rules } from '@adonisjs/validator';
|
||||
import { ModelQueryBuilderContract } from "@adonisjs/lucid/types/model";
|
||||
|
||||
interface Dictionary {
|
||||
[index: string]: string;
|
||||
}
|
||||
|
||||
|
||||
export default class DatasetsController {
|
||||
public async index({ auth, request, inertia }: HttpContextContract) {
|
||||
public async index({ auth, request, inertia }: HttpContext) {
|
||||
const user = (await User.find(auth.user?.id)) as User;
|
||||
const page = request.input('page', 1);
|
||||
let datasets: ModelQueryBuilderContract<typeof Dataset, Dataset> = Dataset.query();
|
||||
|
@ -55,7 +60,7 @@ export default class DatasetsController {
|
|||
});
|
||||
}
|
||||
|
||||
public async review({ request, inertia, response }: HttpContextContract) {
|
||||
public async review({ request, inertia, response }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
const dataset = await Dataset.query()
|
||||
.where('id', id)
|
||||
|
@ -79,7 +84,7 @@ export default class DatasetsController {
|
|||
}
|
||||
|
||||
const fieldnames: Array<string> = await dataset.describe();
|
||||
const fields = {};
|
||||
const fields: Dictionary = {};
|
||||
for (const fieldName of fieldnames) {
|
||||
const field: Field = dataset.getField(fieldName) as Field;
|
||||
const modelClass = field.getValueModelClass();
|
||||
|
@ -154,7 +159,7 @@ export default class DatasetsController {
|
|||
});
|
||||
}
|
||||
|
||||
public async reviewUpdate({ request, response }) {
|
||||
public async reviewUpdate({ request, response }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
// const { id } = params;
|
||||
const dataset = await Dataset.findOrFail(id);
|
||||
|
@ -185,7 +190,7 @@ export default class DatasetsController {
|
|||
}
|
||||
}
|
||||
|
||||
public async reject({ request, inertia, response }: HttpContextContract) {
|
||||
public async reject({ request, inertia, response }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
const dataset = await Dataset.query()
|
||||
.where('id', id)
|
||||
|
@ -213,7 +218,7 @@ export default class DatasetsController {
|
|||
});
|
||||
}
|
||||
|
||||
public async rejectUpdate({ request, response }) {
|
||||
public async rejectUpdate({ request, response }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
const dataset = await Dataset.query()
|
||||
.where('id', id)
|
||||
|
|
|
@ -1,21 +1,22 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import User from 'App/Models/User';
|
||||
import Dataset from 'App/Models/Dataset';
|
||||
import License from 'App/Models/License';
|
||||
import Project from 'App/Models/Project';
|
||||
import Title from 'App/Models/Title';
|
||||
import Description from 'App/Models/Description';
|
||||
import Language from 'App/Models/Language';
|
||||
import Coverage from 'App/Models/Coverage';
|
||||
import Collection from 'App/Models/Collection';
|
||||
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import User from '#app/Models/User';
|
||||
import Dataset from '#app/Models/Dataset';
|
||||
import License from '#app/Models/License';
|
||||
import Project from '#app/Models/Project';
|
||||
import Title from '#app/Models/Title';
|
||||
import Description from '#app/Models/Description';
|
||||
import Language from '#app/Models/Language';
|
||||
import Coverage from '#app/Models/Coverage';
|
||||
import Collection from '#app/Models/Collection';
|
||||
import { schema, rules } from '@adonisjs/validator';
|
||||
import { CustomMessages } from "@adonisjs/validator/types";
|
||||
import dayjs from 'dayjs';
|
||||
import Person from 'App/Models/Person';
|
||||
import Database from '@ioc:Adonis/Lucid/Database';
|
||||
import { TransactionClientContract } from '@ioc:Adonis/Lucid/Database';
|
||||
import Subject from 'App/Models/Subject';
|
||||
import CreateDatasetValidator from 'App/Validators/CreateDatasetValidator';
|
||||
import UpdateDatasetValidator from 'App/Validators/UpdateDatasetValidator';
|
||||
import Person from '#app/Models/Person';
|
||||
import db from '@adonisjs/lucid/services/db';
|
||||
import { TransactionClientContract } from "@adonisjs/lucid/types/database";
|
||||
import Subject from '#app/Models/Subject';
|
||||
import CreateDatasetValidator from '#app/Validators/CreateDatasetValidator';
|
||||
import UpdateDatasetValidator from '#app/Validators/UpdateDatasetValidator';
|
||||
import {
|
||||
TitleTypes,
|
||||
DescriptionTypes,
|
||||
|
@ -25,20 +26,24 @@ import {
|
|||
RelationTypes,
|
||||
DatasetTypes,
|
||||
SubjectTypes,
|
||||
} from 'Contracts/enums';
|
||||
import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm';
|
||||
import DatasetReference from 'App/Models/DatasetReference';
|
||||
import { cuid } from '@ioc:Adonis/Core/Helpers';
|
||||
import File from 'App/Models/File';
|
||||
} from '#contracts/enums';
|
||||
import { ModelQueryBuilderContract } from "@adonisjs/lucid/types/model";
|
||||
import DatasetReference from '#app/Models/DatasetReference';
|
||||
import { cuid } from '@adonisjs/core/helpers';
|
||||
import File from '#app/Models/File';
|
||||
import ClamScan from 'clamscan';
|
||||
import { ValidationException } from '@ioc:Adonis/Core/Validator';
|
||||
import Drive from '@ioc:Adonis/Core/Drive';
|
||||
import { Exception } from '@adonisjs/core/build/standalone';
|
||||
import { MultipartFileContract } from '@ioc:Adonis/Core/BodyParser';
|
||||
import { ValidationException } from '@adonisjs/validator';
|
||||
// import Drive from '@ioc:Adonis/Core/Drive';
|
||||
import { Exception } from "@adonisjs/core/exceptions";
|
||||
import { MultipartFile } from '@adonisjs/core/types/bodyparser';
|
||||
import * as crypto from 'crypto';
|
||||
import app from '@adonisjs/core/services/app';
|
||||
interface Dictionary {
|
||||
[index: string]: string;
|
||||
}
|
||||
|
||||
export default class DatasetController {
|
||||
public async index({ auth, request, inertia }: HttpContextContract) {
|
||||
public async index({ auth, request, inertia }: HttpContext) {
|
||||
const user = (await User.find(auth.user?.id)) as User;
|
||||
const page = request.input('page', 1);
|
||||
let datasets: ModelQueryBuilderContract<typeof Dataset, Dataset> = Dataset.query();
|
||||
|
@ -105,7 +110,7 @@ export default class DatasetController {
|
|||
});
|
||||
}
|
||||
|
||||
public async create({ inertia }: HttpContextContract) {
|
||||
public async create({ inertia }: HttpContext) {
|
||||
const licenses = await License.query().select('id', 'name_long').where('active', 'true').pluck('name_long', 'id');
|
||||
|
||||
const projects = await Project.query().pluck('label', 'id');
|
||||
|
@ -140,7 +145,7 @@ export default class DatasetController {
|
|||
});
|
||||
}
|
||||
|
||||
public async firstStep({ request, response }: HttpContextContract) {
|
||||
public async firstStep({ request, response }: HttpContext) {
|
||||
const newDatasetSchema = schema.create({
|
||||
language: schema.string({ trim: true }, [
|
||||
rules.regex(/^[a-zA-Z0-9-_]+$/), //Must be alphanumeric with hyphens or underscores
|
||||
|
@ -149,6 +154,7 @@ export default class DatasetController {
|
|||
rights: schema.string([rules.equalTo('true')]),
|
||||
});
|
||||
|
||||
await request.validate({ schema: newDatasetSchema, messages: this.messages });
|
||||
try {
|
||||
// Step 2 - Validate request body against the schema
|
||||
|
||||
|
@ -162,7 +168,7 @@ export default class DatasetController {
|
|||
return response.redirect().back();
|
||||
}
|
||||
|
||||
public async secondStep({ request, response }: HttpContextContract) {
|
||||
public async secondStep({ request, response }: HttpContext) {
|
||||
const newDatasetSchema = schema.create({
|
||||
// first step
|
||||
language: schema.string({ trim: true }, [
|
||||
|
@ -217,7 +223,7 @@ export default class DatasetController {
|
|||
return response.redirect().back();
|
||||
}
|
||||
|
||||
public async thirdStep({ request, response }: HttpContextContract) {
|
||||
public async thirdStep({ request, response }: HttpContext) {
|
||||
const newDatasetSchema = schema.create({
|
||||
// first step
|
||||
language: schema.string({ trim: true }, [
|
||||
|
@ -305,7 +311,7 @@ export default class DatasetController {
|
|||
return response.redirect().back();
|
||||
}
|
||||
|
||||
public async store({ auth, request, response, session }: HttpContextContract) {
|
||||
public async store({ auth, request, response, session }: HttpContext) {
|
||||
// node ace make:validator CreateDataset
|
||||
try {
|
||||
// Step 2 - Validate request body against the schema
|
||||
|
@ -320,7 +326,7 @@ export default class DatasetController {
|
|||
|
||||
let trx: TransactionClientContract | null = null;
|
||||
try {
|
||||
trx = await Database.transaction();
|
||||
trx = await db.transaction();
|
||||
const user = (await User.find(auth.user?.id)) as User;
|
||||
|
||||
await this.createDatasetAndAssociations(user, request, trx);
|
||||
|
@ -341,7 +347,7 @@ export default class DatasetController {
|
|||
// return response.redirect().back();
|
||||
}
|
||||
|
||||
private async createDatasetAndAssociations(user: User, request: HttpContextContract['request'], trx: TransactionClientContract) {
|
||||
private async createDatasetAndAssociations(user: User, request: HttpContext['request'], trx: TransactionClientContract) {
|
||||
// Create a new instance of the Dataset model:
|
||||
const dataset = new Dataset();
|
||||
dataset.type = request.input('type');
|
||||
|
@ -422,7 +428,7 @@ export default class DatasetController {
|
|||
}
|
||||
|
||||
// save data files
|
||||
const uploadedFiles = request.files('files');
|
||||
const uploadedFiles: MultipartFile[] = request.files('files');
|
||||
for (const [index, file] of uploadedFiles.entries()) {
|
||||
try {
|
||||
await this.scanFileForViruses(file.tmpPath); //, 'gitea.lan', 3310);
|
||||
|
@ -439,13 +445,12 @@ export default class DatasetController {
|
|||
const mimeType = file.headers['content-type'] || 'application/octet-stream'; // Fallback to a default MIME type
|
||||
const datasetFolder = `files/${dataset.id}`;
|
||||
// const size = file.size;
|
||||
await file.moveToDisk(
|
||||
datasetFolder,
|
||||
await file.move(
|
||||
app.makePath( datasetFolder),
|
||||
{
|
||||
name: fileName,
|
||||
overwrite: true, // overwrite in case of conflict
|
||||
},
|
||||
'local',
|
||||
);
|
||||
// save file metadata into db
|
||||
const newFile = new File();
|
||||
|
@ -476,7 +481,7 @@ export default class DatasetController {
|
|||
return `file-${randomString1}-${randomString2}-${randomString3}-${randomString4}-${randomString5}.${extension}`;
|
||||
}
|
||||
|
||||
private async scanFileForViruses(filePath, host?: string, port?: number): Promise<void> {
|
||||
private async scanFileForViruses(filePath: string | undefined, host?: string, port?: number): Promise<void> {
|
||||
// const clamscan = await (new ClamScan().init());
|
||||
const opts: ClamScan.Options = {
|
||||
removeInfected: true, // If true, removes infected files
|
||||
|
@ -537,7 +542,7 @@ export default class DatasetController {
|
|||
|
||||
// Helper function to extract pivot attributes from a person object
|
||||
private extractPivotAttributes(person: any) {
|
||||
const pivotAttributes = {};
|
||||
const pivotAttributes: Dictionary = {};
|
||||
for (const key in person) {
|
||||
if (key.startsWith('pivot_')) {
|
||||
// pivotAttributes[key] = person[key];
|
||||
|
@ -596,7 +601,7 @@ export default class DatasetController {
|
|||
};
|
||||
|
||||
// public async release({ params, view }) {
|
||||
public async release({ request, inertia, response }: HttpContextContract) {
|
||||
public async release({ request, inertia, response }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
|
||||
const dataset = await Dataset.query()
|
||||
|
@ -623,7 +628,7 @@ export default class DatasetController {
|
|||
});
|
||||
}
|
||||
|
||||
public async releaseUpdate({ request, response }: HttpContextContract) {
|
||||
public async releaseUpdate({ request, response }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
const dataset = await Dataset.query().preload('files').where('id', id).firstOrFail();
|
||||
|
||||
|
@ -655,7 +660,10 @@ export default class DatasetController {
|
|||
});
|
||||
|
||||
try {
|
||||
await request.validate({ schema: newSchema });
|
||||
await request.validate({
|
||||
schema: newSchema,
|
||||
// reporter: validator.reporters.vanilla,
|
||||
});
|
||||
} catch (error) {
|
||||
// return response.badRequest(error.messages);
|
||||
throw error;
|
||||
|
@ -698,7 +706,7 @@ export default class DatasetController {
|
|||
// throw new GeneralException(trans('exceptions.publish.release.update_error'));
|
||||
}
|
||||
|
||||
public async edit({ request, inertia, response }) {
|
||||
public async edit({ request, inertia, response }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
const datasetQuery = Dataset.query().where('id', id);
|
||||
datasetQuery
|
||||
|
@ -789,7 +797,7 @@ export default class DatasetController {
|
|||
});
|
||||
}
|
||||
|
||||
public async update({ request, response, session }: HttpContextContract) {
|
||||
public async update({ request, response, session }: HttpContext) {
|
||||
try {
|
||||
// await request.validate({ schema: newDatasetSchema, messages: this.messages });
|
||||
await request.validate(UpdateDatasetValidator);
|
||||
|
@ -804,7 +812,7 @@ export default class DatasetController {
|
|||
|
||||
let trx: TransactionClientContract | null = null;
|
||||
try {
|
||||
trx = await Database.transaction();
|
||||
trx = await db.transaction();
|
||||
// const user = (await User.find(auth.user?.id)) as User;
|
||||
// await this.createDatasetAndAssociations(user, request, trx);
|
||||
const dataset = await Dataset.findOrFail(id);
|
||||
|
@ -897,7 +905,7 @@ export default class DatasetController {
|
|||
}
|
||||
|
||||
// handle new uploaded files:
|
||||
const uploadedFiles: MultipartFileContract[] = request.files('files');
|
||||
const uploadedFiles: MultipartFile[] = request.files('files');
|
||||
if (Array.isArray(uploadedFiles) && uploadedFiles.length > 0) {
|
||||
for (const [index, fileData] of uploadedFiles.entries()) {
|
||||
try {
|
||||
|
@ -911,7 +919,11 @@ export default class DatasetController {
|
|||
// move to disk:
|
||||
const fileName = `file-${cuid()}.${fileData.extname}`;
|
||||
const datasetFolder = `files/${dataset.id}`;
|
||||
await fileData.moveToDisk(datasetFolder, { name: fileName, overwrite: true }, 'local');
|
||||
await fileData.moveToDisk(
|
||||
datasetFolder,
|
||||
{ name: fileName, overwrite: true },
|
||||
'local'
|
||||
);
|
||||
// let path = coverImage.filePath;
|
||||
|
||||
//save to db:
|
||||
|
@ -988,7 +1000,7 @@ export default class DatasetController {
|
|||
}
|
||||
}
|
||||
|
||||
public async delete({ request, inertia, response, session }) {
|
||||
public async delete({ request, inertia, response, session }: HttpContext) {
|
||||
const id = request.param('id');
|
||||
try {
|
||||
const dataset = await Dataset.query()
|
||||
|
@ -1022,7 +1034,7 @@ export default class DatasetController {
|
|||
}
|
||||
}
|
||||
|
||||
public async deleteUpdate({ params, session, response }) {
|
||||
public async deleteUpdate({ params, session, response }: HttpContext) {
|
||||
try {
|
||||
const dataset = await Dataset.query().where('id', params.id).preload('files').firstOrFail();
|
||||
|
||||
|
@ -1041,7 +1053,7 @@ export default class DatasetController {
|
|||
if (folderContents.length === 0) {
|
||||
await Drive.delete(datasetFolder);
|
||||
}
|
||||
// delete dataset wirh relation from db
|
||||
// delete dataset wirh relation in db
|
||||
await dataset.delete();
|
||||
session.flash({ message: 'You have deleted 1 dataset!' });
|
||||
return response.redirect().toRoute('dataset.list');
|
||||
|
@ -1059,7 +1071,7 @@ export default class DatasetController {
|
|||
} else if (error instanceof Exception) {
|
||||
// General exception handling
|
||||
return response
|
||||
.flash({ errors: { error: error.message } })
|
||||
.flash('errors', { error: error.message })
|
||||
.redirect()
|
||||
.back();
|
||||
} else {
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
// import User from 'App/Models/User';
|
||||
// import Dataset from 'App/Models/Dataset';
|
||||
// import License from 'App/Models/License';
|
||||
|
@ -10,12 +10,11 @@ import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
|||
// import Collection from 'App/Models/Collection';
|
||||
// import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
||||
// import dayjs from 'dayjs';
|
||||
import Person from 'App/Models/Person';
|
||||
|
||||
import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Person from '#app/Models/Person';
|
||||
import { ModelQueryBuilderContract } from "@adonisjs/lucid/types/model";
|
||||
|
||||
export default class PersonController {
|
||||
public async index({ auth, request, inertia }: HttpContextContract) {
|
||||
public async index({ auth, request, inertia }: HttpContext) {
|
||||
// const user = (await User.find(auth.user?.id)) as User;
|
||||
const page = request.input('page', 1);
|
||||
let persons: ModelQueryBuilderContract<typeof Person, Person> = Person.query();
|
||||
|
|
|
@ -12,24 +12,53 @@
|
|||
| properly.
|
||||
|
|
||||
*/
|
||||
import app from '@adonisjs/core/services/app';
|
||||
import { HttpContext, ExceptionHandler } from '@adonisjs/core/http';
|
||||
// import logger from '@adonisjs/core/services/logger';
|
||||
import type { StatusPageRange, StatusPageRenderer } from '@adonisjs/core/types/http';
|
||||
|
||||
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import Logger from '@ioc:Adonis/Core/Logger';
|
||||
import HttpExceptionHandler from '@ioc:Adonis/Core/HttpExceptionHandler';
|
||||
export default class HttpExceptionHandler extends ExceptionHandler {
|
||||
/**
|
||||
* In debug mode, the exception handler will display verbose errors
|
||||
* with pretty printed stack traces.
|
||||
*/
|
||||
protected debug = !app.inProduction;
|
||||
|
||||
export default class ExceptionHandler extends HttpExceptionHandler {
|
||||
protected statusPages = {
|
||||
'401,403': 'errors/unauthorized',
|
||||
'404': 'errors/not-found',
|
||||
'500..599': 'errors/server-error',
|
||||
/**
|
||||
* Status pages are used to display a custom HTML pages for certain error
|
||||
* codes. You might want to enable them in production only, but feel
|
||||
* free to enable them in development as well.
|
||||
*/
|
||||
protected renderStatusPages = true;
|
||||
|
||||
// protected statusPages = {
|
||||
// '401,403': 'errors/unauthorized',
|
||||
// '404': 'errors/not-found',
|
||||
// '500..599': 'errors/server-error',
|
||||
// };
|
||||
|
||||
/**
|
||||
* Status pages is a collection of error code range and a callback
|
||||
* to return the HTML contents to send as a response.
|
||||
*/
|
||||
protected statusPages: Record<StatusPageRange, StatusPageRenderer> = {
|
||||
'401..403': (error, { view }) => {
|
||||
return view.render('./errors/unauthorized', { error });
|
||||
},
|
||||
'404': (error, { view }) => {
|
||||
return view.render('./errors/not-found', { error });
|
||||
},
|
||||
'500..599': (error, { view }) => {
|
||||
return view.render('./errors/server-error', { error });
|
||||
},
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super(Logger);
|
||||
}
|
||||
// constructor() {
|
||||
// super(logger);
|
||||
// }
|
||||
|
||||
public async handle(error: any, ctx: HttpContextContract) {
|
||||
const { response, request, inertia } = ctx;
|
||||
public async handle(error: any, ctx: HttpContext) {
|
||||
const { response, request, session } = ctx;
|
||||
|
||||
/**
|
||||
* Handle failed authentication attempt
|
||||
|
@ -44,11 +73,16 @@ export default class ExceptionHandler extends HttpExceptionHandler {
|
|||
// }
|
||||
|
||||
// https://github.com/inertiajs/inertia-laravel/issues/56
|
||||
if (request.header('X-Inertia') && [500, 503, 404, 403, 401].includes(response.getStatus())) {
|
||||
return inertia.render('Error', {
|
||||
status: response.getStatus(),
|
||||
message: error.message,
|
||||
});
|
||||
// let test = response.getStatus(); //200
|
||||
// let header = request.header('X-Inertia'); // true
|
||||
if (request.header('X-Inertia') && [500, 503, 404, 403, 401, 200].includes(response.getStatus())) {
|
||||
// session.flash('errors', error.messages.errors);
|
||||
session.flash('errors', error.messages);
|
||||
return response.redirect().back();
|
||||
// return inertia.render('Error', {
|
||||
// status: response.getStatus(),
|
||||
// message: error.message,
|
||||
// });
|
||||
// ->toResponse($request)
|
||||
// ->setStatusCode($response->status());
|
||||
}
|
||||
|
@ -58,4 +92,14 @@ export default class ExceptionHandler extends HttpExceptionHandler {
|
|||
*/
|
||||
return super.handle(error, ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* The method is used to report error to the logging service or
|
||||
* the a third party error monitoring service.
|
||||
*
|
||||
* @note You should not attempt to send a response from this method.
|
||||
*/
|
||||
async report(error: unknown, ctx: HttpContext) {
|
||||
return super.report(error, ctx);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { StatusCodes } from 'http-status-codes';
|
||||
import HTTPException from './HttpException';
|
||||
import HTTPException from './HttpException.js';
|
||||
|
||||
class InternalServerErrorException extends HTTPException {
|
||||
constructor(message?: string) {
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
import { Exception } from '@adonisjs/core/build/standalone';
|
||||
import { Exception } from "@adonisjs/core/exceptions";
|
||||
import { HttpContext } from "@adonisjs/core/http";
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -23,21 +24,21 @@ export default class InvalidCredentialException extends Exception {
|
|||
* Unable to find user
|
||||
*/
|
||||
public static invalidUid() {
|
||||
const error = new this('User not found', 400, 'E_INVALID_AUTH_UID');
|
||||
const error = new this('User not found', {status: 400, code: 'E_INVALID_AUTH_UID'});
|
||||
return error;
|
||||
}
|
||||
/**
|
||||
* Invalid user password
|
||||
*/
|
||||
public static invalidPassword() {
|
||||
const error = new this('Password mis-match', 400, 'E_INVALID_AUTH_PASSWORD');
|
||||
const error = new this('Password mis-match', {status: 400, code: 'E_INVALID_AUTH_PASSWORD'});
|
||||
return error;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flash error message and redirect the user back
|
||||
*/
|
||||
private respondWithRedirect(error, ctx) {
|
||||
private respondWithRedirect(error: any, ctx: HttpContext) {
|
||||
// if (!ctx.session) {
|
||||
// return ctx.response.status(this.status).send(this.responseText);
|
||||
// }
|
||||
|
@ -59,7 +60,7 @@ export default class InvalidCredentialException extends Exception {
|
|||
* Handle this exception by itself
|
||||
*/
|
||||
|
||||
public handle(error, ctx) {
|
||||
public handle(error: any, ctx: HttpContext) {
|
||||
// return response.status(403).view.render("errors/unauthorized", {
|
||||
// error: error,
|
||||
// });
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import { StatusCodes } from 'http-status-codes';
|
||||
// import HTTPException from './HttpException';
|
||||
import { OaiErrorCodes } from './OaiErrorCodes';
|
||||
import { OaiErrorCodes } from './OaiErrorCodes.js';
|
||||
|
||||
export class ErrorCode {
|
||||
public static readonly Unauthenticated = 'Unauthenticated';
|
||||
|
|
|
@ -1,34 +0,0 @@
|
|||
import { Response } from '@adonisjs/http-server/build/src/Response';
|
||||
import { ServerResponse, IncomingMessage } from 'http';
|
||||
import { RouterContract } from '@ioc:Adonis/Core/Route';
|
||||
import { EncryptionContract } from '@ioc:Adonis/Core/Encryption';
|
||||
import { ResponseConfig, ResponseContract } from '@ioc:Adonis/Core/Response';
|
||||
|
||||
class FlashResponse extends Response implements ResponseContract {
|
||||
protected static macros = {};
|
||||
protected static getters = {};
|
||||
constructor(
|
||||
public request: IncomingMessage,
|
||||
public response: ServerResponse,
|
||||
flashEncryption: EncryptionContract,
|
||||
flashConfig: ResponseConfig,
|
||||
flashRouter: RouterContract,
|
||||
) {
|
||||
super(request, response, flashEncryption, flashConfig, flashRouter);
|
||||
}
|
||||
public nonce: string;
|
||||
|
||||
public flash(key: string, message: any): this {
|
||||
// Store the flash message in the session
|
||||
this.ctx?.session.flash(key, message);
|
||||
return this;
|
||||
}
|
||||
|
||||
public toRoute(route: string): this {
|
||||
// Redirect to the specified route
|
||||
super.redirect().toRoute(route);
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
export default FlashResponse;
|
|
@ -1,11 +1,12 @@
|
|||
// import { Client } from 'guzzle';
|
||||
// import { Log } from '@adonisjs/core/build/standalone';
|
||||
// import { DoiInterface } from './interfaces/DoiInterface';
|
||||
import DoiClientContract from 'App/Library/Doi/DoiClientContract';
|
||||
import DoiClientException from 'App/Exceptions/DoiClientException';
|
||||
import DoiClientContract from '#app/Library/Doi/DoiClientContract';
|
||||
import DoiClientException from '#app/Exceptions/DoiClientException';
|
||||
import { StatusCodes } from 'http-status-codes';
|
||||
import Logger from '@ioc:Adonis/Core/Logger';
|
||||
import axios, { AxiosResponse } from 'axios';
|
||||
import logger from '@adonisjs/core/services/logger';
|
||||
import { AxiosResponse } from 'axios';
|
||||
import axios from 'axios';
|
||||
|
||||
export class DoiClient implements DoiClientContract {
|
||||
public username: string;
|
||||
|
@ -22,7 +23,7 @@ export class DoiClient implements DoiClientContract {
|
|||
|
||||
if (this.username === '' || this.password === '' || this.serviceUrl === '') {
|
||||
const message = 'issing configuration settings to properly initialize DOI client';
|
||||
Logger.error(message);
|
||||
logger.error(message);
|
||||
throw new DoiClientException(StatusCodes.BAD_REQUEST, message);
|
||||
}
|
||||
}
|
||||
|
@ -49,7 +50,7 @@ export class DoiClient implements DoiClientContract {
|
|||
'Content-Type': 'application/xml;charset=UTF-8',
|
||||
};
|
||||
try {
|
||||
const metadataResponse = await axios.put(`${this.serviceUrl}/metadata/${doiValue}`, xmlMeta, { auth, headers });
|
||||
const metadataResponse = await axios.default.put(`${this.serviceUrl}/metadata/${doiValue}`, xmlMeta, { auth, headers });
|
||||
|
||||
// Response Codes
|
||||
// 201 Created: operation successful
|
||||
|
@ -60,11 +61,11 @@ export class DoiClient implements DoiClientContract {
|
|||
// let test = metadataResponse.data; // 'OK (10.21388/TETHYS.213)'
|
||||
if (metadataResponse.status !== 201) {
|
||||
const message = `Unexpected DataCite MDS response code ${metadataResponse.status}`;
|
||||
Logger.error(message);
|
||||
logger.error(message);
|
||||
throw new DoiClientException(metadataResponse.status, message);
|
||||
}
|
||||
|
||||
const doiResponse = await axios.put(`${this.serviceUrl}/doi/${doiValue}`, `doi=${doiValue}\nurl=${landingPageUrl}`, {
|
||||
const doiResponse = await axios.default.put(`${this.serviceUrl}/doi/${doiValue}`, `doi=${doiValue}\nurl=${landingPageUrl}`, {
|
||||
auth,
|
||||
headers,
|
||||
});
|
||||
|
@ -77,7 +78,7 @@ export class DoiClient implements DoiClientContract {
|
|||
// 412 Precondition failed: metadata must be uploaded first.
|
||||
if (doiResponse.status !== 201) {
|
||||
const message = `Unexpected DataCite MDS response code ${doiResponse.status}`;
|
||||
Logger.error(message);
|
||||
logger.error(message);
|
||||
throw new DoiClientException(doiResponse.status, message);
|
||||
}
|
||||
|
||||
|
@ -85,7 +86,7 @@ export class DoiClient implements DoiClientContract {
|
|||
} catch (error) {
|
||||
// const message = `request for registering DOI failed with ${error.message}`;
|
||||
// Handle the error, log it, or rethrow as needed
|
||||
Logger.error(error.message);
|
||||
logger.error(error.message);
|
||||
throw new DoiClientException(error.response.status, error.response.data);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,5 @@
|
|||
// import ResumptionToken from './ResumptionToken';
|
||||
import { AxiosResponse } from 'axios';
|
||||
|
||||
export default interface DoiClientContract {
|
||||
username: string;
|
||||
|
@ -6,7 +7,7 @@ export default interface DoiClientContract {
|
|||
serviceUrl: string;
|
||||
// prefix: string;
|
||||
// base_domain: string;
|
||||
registerDoi(doiValue: string, xmlMeta: string, landingPageUrl: string);
|
||||
registerDoi(doiValue: string, xmlMeta: string, landingPageUrl: string): Promise<AxiosResponse<any>>;
|
||||
// get(key: string): Promise<ResumptionToken | null>;
|
||||
// set(token: ResumptionToken): Promise<string>;
|
||||
}
|
|
@ -1,10 +0,0 @@
|
|||
import ResumptionToken from './ResumptionToken';
|
||||
|
||||
export default interface TokenWorkerContract {
|
||||
ttl: number;
|
||||
isConnected: boolean;
|
||||
connect();
|
||||
close();
|
||||
get(key: string): Promise<ResumptionToken | null>;
|
||||
set(token: ResumptionToken): Promise<string>;
|
||||
}
|
11
app/Library/Oai/TokenWorkerContract.ts
Normal file
11
app/Library/Oai/TokenWorkerContract.ts
Normal file
|
@ -0,0 +1,11 @@
|
|||
import ResumptionToken from './ResumptionToken.js';
|
||||
|
||||
export default abstract class TokenWorkerContract {
|
||||
abstract ttl: number;
|
||||
abstract isConnected: boolean;
|
||||
abstract connect(): void;
|
||||
abstract close(): void;
|
||||
abstract get(key: string): Promise<ResumptionToken | null>;
|
||||
abstract set(token: ResumptionToken): Promise<string>;
|
||||
}
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
import ResumptionToken from './ResumptionToken';
|
||||
import ResumptionToken from './ResumptionToken.js';
|
||||
import { createClient, RedisClientType } from 'redis';
|
||||
import InternalServerErrorException from 'App/Exceptions/InternalServerException';
|
||||
import InternalServerErrorException from '#app/Exceptions/InternalServerException';
|
||||
import { sprintf } from 'sprintf-js';
|
||||
import dayjs from 'dayjs';
|
||||
import TokenWorkerContract from './TokenWorker';
|
||||
import TokenWorkerContract from './TokenWorkerContract.js';
|
||||
|
||||
export default class TokenWorkerService implements TokenWorkerContract {
|
||||
protected filePrefix = 'rs_';
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces';
|
||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
|
||||
import { create } from 'xmlbuilder2';
|
||||
import Dataset from 'App/Models/Dataset';
|
||||
import Field from './Field';
|
||||
import BaseModel from 'App/Models/BaseModel';
|
||||
import Dataset from '#app/Models/Dataset';
|
||||
import Field from './Field.js';
|
||||
import BaseModel from '#app/Models/BaseModel';
|
||||
import { DateTime } from 'luxon';
|
||||
|
||||
export default class Strategy {
|
||||
|
@ -10,7 +10,7 @@ export default class Strategy {
|
|||
private config;
|
||||
private xml: XMLBuilder;
|
||||
|
||||
constructor(config) {
|
||||
constructor(config: any) {
|
||||
this.version = 1.0;
|
||||
this.config = config;
|
||||
}
|
||||
|
@ -45,11 +45,11 @@ export default class Strategy {
|
|||
|
||||
for (const fieldname of fieldsDiff) {
|
||||
const field = model.getField(fieldname);
|
||||
this.mapField(field, modelNode);
|
||||
this.mapField(field as Field, modelNode);
|
||||
}
|
||||
}
|
||||
|
||||
private mapField(field, modelNode: XMLBuilder) {
|
||||
private mapField(field: Field, modelNode: XMLBuilder) {
|
||||
const modelClass = field.getValueModelClass();
|
||||
let fieldValues = field.getValue();
|
||||
|
||||
|
@ -107,7 +107,7 @@ export default class Strategy {
|
|||
childNode.att('Timezone', zoneName);
|
||||
}
|
||||
|
||||
private mapModelAttributes(myObject, childNode: XMLBuilder) {
|
||||
private mapModelAttributes(myObject: any, childNode: XMLBuilder) {
|
||||
Object.keys(myObject).forEach((prop) => {
|
||||
let value = myObject[prop];
|
||||
// console.log(`${prop}: ${value}`);
|
||||
|
@ -161,7 +161,7 @@ export default class Strategy {
|
|||
return fieldValues?.toString().trim();
|
||||
}
|
||||
|
||||
private createModelNode(model) {
|
||||
private createModelNode(model: Dataset) {
|
||||
const className = 'Rdr_' + model.constructor.name.split('\\').pop(); //Rdr_Dataset
|
||||
// return dom.createElement(className);
|
||||
return this.xml.root().ele(className);
|
||||
|
|
|
@ -1,18 +1,20 @@
|
|||
import Dataset from 'App/Models/Dataset';
|
||||
import Dataset from '#app/Models/Dataset';
|
||||
import { Client } from '@opensearch-project/opensearch';
|
||||
import { create } from 'xmlbuilder2';
|
||||
import { transform } from 'saxon-js';
|
||||
import XmlModel from 'App/Library/XmlModel';
|
||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces';
|
||||
import Logger from '@ioc:Adonis/Core/Logger';
|
||||
import SaxonJS from 'saxon-js';
|
||||
import XmlModel from '#app/Library/XmlModel';
|
||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
|
||||
import logger from '@adonisjs/core/services/logger';
|
||||
import { readFileSync } from 'fs';
|
||||
import { DateTime } from 'luxon';
|
||||
// import Config from '@ioc:Adonis/Core/Config';
|
||||
import { getDomain } from 'App/Utils/utility-functions';
|
||||
import { getDomain } from '#app/Utils/utility-functions';
|
||||
|
||||
// const opensearchNode = process.env.OPENSEARCH_HOST || 'localhost';
|
||||
// const client = new Client({ node: `http://${opensearchNode}` }); // replace with your OpenSearch endpoint
|
||||
|
||||
interface XslTParameter {
|
||||
[key: string]: any;
|
||||
}
|
||||
export default {
|
||||
// opensearchNode: process.env.OPENSEARCH_HOST || 'localhost',
|
||||
client: new Client({ node: `http://${process.env.OPENSEARCH_HOST || 'localhost'}` }), // replace with your OpenSearch endpoint
|
||||
|
@ -20,7 +22,7 @@ export default {
|
|||
async getDoiRegisterString(dataset: Dataset): Promise<string | undefined> {
|
||||
try {
|
||||
const proc = readFileSync('public/assets2/doi_datacite.sef.json');
|
||||
const xsltParameter = {};
|
||||
const xsltParameter: XslTParameter = {};
|
||||
let xml = create({ version: '1.0', encoding: 'UTF-8', standalone: true }, '<root></root>');
|
||||
const datasetNode = xml.root().ele('Dataset');
|
||||
await createXmlRecord(dataset, datasetNode);
|
||||
|
@ -50,7 +52,7 @@ export default {
|
|||
|
||||
let xmlOutput; // = xmlString;
|
||||
try {
|
||||
const result = await transform({
|
||||
const result = await SaxonJS.transform({
|
||||
// stylesheetFileName: `${config.TMP_BASE_DIR}/data-quality/rules/iati.sef.json`,
|
||||
stylesheetText: proc,
|
||||
destination: 'serialized',
|
||||
|
@ -61,12 +63,12 @@ export default {
|
|||
});
|
||||
xmlOutput = result.principalResult;
|
||||
} catch (error) {
|
||||
Logger.error('An error occurred while creating the user', error.message);
|
||||
logger.error('An error occurred while creating the user', error.message);
|
||||
}
|
||||
|
||||
return xmlOutput;
|
||||
} catch (error) {
|
||||
Logger.error(`An error occurred while indexing datsaet with publish_id ${dataset.publish_id}.`);
|
||||
logger.error(`An error occurred while indexing datsaet with publish_id ${dataset.publish_id}.`);
|
||||
}
|
||||
},
|
||||
|
||||
|
@ -82,27 +84,27 @@ export default {
|
|||
body: document,
|
||||
refresh: true,
|
||||
});
|
||||
Logger.info(`dataset with publish_id ${dataset.publish_id} successfully indexed`);
|
||||
logger.info(`dataset with publish_id ${dataset.publish_id} successfully indexed`);
|
||||
} catch (error) {
|
||||
Logger.error(`An error occurred while indexing datsaet with publish_id ${dataset.publish_id}.`);
|
||||
logger.error(`An error occurred while indexing datsaet with publish_id ${dataset.publish_id}.`);
|
||||
}
|
||||
},
|
||||
|
||||
async getTransformedString(dataset, proc): Promise<string> {
|
||||
async getTransformedString(dataset: Dataset, proc: Buffer): Promise<string> {
|
||||
let xml = create({ version: '1.0', encoding: 'UTF-8', standalone: true }, '<root></root>');
|
||||
const datasetNode = xml.root().ele('Dataset');
|
||||
await createXmlRecord(dataset, datasetNode);
|
||||
const xmlString = xml.end({ prettyPrint: false });
|
||||
|
||||
try {
|
||||
const result = await transform({
|
||||
const result = await SaxonJS.transform({
|
||||
stylesheetText: proc,
|
||||
destination: 'serialized',
|
||||
sourceText: xmlString,
|
||||
});
|
||||
return result.principalResult;
|
||||
} catch (error) {
|
||||
Logger.error(`An error occurred while creating the user, error: ${error.message},`);
|
||||
logger.error(`An error occurred while creating the user, error: ${error.message},`);
|
||||
return '';
|
||||
}
|
||||
},
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
import DocumentXmlCache from 'App/Models/DocumentXmlCache';
|
||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces';
|
||||
import Dataset from 'App/Models/Dataset';
|
||||
import Strategy from './Strategy';
|
||||
import DocumentXmlCache from '#app/Models/DocumentXmlCache';
|
||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
|
||||
import Dataset from '#app/Models/Dataset';
|
||||
import Strategy from './Strategy.js';
|
||||
import { DateTime } from 'luxon';
|
||||
import { builder } from 'xmlbuilder2';
|
||||
|
||||
|
|
|
@ -1,67 +0,0 @@
|
|||
import { AuthenticationException } from '@adonisjs/auth/build/standalone';
|
||||
import type { GuardsList } from '@ioc:Adonis/Addons/Auth';
|
||||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
|
||||
/**
|
||||
* Auth middleware is meant to restrict un-authenticated access to a given route
|
||||
* or a group of routes.
|
||||
*
|
||||
* You must register this middleware inside `start/kernel.ts` file under the list
|
||||
* of named middleware.
|
||||
*/
|
||||
export default class AuthMiddleware {
|
||||
/**
|
||||
* The URL to redirect to when request is Unauthorized
|
||||
*/
|
||||
protected redirectTo = '/app/login';
|
||||
|
||||
/**
|
||||
* Authenticates the current HTTP request against a custom set of defined
|
||||
* guards.
|
||||
*
|
||||
* The authentication loop stops as soon as the user is authenticated using any
|
||||
* of the mentioned guards and that guard will be used by the rest of the code
|
||||
* during the current request.
|
||||
*/
|
||||
protected async authenticate(auth: HttpContextContract['auth'], guards: (keyof GuardsList)[]) {
|
||||
/**
|
||||
* Hold reference to the guard last attempted within the for loop. We pass
|
||||
* the reference of the guard to the "AuthenticationException", so that
|
||||
* it can decide the correct response behavior based upon the guard
|
||||
* driver
|
||||
*/
|
||||
let guardLastAttempted: string | undefined;
|
||||
|
||||
for (let guard of guards) {
|
||||
guardLastAttempted = guard;
|
||||
|
||||
if (await auth.use(guard).check()) {
|
||||
/**
|
||||
* Instruct auth to use the given guard as the default guard for
|
||||
* the rest of the request, since the user authenticated
|
||||
* succeeded here
|
||||
*/
|
||||
auth.defaultGuard = guard;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unable to authenticate using any guard
|
||||
*/
|
||||
throw new AuthenticationException('Unauthorized access', 'E_UNAUTHORIZED_ACCESS', guardLastAttempted, this.redirectTo);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle request
|
||||
*/
|
||||
public async handle({ auth }: HttpContextContract, next: () => Promise<void>, customGuards: (keyof GuardsList)[]) {
|
||||
/**
|
||||
* Uses the user defined guards or the default guard mentioned in
|
||||
* the config file
|
||||
*/
|
||||
const guards = customGuards.length ? customGuards : [auth.name];
|
||||
await this.authenticate(auth, guards);
|
||||
await next();
|
||||
}
|
||||
}
|
|
@ -1,13 +1,14 @@
|
|||
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import Config from '@ioc:Adonis/Core/Config';
|
||||
import Database from '@ioc:Adonis/Lucid/Database';
|
||||
import User from 'App/Models/User';
|
||||
import { Exception } from '@adonisjs/core/build/standalone';
|
||||
import { HttpContext } from '@adonisjs/core/http';
|
||||
// import Config from '@ioc:Adonis/Core/Config';
|
||||
import config from '@adonisjs/core/services/config';
|
||||
import db from '@adonisjs/lucid/services/db';
|
||||
import User from '#app/Models/User';
|
||||
import { Exception } from '@adonisjs/core/exceptions';
|
||||
|
||||
const permissionTable = Config.get('rolePermission.permission_table', 'permissions');
|
||||
const rolePermissionTable = Config.get('rolePermission.role_permission_table', 'role_has_permissions');
|
||||
const roleTable = Config.get('rolePermission.role_table', 'roles');
|
||||
const userRoleTable = Config.get('rolePermission.user_role_table', 'link_accounts_roles');
|
||||
const permissionTable = config.get('rolePermission.permission_table', 'permissions');
|
||||
const rolePermissionTable = config.get('rolePermission.role_permission_table', 'role_has_permissions');
|
||||
const roleTable = config.get('rolePermission.role_table', 'roles');
|
||||
const userRoleTable = config.get('rolePermission.user_role_table', 'link_accounts_roles');
|
||||
|
||||
/**
|
||||
* Permission authentication to check if user has any of the specified permissions
|
||||
|
@ -18,7 +19,7 @@ export default class Can {
|
|||
/**
|
||||
* Handle request
|
||||
*/
|
||||
public async handle({ auth, response }: HttpContextContract, next: () => Promise<void>, permissionNames: string[]) {
|
||||
public async handle({ auth, response }: HttpContext, next: () => Promise<void>, permissionNames: string[]) {
|
||||
/**
|
||||
* Check if user is logged-in
|
||||
*/
|
||||
|
@ -31,9 +32,10 @@ export default class Can {
|
|||
// return response.unauthorized({
|
||||
// error: `Doesn't have required role(s): ${permissionNames.join(',')}`,
|
||||
// });
|
||||
throw new Exception(`Doesn't have required permission(s): ${permissionNames.join(',')}`, 401);
|
||||
throw new Exception(`Doesn't have required permission(s): ${permissionNames.join(',')}`, { status: 401 });
|
||||
}
|
||||
await next();
|
||||
// await next();
|
||||
return next();
|
||||
}
|
||||
|
||||
private async checkHasPermissions(user: User, permissionNames: Array<string>): Promise<boolean> {
|
||||
|
@ -66,7 +68,7 @@ export default class Can {
|
|||
rows: {
|
||||
0: { permissioncount },
|
||||
},
|
||||
} = await Database.rawQuery(
|
||||
} = await db.rawQuery(
|
||||
'SELECT count("p"."name") as permissionCount FROM ' +
|
||||
roleTable +
|
||||
' r INNER JOIN ' +
|
||||
|
|
|
@ -1,11 +1,12 @@
|
|||
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import Config from '@ioc:Adonis/Core/Config';
|
||||
import Database from '@ioc:Adonis/Lucid/Database';
|
||||
import User from 'App/Models/User';
|
||||
import { HttpContext } from '@adonisjs/core/http';
|
||||
// import Config from '@ioc:Adonis/Core/Config';
|
||||
import config from '@adonisjs/core/services/config'
|
||||
import db from '@adonisjs/lucid/services/db';
|
||||
import User from '#app/Models/User';
|
||||
// import { Exception } from '@adonisjs/core/build/standalone'
|
||||
|
||||
const roleTable = Config.get('rolePermission.role_table', 'roles');
|
||||
const userRoleTable = Config.get('rolePermission.user_role_table', 'user_roles');
|
||||
const roleTable = config.get('rolePermission.role_table', 'roles');
|
||||
const userRoleTable = config.get('rolePermission.user_role_table', 'user_roles');
|
||||
|
||||
/**
|
||||
* Role authentication to check if user has any of the specified roles
|
||||
|
@ -16,7 +17,7 @@ export default class Is {
|
|||
/**
|
||||
* Handle request
|
||||
*/
|
||||
public async handle({ auth, response }: HttpContextContract, next: () => Promise<void>, roleNames: string[]) {
|
||||
public async handle({ auth, response }: HttpContext, next: () => Promise<void>, roleNames: string[]) {
|
||||
/**
|
||||
* Check if user is logged-in or not.
|
||||
*/
|
||||
|
@ -33,7 +34,8 @@ export default class Is {
|
|||
// 401,
|
||||
// "E_INVALID_AUTH_UID");
|
||||
}
|
||||
await next();
|
||||
// await next();
|
||||
return next()
|
||||
}
|
||||
|
||||
private async checkHasRoles(user: User, roleNames: Array<string>): Promise<boolean> {
|
||||
|
@ -46,7 +48,7 @@ export default class Is {
|
|||
0: {
|
||||
0: { roleCount },
|
||||
},
|
||||
} = await Database.rawQuery(
|
||||
} = await db.rawQuery(
|
||||
'SELECT count(`ur`.`id`) as roleCount FROM ' +
|
||||
userRoleTable +
|
||||
' ur INNER JOIN ' +
|
||||
|
|
|
@ -1,23 +1,25 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import Database from '@ioc:Adonis/Lucid/Database';
|
||||
import Config from '@ioc:Adonis/Core/Config';
|
||||
import User from 'app/Models/User';
|
||||
import { Exception } from '@adonisjs/core/build/standalone';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import db from '@adonisjs/lucid/services/db';
|
||||
import config from '@adonisjs/core/services/config';
|
||||
import User from '#app/Models/User';
|
||||
import { Exception } from '@adonisjs/core/exceptions';
|
||||
|
||||
const roleTable = Config.get('rolePermission.role_table', 'roles');
|
||||
const userRoleTable = Config.get('rolePermission.user_role_table', 'link_accounts_roles');
|
||||
// const roleTable = Config.get('rolePermission.role_table', 'roles');
|
||||
const roleTable = config.get('rolePermission.role_table', 'roles');
|
||||
// const userRoleTable = Config.get('rolePermission.user_role_table', 'link_accounts_roles');
|
||||
const userRoleTable = config.get('rolePermission.user_role_table', 'user_roles');
|
||||
|
||||
// node ace make:middleware role
|
||||
export default class Role {
|
||||
// .middleware(['auth', 'role:admin,moderator'])
|
||||
public async handle({ auth, response }: HttpContextContract, next: () => Promise<void>, userRoles: string[]) {
|
||||
public async handle({ auth, response }: HttpContext, next: () => Promise<void>, userRoles: string[]) {
|
||||
// Check if user is logged-in or not.
|
||||
// let expression = "";
|
||||
// if (Array.isArray(args)) {
|
||||
// expression = args.join(" || ");
|
||||
// }
|
||||
|
||||
let user = await auth.user;
|
||||
let user = auth.user as User;
|
||||
if (!user) {
|
||||
return response.unauthorized({ error: 'Must be logged in' });
|
||||
}
|
||||
|
@ -28,7 +30,7 @@ export default class Role {
|
|||
// error: `Doesn't have required role(s): ${userRoles.join(',')}`,
|
||||
// // error: `Doesn't have required role(s)`,
|
||||
// });
|
||||
throw new Exception(`Doesn't have required role(s): ${userRoles.join(',')}`, 401);
|
||||
throw new Exception(`Doesn't have required role(s): ${userRoles.join(',')}`, { status: 401 });
|
||||
}
|
||||
|
||||
// code for middleware goes here. ABOVE THE NEXT CALL
|
||||
|
@ -62,7 +64,7 @@ export default class Role {
|
|||
rows: {
|
||||
0: { rolecount },
|
||||
},
|
||||
} = await Database.rawQuery(
|
||||
} = await db.rawQuery(
|
||||
'SELECT count("r"."id") as roleCount FROM ' +
|
||||
roleTable +
|
||||
' r INNER JOIN ' +
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
|
||||
/**
|
||||
* Silent auth middleware can be used as a global middleware to silent check
|
||||
|
@ -10,7 +10,7 @@ export default class SilentAuthMiddleware {
|
|||
/**
|
||||
* Handle request
|
||||
*/
|
||||
public async handle({ auth }: HttpContextContract, next: () => Promise<void>) {
|
||||
public async handle({ auth }: HttpContext, next: () => Promise<void>) {
|
||||
/**
|
||||
* Check if user is logged-in or not. If yes, then `ctx.auth.user` will be
|
||||
* set to the instance of the currently logged in user.
|
||||
|
|
25
app/Middleware/auth_middleware.ts
Normal file
25
app/Middleware/auth_middleware.ts
Normal file
|
@ -0,0 +1,25 @@
|
|||
import type { HttpContext } from '@adonisjs/core/http'
|
||||
import type { NextFn } from '@adonisjs/core/types/http'
|
||||
import type { Authenticators } from '@adonisjs/auth/types'
|
||||
|
||||
/**
|
||||
* Auth middleware is used authenticate HTTP requests and deny
|
||||
* access to unauthenticated users.
|
||||
*/
|
||||
export default class AuthMiddleware {
|
||||
/**
|
||||
* The URL to redirect to, when authentication fails
|
||||
*/
|
||||
redirectTo = '/app/login'
|
||||
|
||||
async handle(
|
||||
ctx: HttpContext,
|
||||
next: NextFn,
|
||||
options: {
|
||||
guards?: (keyof Authenticators)[]
|
||||
} = {}
|
||||
) {
|
||||
await ctx.auth.authenticateUsing(options.guards, { loginRoute: this.redirectTo })
|
||||
return next()
|
||||
}
|
||||
}
|
19
app/Middleware/container_bindings_middleware.ts
Normal file
19
app/Middleware/container_bindings_middleware.ts
Normal file
|
@ -0,0 +1,19 @@
|
|||
import { Logger } from '@adonisjs/core/logger';
|
||||
import { HttpContext } from '@adonisjs/core/http';
|
||||
import { NextFn } from '@adonisjs/core/types/http';
|
||||
|
||||
/**
|
||||
* The container bindings middleware binds classes to their request
|
||||
* specific value using the container resolver.
|
||||
*
|
||||
* - We bind "HttpContext" class to the "ctx" object
|
||||
* - And bind "Logger" class to the "ctx.logger" object
|
||||
*/
|
||||
export default class ContainerBindingsMiddleware {
|
||||
handle(ctx: HttpContext, next: NextFn) {
|
||||
ctx.containerResolver.bindValue(HttpContext, ctx);
|
||||
ctx.containerResolver.bindValue(Logger, ctx.logger);
|
||||
|
||||
return next();
|
||||
}
|
||||
}
|
27
app/Middleware/guest_middleware.ts
Normal file
27
app/Middleware/guest_middleware.ts
Normal file
|
@ -0,0 +1,27 @@
|
|||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import type { NextFn } from '@adonisjs/core/types/http';
|
||||
import type { Authenticators } from '@adonisjs/auth/types';
|
||||
|
||||
/**
|
||||
* Guest middleware is used to deny access to routes that should
|
||||
* be accessed by unauthenticated users.
|
||||
*
|
||||
* For example, the login page should not be accessible if the user
|
||||
* is already logged-in
|
||||
*/
|
||||
export default class GuestMiddleware {
|
||||
/**
|
||||
* The URL to redirect to when user is logged-in
|
||||
*/
|
||||
redirectTo = '/';
|
||||
|
||||
async handle(ctx: HttpContext, next: NextFn, options: { guards?: (keyof Authenticators)[] } = {}) {
|
||||
for (let guard of options.guards || [ctx.auth.defaultGuard]) {
|
||||
if (await ctx.auth.use(guard).check()) {
|
||||
return ctx.response.redirect(this.redirectTo, true);
|
||||
}
|
||||
}
|
||||
|
||||
return next();
|
||||
}
|
||||
}
|
27
app/Middleware/stardust_middleware.ts
Normal file
27
app/Middleware/stardust_middleware.ts
Normal file
|
@ -0,0 +1,27 @@
|
|||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import type { NextFn } from '@adonisjs/core/types/http';
|
||||
|
||||
export default class StardustMiddleware {
|
||||
async handle(ctx: HttpContext, next: NextFn): Promise<void> {
|
||||
/**
|
||||
* Middleware logic goes here (before the next call)
|
||||
*/
|
||||
// console.log(ctx);
|
||||
const { pathname } = new URL(ctx.request.completeUrl());
|
||||
globalThis.stardust = {
|
||||
...globalThis.stardust,
|
||||
pathname,
|
||||
};
|
||||
|
||||
/**
|
||||
* Call next method in the pipeline and return its output
|
||||
*/
|
||||
const output = await next();
|
||||
return output;
|
||||
}
|
||||
}
|
||||
|
||||
// import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
// export default class StardustMiddleware {
|
||||
// handle({ request }: HttpContextContract, next: () => Promise<void>): Promise<void>;
|
||||
// }
|
|
@ -1,4 +1,4 @@
|
|||
import { BaseModel as LucidBaseModel } from '@ioc:Adonis/Lucid/Orm';
|
||||
import { BaseModel as LucidBaseModel } from '@adonisjs/lucid/orm';
|
||||
// import { ManyToManyQueryClient } from '@ioc:Adonis/Lucid/Orm';
|
||||
|
||||
// export class CustomManyToManyQueryClient extends ManyToManyQueryClient {
|
||||
|
@ -29,6 +29,8 @@ export default class BaseModel extends LucidBaseModel {
|
|||
*/
|
||||
// private fillInvoked: boolean = false;
|
||||
|
||||
[key: string]: any;
|
||||
|
||||
public static fillable: string[] = [];
|
||||
|
||||
public fill(attributes: any, allowExtraProperties: boolean = false): this {
|
||||
|
@ -118,6 +120,8 @@ export default class BaseModel extends LucidBaseModel {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
// export class DatasetRelatedBaseModel extends LucidBaseModel {
|
||||
// public dataset: BelongsTo<typeof Dataset>;
|
||||
// }
|
||||
|
|
|
@ -1,7 +1,9 @@
|
|||
import { column, SnakeCaseNamingStrategy, manyToMany, ManyToMany, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Dataset from './Dataset';
|
||||
import BaseModel from './BaseModel';
|
||||
import CollectionRole from './CollectionRole';
|
||||
import { column, SnakeCaseNamingStrategy, manyToMany, belongsTo } from '@adonisjs/lucid/orm';
|
||||
import Dataset from './Dataset.js';
|
||||
import BaseModel from './BaseModel.js';
|
||||
import CollectionRole from './CollectionRole.js';
|
||||
import type { ManyToMany } from "@adonisjs/lucid/types/relations";
|
||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class Collection extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
import { column, SnakeCaseNamingStrategy, hasMany, HasMany } from '@ioc:Adonis/Lucid/Orm';
|
||||
import BaseModel from './BaseModel';
|
||||
import Collection from './Collection';
|
||||
import { column, SnakeCaseNamingStrategy, hasMany } from '@adonisjs/lucid/orm';
|
||||
import BaseModel from './BaseModel.js';
|
||||
import Collection from './Collection.js';
|
||||
import type { HasMany } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class CollectionRole extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
import { column, SnakeCaseNamingStrategy, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm';
|
||||
import { column, SnakeCaseNamingStrategy, belongsTo } from '@adonisjs/lucid/orm';
|
||||
import { DateTime } from 'luxon';
|
||||
import Dataset from './Dataset';
|
||||
import BaseModel from './BaseModel';
|
||||
import Dataset from './Dataset.js';
|
||||
import BaseModel from './BaseModel.js';
|
||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class Coverage extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
|
|
@ -2,31 +2,31 @@ import {
|
|||
column,
|
||||
SnakeCaseNamingStrategy,
|
||||
manyToMany,
|
||||
ManyToMany,
|
||||
belongsTo,
|
||||
BelongsTo,
|
||||
hasMany,
|
||||
HasMany,
|
||||
computed,
|
||||
hasOne,
|
||||
HasOne,
|
||||
} from '@ioc:Adonis/Lucid/Orm';
|
||||
hasOne
|
||||
} from '@adonisjs/lucid/orm';
|
||||
import { DateTime } from 'luxon';
|
||||
import dayjs from 'dayjs';
|
||||
import Person from './Person';
|
||||
import User from './User';
|
||||
import Title from './Title';
|
||||
import Description from './Description';
|
||||
import License from './License';
|
||||
import Subject from './Subject';
|
||||
import File from './File';
|
||||
import Coverage from './Coverage';
|
||||
import DatasetReference from './DatasetReference';
|
||||
import Collection from './Collection';
|
||||
import DatasetIdentifier from './DatasetIdentifier';
|
||||
import Project from './Project';
|
||||
import DocumentXmlCache from './DocumentXmlCache';
|
||||
import DatasetExtension from 'App/Models/Traits/DatasetExtension'; // Adjust the import path
|
||||
import Person from './Person.js';
|
||||
import User from './User.js';
|
||||
import Title from './Title.js';
|
||||
import Description from './Description.js';
|
||||
import License from './License.js';
|
||||
import Subject from './Subject.js';
|
||||
import File from './File.js';
|
||||
import Coverage from './Coverage.js';
|
||||
import DatasetReference from './DatasetReference.js';
|
||||
import Collection from './Collection.js';
|
||||
import DatasetIdentifier from './DatasetIdentifier.js';
|
||||
import Project from './Project.js';
|
||||
import DocumentXmlCache from './DocumentXmlCache.js';
|
||||
import DatasetExtension from '#app/Models/Traits/DatasetExtension';
|
||||
import type { ManyToMany } from "@adonisjs/lucid/types/relations";
|
||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
||||
import type { HasMany } from "@adonisjs/lucid/types/relations";
|
||||
import type { HasOne } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class Dataset extends DatasetExtension {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
import { column, SnakeCaseNamingStrategy, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm';
|
||||
import { column, SnakeCaseNamingStrategy, belongsTo } from '@adonisjs/lucid/orm';
|
||||
import { DateTime } from 'luxon';
|
||||
import Dataset from './Dataset';
|
||||
import BaseModel from './BaseModel';
|
||||
import Dataset from './Dataset.js';
|
||||
import BaseModel from './BaseModel.js';
|
||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class DatasetIdentifier extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
|
|
@ -1,7 +1,8 @@
|
|||
import { column, SnakeCaseNamingStrategy, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm';
|
||||
import { column, SnakeCaseNamingStrategy, belongsTo } from '@adonisjs/lucid/orm';
|
||||
import { DateTime } from 'luxon';
|
||||
import Dataset from './Dataset';
|
||||
import BaseModel from './BaseModel';
|
||||
import Dataset from './Dataset.js';
|
||||
import BaseModel from './BaseModel.js';
|
||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class DatasetReference extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
import { column, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Dataset from './Dataset';
|
||||
import BaseModel from './BaseModel';
|
||||
import { column, belongsTo } from '@adonisjs/lucid/orm';
|
||||
import Dataset from './Dataset.js';
|
||||
import BaseModel from './BaseModel.js';
|
||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class Description extends BaseModel {
|
||||
public static primaryKey = 'id';
|
||||
|
|
|
@ -1,9 +1,10 @@
|
|||
import { column, BaseModel, SnakeCaseNamingStrategy, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Dataset from './Dataset';
|
||||
import { column, BaseModel, SnakeCaseNamingStrategy, belongsTo } from '@adonisjs/lucid/orm';
|
||||
import Dataset from './Dataset.js';
|
||||
import { builder, create } from 'xmlbuilder2';
|
||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces';
|
||||
import Database from '@ioc:Adonis/Lucid/Database';
|
||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
|
||||
import db from '@adonisjs/lucid/services/db';
|
||||
import { DateTime } from 'luxon';
|
||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class DocumentXmlCache extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
@ -86,7 +87,7 @@ export default class DocumentXmlCache extends BaseModel {
|
|||
// Assuming 'DocumentXmlCache' has a table with a 'server_date_modified' column in your database
|
||||
public static async hasValidEntry(datasetId: number, datasetServerDateModified: DateTime): Promise<boolean> {
|
||||
const serverDateModifiedString: string = datasetServerDateModified.toFormat('yyyy-MM-dd HH:mm:ss'); // Convert DateTime to ISO string
|
||||
const query = Database.from(this.table)
|
||||
const query = db.from(this.table)
|
||||
.where('document_id', datasetId)
|
||||
.where('server_date_modified', '>=', serverDateModifiedString) // Check if server_date_modified is newer or equal
|
||||
.first();
|
||||
|
|
|
@ -1,13 +1,22 @@
|
|||
import { DateTime } from 'luxon';
|
||||
import { column, hasMany, HasMany, belongsTo, BelongsTo, SnakeCaseNamingStrategy, computed } from '@ioc:Adonis/Lucid/Orm';
|
||||
import HashValue from './HashValue';
|
||||
import Dataset from './Dataset';
|
||||
import BaseModel from './BaseModel';
|
||||
import { column, hasMany, belongsTo, SnakeCaseNamingStrategy, computed } from '@adonisjs/lucid/orm';
|
||||
import HashValue from './HashValue.js';
|
||||
import Dataset from './Dataset.js';
|
||||
import BaseModel from './BaseModel.js';
|
||||
// import { Buffer } from 'buffer';
|
||||
import * as fs from 'fs';
|
||||
import crypto from 'crypto';
|
||||
import { TransactionClientContract } from '@ioc:Adonis/Lucid/Database';
|
||||
import Drive from '@ioc:Adonis/Core/Drive';
|
||||
// import Drive from '@ioc:Adonis/Core/Drive';
|
||||
import Drive from '@adonisjs/drive';
|
||||
|
||||
import type { HasMany } from "@adonisjs/lucid/types/relations";
|
||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
||||
// import { TransactionClientContract } from "@adonisjs/lucid/database";
|
||||
import { TransactionClientContract } from '@adonisjs/lucid/types/database';
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
export default class File extends BaseModel {
|
||||
// private readonly _data: Uint8Array;
|
||||
|
@ -162,7 +171,7 @@ export default class File extends BaseModel {
|
|||
await super.delete();
|
||||
}
|
||||
|
||||
private async _checksumFile(path, hashName = 'md5'): Promise<string> {
|
||||
private async _checksumFile(path: string, hashName = 'md5'): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const hash = crypto.createHash(hashName);
|
||||
const stream = fs.createReadStream(path);
|
||||
|
|
|
@ -1,5 +1,6 @@
|
|||
import { column, BaseModel, belongsTo, BelongsTo, SnakeCaseNamingStrategy } from '@ioc:Adonis/Lucid/Orm';
|
||||
import File from './File';
|
||||
import { column, BaseModel, belongsTo, SnakeCaseNamingStrategy } from '@adonisjs/lucid/orm';
|
||||
import File from './File.js';
|
||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class HashValue extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { column, SnakeCaseNamingStrategy } from '@ioc:Adonis/Lucid/Orm';
|
||||
import BaseModel from './BaseModel';
|
||||
import { column, SnakeCaseNamingStrategy } from '@adonisjs/lucid/orm';
|
||||
import BaseModel from './BaseModel.js';
|
||||
// import { DateTime } from 'luxon';
|
||||
|
||||
export default class Language extends BaseModel {
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
import { column, SnakeCaseNamingStrategy } from '@ioc:Adonis/Lucid/Orm';
|
||||
import BaseModel from './BaseModel';
|
||||
import { column, SnakeCaseNamingStrategy } from '@adonisjs/lucid/orm';
|
||||
import BaseModel from './BaseModel.js';
|
||||
|
||||
export default class License extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
import { column, manyToMany, ManyToMany, SnakeCaseNamingStrategy, beforeUpdate, beforeCreate } from '@ioc:Adonis/Lucid/Orm';
|
||||
import { column, manyToMany, SnakeCaseNamingStrategy } from '@adonisjs/lucid/orm';
|
||||
import { DateTime } from 'luxon';
|
||||
import dayjs from 'dayjs';
|
||||
import Role from 'App/Models/Role';
|
||||
import BaseModel from './BaseModel';
|
||||
import Role from '#app/Models/Role';
|
||||
import BaseModel from './BaseModel.js';
|
||||
import type { ManyToMany } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class Permission extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
@ -44,12 +45,12 @@ export default class Permission extends BaseModel {
|
|||
})
|
||||
public updated_at: DateTime;
|
||||
|
||||
@beforeCreate()
|
||||
@beforeUpdate()
|
||||
public static async resetDate(role) {
|
||||
role.created_at = this.formatDateTime(role.created_at);
|
||||
role.updated_at = this.formatDateTime(role.updated_at);
|
||||
}
|
||||
// @beforeCreate()
|
||||
// @beforeUpdate()
|
||||
// public static async resetDate(role) {
|
||||
// role.created_at = this.formatDateTime(role.created_at);
|
||||
// role.updated_at = this.formatDateTime(role.updated_at);
|
||||
// }
|
||||
|
||||
// public static boot() {
|
||||
// super.boot()
|
||||
|
@ -64,22 +65,22 @@ export default class Permission extends BaseModel {
|
|||
// })
|
||||
// }
|
||||
|
||||
private static formatDateTime(datetime) {
|
||||
let value = new Date(datetime);
|
||||
return datetime
|
||||
? value.getFullYear() +
|
||||
'-' +
|
||||
(value.getMonth() + 1) +
|
||||
'-' +
|
||||
value.getDate() +
|
||||
' ' +
|
||||
value.getHours() +
|
||||
':' +
|
||||
value.getMinutes() +
|
||||
':' +
|
||||
value.getSeconds()
|
||||
: datetime;
|
||||
}
|
||||
// private static formatDateTime(datetime) {
|
||||
// let value = new Date(datetime);
|
||||
// return datetime
|
||||
// ? value.getFullYear() +
|
||||
// '-' +
|
||||
// (value.getMonth() + 1) +
|
||||
// '-' +
|
||||
// value.getDate() +
|
||||
// ' ' +
|
||||
// value.getHours() +
|
||||
// ':' +
|
||||
// value.getMinutes() +
|
||||
// ':' +
|
||||
// value.getSeconds()
|
||||
// : datetime;
|
||||
// }
|
||||
|
||||
// @belongsTo(() => Role)
|
||||
// public role: BelongsTo<typeof Role>;
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
import { column, SnakeCaseNamingStrategy, computed, manyToMany, ManyToMany } from '@ioc:Adonis/Lucid/Orm';
|
||||
import { column, SnakeCaseNamingStrategy, computed, manyToMany } from '@adonisjs/lucid/orm';
|
||||
import { DateTime } from 'luxon';
|
||||
import dayjs from 'dayjs';
|
||||
import Dataset from './Dataset';
|
||||
import BaseModel from './BaseModel';
|
||||
import Dataset from './Dataset.js';
|
||||
import BaseModel from './BaseModel.js';
|
||||
import type { ManyToMany } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class Person extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import { column, SnakeCaseNamingStrategy } from '@ioc:Adonis/Lucid/Orm';
|
||||
import { column, SnakeCaseNamingStrategy } from '@adonisjs/lucid/orm';
|
||||
import { DateTime } from 'luxon';
|
||||
import BaseModel from './BaseModel';
|
||||
import BaseModel from './BaseModel.js';
|
||||
|
||||
export default class Project extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
|
|
@ -1,10 +1,11 @@
|
|||
import { column, SnakeCaseNamingStrategy, manyToMany, ManyToMany, beforeCreate, beforeUpdate } from '@ioc:Adonis/Lucid/Orm';
|
||||
import BaseModel from './BaseModel';
|
||||
import { column, SnakeCaseNamingStrategy, manyToMany, beforeCreate, beforeUpdate } from '@adonisjs/lucid/orm';
|
||||
import BaseModel from './BaseModel.js';
|
||||
import { DateTime } from 'luxon';
|
||||
// import moment from 'moment';
|
||||
import dayjs from 'dayjs';
|
||||
import User from './User';
|
||||
import Permission from 'App/Models/Permission';
|
||||
import User from './User.js';
|
||||
import Permission from '#app/Models/Permission';
|
||||
import type { ManyToMany } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class Role extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
@ -46,7 +47,7 @@ export default class Role extends BaseModel {
|
|||
|
||||
@beforeCreate()
|
||||
@beforeUpdate()
|
||||
public static async resetDate(role) {
|
||||
public static async resetDate(role: Role) {
|
||||
role.created_at = this.formatDateTime(role.created_at);
|
||||
role.updated_at = this.formatDateTime(role.updated_at);
|
||||
}
|
||||
|
@ -64,7 +65,7 @@ export default class Role extends BaseModel {
|
|||
// });
|
||||
// }
|
||||
|
||||
private static formatDateTime(datetime) {
|
||||
private static formatDateTime(datetime: any) {
|
||||
let value = new Date(datetime);
|
||||
return datetime
|
||||
? value.getFullYear() +
|
||||
|
|
|
@ -1,9 +1,10 @@
|
|||
import { column, SnakeCaseNamingStrategy, manyToMany, ManyToMany, computed} from '@ioc:Adonis/Lucid/Orm';
|
||||
import BaseModel from './BaseModel';
|
||||
import { column, SnakeCaseNamingStrategy, manyToMany, computed} from '@adonisjs/lucid/orm';
|
||||
import BaseModel from './BaseModel.js';
|
||||
|
||||
import { DateTime } from 'luxon';
|
||||
import dayjs from 'dayjs';
|
||||
import Dataset from './Dataset';
|
||||
import Dataset from './Dataset.js';
|
||||
import type { ManyToMany } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class Subject extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
import { column, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Dataset from './Dataset';
|
||||
import BaseModel from './BaseModel';
|
||||
import { column, belongsTo } from '@adonisjs/lucid/orm';
|
||||
import Dataset from './Dataset.js';
|
||||
import BaseModel from './BaseModel.js';
|
||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
// import { DatasetRelatedBaseModel } from './BaseModel';
|
||||
|
||||
export default class Title extends BaseModel {
|
||||
|
|
|
@ -1,8 +1,10 @@
|
|||
import { column, BaseModel, SnakeCaseNamingStrategy, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm';
|
||||
import User from './User';
|
||||
import { column, BaseModel, SnakeCaseNamingStrategy, belongsTo } from '@adonisjs/lucid/orm';
|
||||
import User from './User.js';
|
||||
import { DateTime } from 'luxon';
|
||||
import dayjs from 'dayjs';
|
||||
import Encryption from '@ioc:Adonis/Core/Encryption';
|
||||
// import Encryption from '@ioc:Adonis/Core/Encryption';
|
||||
import encryption from '@adonisjs/core/services/encryption';
|
||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
export default class TotpSecret extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
|
@ -21,16 +23,16 @@ export default class TotpSecret extends BaseModel {
|
|||
// public twoFactorSecret: string;
|
||||
@column({
|
||||
serializeAs: null,
|
||||
consume: (value: string) => (value ? JSON.parse(Encryption.decrypt(value) ?? '{}') : null),
|
||||
prepare: (value: string) => Encryption.encrypt(JSON.stringify(value)),
|
||||
consume: (value: string) => (value ? JSON.parse(encryption.decrypt(value) ?? '{}') : null),
|
||||
prepare: (value: string) => encryption.encrypt(JSON.stringify(value)),
|
||||
})
|
||||
public twoFactorSecret?: string | null;
|
||||
|
||||
// serializeAs: null removes the model properties from the serialized output.
|
||||
@column({
|
||||
serializeAs: null,
|
||||
consume: (value: string) => (value ? JSON.parse(Encryption.decrypt(value) ?? '[]') : []),
|
||||
prepare: (value: string[]) => Encryption.encrypt(JSON.stringify(value)),
|
||||
consume: (value: string) => (value ? JSON.parse(encryption.decrypt(value) ?? '[]') : []),
|
||||
prepare: (value: string[]) => encryption.encrypt(JSON.stringify(value)),
|
||||
})
|
||||
public twoFactorRecoveryCodes?: string[] | null;
|
||||
|
||||
|
|
|
@ -1,15 +1,15 @@
|
|||
import Title from 'App/Models/Title';
|
||||
import Description from 'App/Models/Description';
|
||||
import License from 'App/Models/License';
|
||||
import Person from 'App/Models/Person';
|
||||
import DatasetReference from 'App/Models/DatasetReference';
|
||||
import DatasetIdentifier from 'App/Models/DatasetIdentifier';
|
||||
import Subject from 'App/Models/Subject';
|
||||
import File from 'App/Models/File';
|
||||
import Coverage from 'App/Models/Coverage';
|
||||
import Collection from 'App/Models/Collection';
|
||||
import { BaseModel as LucidBaseModel } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Field from 'App/Library/Field';
|
||||
import Title from '#app/Models/Title';
|
||||
import Description from '#app/Models/Description';
|
||||
import License from '#app/Models/License';
|
||||
import Person from '#app/Models/Person';
|
||||
import DatasetReference from '#app/Models/DatasetReference';
|
||||
import DatasetIdentifier from '#app/Models/DatasetIdentifier';
|
||||
import Subject from '#app/Models/Subject';
|
||||
import File from '#app/Models/File';
|
||||
import Coverage from '#app/Models/Coverage';
|
||||
import Collection from '#app/Models/Collection';
|
||||
import { BaseModel as LucidBaseModel } from '@adonisjs/lucid/orm';
|
||||
import Field from '#app/Library/Field';
|
||||
import { DateTime } from 'luxon';
|
||||
|
||||
// @StaticImplements<LucidModel>()
|
||||
|
@ -31,11 +31,12 @@ export type DatasetRelatedModel =
|
|||
| typeof File;
|
||||
|
||||
export default abstract class DatasetExtension extends LucidBaseModel {
|
||||
public abstract id;
|
||||
public abstract id: number;
|
||||
public externalFields: Record<string, any> = this.getExternalFields();
|
||||
// which fields shoud#t be published
|
||||
protected internalFields: Record<string, any> = {};
|
||||
protected fields: Record<string, any> = {};
|
||||
[key: string]: any;
|
||||
|
||||
private getExternalFields(): Record<string, any> {
|
||||
// External fields definition
|
||||
|
|
|
@ -1,13 +1,25 @@
|
|||
import { DateTime } from 'luxon';
|
||||
import { column, beforeSave, manyToMany, ManyToMany, hasMany, HasMany } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Hash from '@ioc:Adonis/Core/Hash';
|
||||
import Role from './Role';
|
||||
import Database from '@ioc:Adonis/Lucid/Database';
|
||||
import Config from '@ioc:Adonis/Core/Config';
|
||||
import Dataset from './Dataset';
|
||||
import BaseModel from './BaseModel';
|
||||
import Encryption from '@ioc:Adonis/Core/Encryption';
|
||||
import { TotpState } from 'Contracts/enums';
|
||||
import { withAuthFinder } from '@adonisjs/auth';
|
||||
import { column, beforeSave, manyToMany, hasMany } from '@adonisjs/lucid/orm';
|
||||
import hash from '@adonisjs/core/services/hash';
|
||||
import Role from './Role.js';
|
||||
import db from '@adonisjs/lucid/services/db';
|
||||
// import Config from '@ioc:Adonis/Core/Config';
|
||||
import config from '@adonisjs/core/services/config';
|
||||
import Dataset from './Dataset.js';
|
||||
import BaseModel from './BaseModel.js';
|
||||
// import Encryption from '@ioc:Adonis/Core/Encryption';
|
||||
import encryption from '@adonisjs/core/services/encryption';
|
||||
import { TotpState } from '#contracts/enums';
|
||||
import type { ManyToMany } from '@adonisjs/lucid/types/relations';
|
||||
import type { HasMany } from '@adonisjs/lucid/types/relations';
|
||||
import { compose } from '@adonisjs/core/helpers';
|
||||
|
||||
const AuthFinder = withAuthFinder(() => hash.use('laravel'), {
|
||||
uids: ['email'],
|
||||
passwordColumnName: 'password',
|
||||
});
|
||||
|
||||
// import TotpSecret from './TotpSecret';
|
||||
|
||||
// export default interface IUser {
|
||||
|
@ -20,13 +32,14 @@ import { TotpState } from 'Contracts/enums';
|
|||
// // async (user): Promise<void>;
|
||||
// }
|
||||
|
||||
const permissionTable = Config.get('rolePermission.permission_table', 'permissions');
|
||||
const rolePermissionTable = Config.get('rolePermission.role_permission_table', 'role_has_permissions');
|
||||
// const permissionTable = config.get('rolePermission.permission_table', 'permissions');
|
||||
// const rolePermissionTable = config.get('rolePermission.role_permission_table', 'role_has_permissions');
|
||||
|
||||
const roleTable = Config.get('rolePermission.role_table', 'roles');
|
||||
const userRoleTable = Config.get('rolePermission.user_role_table', 'link_accounts_roles');
|
||||
// const roleTable = config.get('rolePermission.role_table', 'roles');
|
||||
// const userRoleTable = config.get('rolePermission.user_role_table', 'link_accounts_roles');
|
||||
|
||||
export default class User extends BaseModel {
|
||||
export default class User extends compose(BaseModel, AuthFinder) {
|
||||
// export default class User extends BaseModel {
|
||||
public static table = 'accounts';
|
||||
|
||||
@column({ isPrimary: true })
|
||||
|
@ -50,16 +63,16 @@ export default class User extends BaseModel {
|
|||
// serializeAs: null removes the model properties from the serialized output.
|
||||
@column({
|
||||
serializeAs: null,
|
||||
consume: (value: string) => (value ? JSON.parse(Encryption.decrypt(value) ?? '{}') : null),
|
||||
prepare: (value: string) => Encryption.encrypt(JSON.stringify(value)),
|
||||
consume: (value: string) => (value ? JSON.parse(encryption.decrypt(value) ?? '{}') : null),
|
||||
prepare: (value: string) => encryption.encrypt(JSON.stringify(value)),
|
||||
})
|
||||
public twoFactorSecret?: string | null;
|
||||
|
||||
// serializeAs: null removes the model properties from the serialized output.
|
||||
@column({
|
||||
serializeAs: null,
|
||||
consume: (value: string) => (value ? JSON.parse(Encryption.decrypt(value) ?? '[]') : []),
|
||||
prepare: (value: string[]) => Encryption.encrypt(JSON.stringify(value)),
|
||||
consume: (value: string) => (value ? JSON.parse(encryption.decrypt(value) ?? '[]') : []),
|
||||
prepare: (value: string[]) => encryption.encrypt(JSON.stringify(value)),
|
||||
})
|
||||
public twoFactorRecoveryCodes?: string[] | null;
|
||||
|
||||
|
@ -72,9 +85,9 @@ export default class User extends BaseModel {
|
|||
// public totp_secret: HasOne<typeof TotpSecret>;
|
||||
|
||||
@beforeSave()
|
||||
public static async hashPassword(user) {
|
||||
public static async hashPassword(user: User) {
|
||||
if (user.$dirty.password) {
|
||||
user.password = await Hash.make(user.password);
|
||||
user.password = await hash.use('laravel').make(user.password);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -109,6 +122,12 @@ export default class User extends BaseModel {
|
|||
}
|
||||
|
||||
private async checkHasPermissions(user: User, permissionNames: Array<string>): Promise<boolean> {
|
||||
const permissionTable = config.get('rolePermission.permission_table', 'permissions');
|
||||
const rolePermissionTable = config.get('rolePermission.role_permission_table', 'role_has_permissions');
|
||||
|
||||
const roleTable = config.get('rolePermission.role_table', 'roles');
|
||||
const userRoleTable = config.get('rolePermission.user_role_table', 'link_accounts_roles');
|
||||
|
||||
let permissionPlaceHolder = '(';
|
||||
let placeholders = new Array(permissionNames.length).fill('?');
|
||||
permissionPlaceHolder += placeholders.join(',');
|
||||
|
@ -118,7 +137,7 @@ export default class User extends BaseModel {
|
|||
rows: {
|
||||
0: { permissioncount },
|
||||
},
|
||||
} = await Database.rawQuery(
|
||||
} = await db.rawQuery(
|
||||
'SELECT count("p"."name") as permissionCount FROM ' +
|
||||
roleTable +
|
||||
' r INNER JOIN ' +
|
||||
|
|
|
@ -1,8 +1,10 @@
|
|||
import { column, BaseModel, belongsTo, BelongsTo, SnakeCaseNamingStrategy } from '@ioc:Adonis/Lucid/Orm';
|
||||
import { column, BaseModel, belongsTo, SnakeCaseNamingStrategy } from '@adonisjs/lucid/orm';
|
||||
|
||||
import User from 'App/Models/User';
|
||||
import Role from 'App/Models/Role';
|
||||
import User from '#app/Models/User';
|
||||
import Role from '#app/Models/Role';
|
||||
import { DateTime } from 'luxon';
|
||||
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
|
||||
|
||||
// import moment from 'moment'
|
||||
|
||||
export default class UserRole extends BaseModel {
|
||||
|
@ -49,7 +51,7 @@ export default class UserRole extends BaseModel {
|
|||
});
|
||||
}
|
||||
|
||||
private static formatDateTime(datetime) {
|
||||
private static formatDateTime(datetime: any) {
|
||||
let value = new Date(datetime);
|
||||
return datetime
|
||||
? value.getFullYear() +
|
||||
|
|
|
@ -1,19 +1,18 @@
|
|||
import Database, {
|
||||
// DatabaseQueryBuilderContract,
|
||||
QueryClientContract,
|
||||
TransactionClientContract,
|
||||
} from '@ioc:Adonis/Lucid/Database';
|
||||
import Config from '@ioc:Adonis/Core/Config';
|
||||
// import db from '@adonisjs/lucid/services/db';
|
||||
// // import Config from '@ioc:Adonis/Core/Config';
|
||||
// import config from '@adonisjs/core/services/config';
|
||||
// import { QueryClientContract } from "@adonisjs/lucid/types/database";
|
||||
// import { TransactionClientContract } from "@adonisjs/lucid/types/database";
|
||||
|
||||
export function getUserRoles(userId: number, trx?: TransactionClientContract): Promise<Array<string>> {
|
||||
const { userRole } = Config.get('acl.joinTables');
|
||||
return ((trx || Database) as QueryClientContract | TransactionClientContract)
|
||||
.query()
|
||||
.from('roles')
|
||||
.distinct('roles.slug')
|
||||
.leftJoin(userRole, `${userRole}.role_id`, 'roles.id')
|
||||
.where(`${userRole}.user_id`, userId)
|
||||
.then((res) => {
|
||||
return res.map((r) => r.slug);
|
||||
});
|
||||
}
|
||||
// export function getUserRoles(userId: number, trx?: TransactionClientContract): Promise<Array<string>> {
|
||||
// const { userRole } = config.get('acl.joinTables');
|
||||
// return ((trx || db) as QueryClientContract | TransactionClientContract)
|
||||
// .query()
|
||||
// .from('roles')
|
||||
// .distinct('roles.slug')
|
||||
// .leftJoin(userRole, `${userRole}.role_id`, 'roles.id')
|
||||
// .where(`${userRole}.user_id`, userId)
|
||||
// .then((res) => {
|
||||
// return res.map((r) => r.slug);
|
||||
// });
|
||||
// }
|
||||
|
|
|
@ -1,10 +1,11 @@
|
|||
import Config from '@ioc:Adonis/Core/Config';
|
||||
import User from 'App/Models/User';
|
||||
import { generateSecret, verifyToken } from 'node-2fa/dist/index';
|
||||
// import Config from '@ioc:Adonis/Core/Config';
|
||||
import config from '@adonisjs/core/services/config'
|
||||
import User from '#app/Models/User';
|
||||
import { generateSecret, verifyToken } from 'node-2fa/dist/index.js';
|
||||
// import cryptoRandomString from 'crypto-random-string';
|
||||
import QRCode from 'qrcode';
|
||||
import crypto from 'crypto';
|
||||
import { TotpState } from 'Contracts/enums';
|
||||
import { TotpState } from '#contracts/enums';
|
||||
|
||||
// npm install node-2fa --save
|
||||
// npm install crypto-random-string --save
|
||||
|
@ -13,7 +14,7 @@ import { TotpState } from 'Contracts/enums';
|
|||
// npm i --save-dev @types/qrcode
|
||||
|
||||
class TwoFactorAuthProvider {
|
||||
private issuer = Config.get('twoFactorAuthConfig.app.name') || 'TethysCloud';
|
||||
private issuer: string = config.get('twoFactorAuthConfig.app.name') || 'TethysCloud';
|
||||
|
||||
/**
|
||||
* generateSecret will generate a user-specific 32-character secret.
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import { schema, rules } from '@adonisjs/validator';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import { CustomMessages } from "@adonisjs/validator/types";
|
||||
|
||||
export default class AuthValidator {
|
||||
constructor(protected ctx: HttpContextContract) {}
|
||||
constructor(protected ctx: HttpContext) {}
|
||||
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
|
|
|
@ -1,10 +1,11 @@
|
|||
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import { schema, rules } from '@adonisjs/validator';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import dayjs from 'dayjs';
|
||||
import { TitleTypes, DescriptionTypes, RelationTypes, ReferenceIdentifierTypes, ContributorTypes } from 'Contracts/enums';
|
||||
import { TitleTypes, DescriptionTypes, RelationTypes, ReferenceIdentifierTypes, ContributorTypes } from '#contracts/enums';
|
||||
import { CustomMessages } from "@adonisjs/validator/types";
|
||||
|
||||
export default class CreateDatasetValidator {
|
||||
constructor(protected ctx: HttpContextContract) {}
|
||||
constructor(protected ctx: HttpContext) {}
|
||||
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
|
@ -104,8 +105,8 @@ export default class CreateDatasetValidator {
|
|||
// }),
|
||||
files: schema.array([rules.minLength(1)]).members(
|
||||
schema.file({
|
||||
size: '100mb',
|
||||
extnames: ['jpg', 'gif', 'png', 'tif', 'pdf'],
|
||||
size: '512mb',
|
||||
extnames: ['jpg', 'gif', 'png', 'tif', 'pdf', 'zip', 'fgb', 'nc', 'qml', 'ovr', 'gpkg', 'gml', 'gpx', 'kml', 'kmz', 'json'],
|
||||
}),
|
||||
),
|
||||
// upload: schema.object().members({
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import { schema, rules } from '@adonisjs/validator';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import { CustomMessages } from "@adonisjs/validator/types";
|
||||
|
||||
export default class CreateRoleValidator {
|
||||
constructor(protected ctx: HttpContextContract) {}
|
||||
constructor(protected ctx: HttpContext) {}
|
||||
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import { schema, rules } from '@adonisjs/validator';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import { CustomMessages } from "@adonisjs/validator/types";
|
||||
|
||||
export default class CreateUserValidator {
|
||||
constructor(protected ctx: HttpContextContract) {}
|
||||
constructor(protected ctx: HttpContext) {}
|
||||
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
|
|
|
@ -1,10 +1,11 @@
|
|||
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import { schema, rules } from '@adonisjs/validator';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import dayjs from 'dayjs';
|
||||
import { TitleTypes, DescriptionTypes, RelationTypes, ReferenceIdentifierTypes, ContributorTypes } from 'Contracts/enums';
|
||||
import { TitleTypes, DescriptionTypes, RelationTypes, ReferenceIdentifierTypes, ContributorTypes } from '#contracts/enums';
|
||||
import { CustomMessages } from "@adonisjs/validator/types";
|
||||
|
||||
export default class UpdateDatasetValidator {
|
||||
constructor(protected ctx: HttpContextContract) {}
|
||||
constructor(protected ctx: HttpContext) {}
|
||||
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
|
|
|
@ -1,12 +1,14 @@
|
|||
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import { schema, rules } from '@adonisjs/validator';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import { CustomMessages } from "@adonisjs/validator/types";
|
||||
|
||||
// import { Request } from '@adonisjs/core/build/standalone';
|
||||
|
||||
export default class UpdateRoleValidator {
|
||||
protected ctx: HttpContextContract;
|
||||
protected ctx: HttpContext;
|
||||
public schema;
|
||||
|
||||
constructor(ctx: HttpContextContract) {
|
||||
constructor(ctx: HttpContext) {
|
||||
this.ctx = ctx;
|
||||
this.schema = this.createSchema();
|
||||
}
|
||||
|
|
|
@ -1,12 +1,14 @@
|
|||
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import { schema, rules } from '@adonisjs/validator';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
import { CustomMessages } from "@adonisjs/validator/types";
|
||||
|
||||
// import { Request } from '@adonisjs/core/build/standalone';
|
||||
|
||||
export default class UpdateUserValidator {
|
||||
protected ctx: HttpContextContract;
|
||||
protected ctx: HttpContext;
|
||||
public schema;
|
||||
|
||||
constructor(ctx: HttpContextContract) {
|
||||
constructor(ctx: HttpContext) {
|
||||
this.ctx = ctx;
|
||||
this.schema = this.createSchema();
|
||||
}
|
||||
|
|
47
bin/console.ts
Normal file
47
bin/console.ts
Normal file
|
@ -0,0 +1,47 @@
|
|||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Ace entry point
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The "console.ts" file is the entrypoint for booting the AdonisJS
|
||||
| command-line framework and executing commands.
|
||||
|
|
||||
| Commands do not boot the application, unless the currently running command
|
||||
| has "options.startApp" flag set to true.
|
||||
|
|
||||
*/
|
||||
|
||||
import 'reflect-metadata'
|
||||
import { Ignitor, prettyPrintError } from '@adonisjs/core'
|
||||
|
||||
/**
|
||||
* URL to the application root. AdonisJS need it to resolve
|
||||
* paths to file and directories for scaffolding commands
|
||||
*/
|
||||
const APP_ROOT = new URL('../', import.meta.url)
|
||||
|
||||
/**
|
||||
* The importer is used to import files in context of the
|
||||
* application.
|
||||
*/
|
||||
const IMPORTER = (filePath: string) => {
|
||||
if (filePath.startsWith('./') || filePath.startsWith('../')) {
|
||||
return import(new URL(filePath, APP_ROOT).href)
|
||||
}
|
||||
return import(filePath)
|
||||
}
|
||||
|
||||
new Ignitor(APP_ROOT, { importer: IMPORTER })
|
||||
.tap((app) => {
|
||||
app.booting(async () => {
|
||||
await import('#start/env')
|
||||
})
|
||||
app.listen('SIGTERM', () => app.terminate())
|
||||
app.listenIf(app.managedByPm2, 'SIGINT', () => app.terminate())
|
||||
})
|
||||
.ace()
|
||||
.handle(process.argv.splice(2))
|
||||
.catch((error) => {
|
||||
process.exitCode = 1
|
||||
prettyPrintError(error)
|
||||
})
|
45
bin/server.ts
Normal file
45
bin/server.ts
Normal file
|
@ -0,0 +1,45 @@
|
|||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| HTTP server entrypoint
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The "server.ts" file is the entrypoint for starting the AdonisJS HTTP
|
||||
| server. Either you can run this file directly or use the "serve"
|
||||
| command to run this file and monitor file changes
|
||||
|
|
||||
*/
|
||||
|
||||
import 'reflect-metadata'
|
||||
import { Ignitor, prettyPrintError } from '@adonisjs/core'
|
||||
|
||||
/**
|
||||
* URL to the application root. AdonisJS need it to resolve
|
||||
* paths to file and directories for scaffolding commands
|
||||
*/
|
||||
const APP_ROOT = new URL('../', import.meta.url)
|
||||
|
||||
/**
|
||||
* The importer is used to import files in context of the
|
||||
* application.
|
||||
*/
|
||||
const IMPORTER = (filePath: string) => {
|
||||
if (filePath.startsWith('./') || filePath.startsWith('../')) {
|
||||
return import(new URL(filePath, APP_ROOT).href)
|
||||
}
|
||||
return import(filePath)
|
||||
}
|
||||
|
||||
new Ignitor(APP_ROOT, { importer: IMPORTER })
|
||||
.tap((app) => {
|
||||
app.booting(async () => {
|
||||
await import('#start/env')
|
||||
})
|
||||
app.listen('SIGTERM', () => app.terminate())
|
||||
app.listenIf(app.managedByPm2, 'SIGINT', () => app.terminate())
|
||||
})
|
||||
.httpServer()
|
||||
.start()
|
||||
.catch((error) => {
|
||||
process.exitCode = 1
|
||||
prettyPrintError(error)
|
||||
})
|
62
bin/test.ts
Normal file
62
bin/test.ts
Normal file
|
@ -0,0 +1,62 @@
|
|||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Test runner entrypoint
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The "test.ts" file is the entrypoint for running tests using Japa.
|
||||
|
|
||||
| Either you can run this file directly or use the "test"
|
||||
| command to run this file and monitor file changes.
|
||||
|
|
||||
*/
|
||||
|
||||
process.env.NODE_ENV = 'test'
|
||||
|
||||
import 'reflect-metadata'
|
||||
import { Ignitor, prettyPrintError } from '@adonisjs/core'
|
||||
import { configure, processCLIArgs, run } from '@japa/runner'
|
||||
|
||||
/**
|
||||
* URL to the application root. AdonisJS need it to resolve
|
||||
* paths to file and directories for scaffolding commands
|
||||
*/
|
||||
const APP_ROOT = new URL('../', import.meta.url)
|
||||
|
||||
/**
|
||||
* The importer is used to import files in context of the
|
||||
* application.
|
||||
*/
|
||||
const IMPORTER = (filePath: string) => {
|
||||
if (filePath.startsWith('./') || filePath.startsWith('../')) {
|
||||
return import(new URL(filePath, APP_ROOT).href)
|
||||
}
|
||||
return import(filePath)
|
||||
}
|
||||
|
||||
new Ignitor(APP_ROOT, { importer: IMPORTER })
|
||||
.tap((app) => {
|
||||
app.booting(async () => {
|
||||
await import('#start/env')
|
||||
})
|
||||
app.listen('SIGTERM', () => app.terminate())
|
||||
app.listenIf(app.managedByPm2, 'SIGINT', () => app.terminate())
|
||||
})
|
||||
.testRunner()
|
||||
.configure(async (app) => {
|
||||
const { runnerHooks, ...config } = await import('../tests/bootstrap.js')
|
||||
|
||||
processCLIArgs(process.argv.splice(2))
|
||||
configure({
|
||||
...app.rcFile.tests,
|
||||
...config,
|
||||
...{
|
||||
setup: runnerHooks.setup,
|
||||
teardown: runnerHooks.teardown.concat([() => app.terminate()]),
|
||||
},
|
||||
})
|
||||
})
|
||||
.run(() => run())
|
||||
.catch((error) => {
|
||||
process.exitCode = 1
|
||||
prettyPrintError(error)
|
||||
})
|
|
@ -1,44 +1,34 @@
|
|||
import { BaseCommand, flags } from '@adonisjs/core/build/standalone';
|
||||
// import Logger from '@ioc:Adonis/Core/Logger';
|
||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces';
|
||||
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
|
||||
import { create } from 'xmlbuilder2';
|
||||
import Dataset from 'App/Models/Dataset';
|
||||
import XmlModel from 'App/Library/XmlModel';
|
||||
import Dataset from '#app/Models/Dataset';
|
||||
import XmlModel from '#app/Library/XmlModel';
|
||||
import { readFileSync } from 'fs';
|
||||
import { transform } from 'saxon-js';
|
||||
import SaxonJS from 'saxon-js';
|
||||
import { Client } from '@opensearch-project/opensearch';
|
||||
import { getDomain } from 'App/Utils/utility-functions';
|
||||
import { getDomain } from '#app/Utils/utility-functions';
|
||||
import { BaseCommand, flags } from '@adonisjs/core/ace';
|
||||
import { CommandOptions } from '@adonisjs/core/types/ace';
|
||||
|
||||
const opensearchNode = process.env.OPENSEARCH_HOST || 'localhost';
|
||||
const client = new Client({ node: `http://${opensearchNode}` }); // replace with your OpenSearch endpoint
|
||||
|
||||
export default class IndexDatasets extends BaseCommand {
|
||||
public static commandName = 'index:datasets';
|
||||
public static description = 'Index datasets based on publish_id';
|
||||
static commandName = 'index:datasets';
|
||||
static description = 'Index datasets based on publish_id';
|
||||
|
||||
@flags.number({ alias: 'p' })
|
||||
public publish_id: number;
|
||||
|
||||
public static settings = {
|
||||
/**
|
||||
* Set the following value to true, if you want to load the application
|
||||
* before running the command. Don't forget to call `node ace generate:manifest`
|
||||
* afterwards.
|
||||
*/
|
||||
static options: CommandOptions = {
|
||||
loadApp: true,
|
||||
|
||||
/**
|
||||
* Set the following value to true, if you want this command to keep running until
|
||||
* you manually decide to exit the process. Don't forget to call
|
||||
* `node ace generate:manifest` afterwards.
|
||||
*/
|
||||
stayAlive: false,
|
||||
staysAlive: false,
|
||||
};
|
||||
|
||||
public async run() {
|
||||
async run() {
|
||||
this.logger.info('Hello world!');
|
||||
// const { default: Dataset } = await import('App/Models/Dataset');
|
||||
const datasets = await this.getDatasets();
|
||||
const { default: Dataset } = await import('#app/Models/Dataset');
|
||||
const datasets = await Dataset.query().where('server_state', 'published').exec(); //this.getDatasets();
|
||||
const proc = readFileSync('public/assets2/solr.sef.json');
|
||||
const index_name = 'tethys-records';
|
||||
|
||||
|
@ -50,13 +40,15 @@ export default class IndexDatasets extends BaseCommand {
|
|||
}
|
||||
}
|
||||
|
||||
private async getDatasets(): Promise<Dataset[]> {
|
||||
const query = Dataset.query().preload('xmlCache').where('server_state', 'published');
|
||||
if (this.publish_id) {
|
||||
query.where('publish_id', this.publish_id);
|
||||
}
|
||||
return await query;
|
||||
}
|
||||
// private async getDatasets(): Promise<any[]> {
|
||||
// // const { default: Dataset } = await import('#app/Models/Dataset');
|
||||
// // const Dataset = (await import('#app/Models/Dataset')).default
|
||||
// const query = Dataset.query().where('server_state', 'published');
|
||||
// if (this.publish_id) {
|
||||
// query.where('publish_id', this.publish_id);
|
||||
// }
|
||||
// return await query;
|
||||
// }
|
||||
|
||||
private async indexDocument(dataset: Dataset, index_name: string, proc: Buffer): Promise<void> {
|
||||
try {
|
||||
|
@ -75,14 +67,14 @@ export default class IndexDatasets extends BaseCommand {
|
|||
}
|
||||
}
|
||||
|
||||
private async getJsonString(dataset, proc) {
|
||||
private async getJsonString(dataset: Dataset, proc: Buffer) {
|
||||
let xml = create({ version: '1.0', encoding: 'UTF-8', standalone: true }, '<root></root>');
|
||||
const datasetNode = xml.root().ele('Dataset');
|
||||
await this.createXmlRecord(dataset, datasetNode);
|
||||
const xmlString = xml.end({ prettyPrint: false });
|
||||
|
||||
try {
|
||||
const result = await transform({
|
||||
const result = await SaxonJS.transform({
|
||||
stylesheetText: proc,
|
||||
destination: 'serialized',
|
||||
sourceText: xmlString,
|
||||
|
|
|
@ -1,8 +1,9 @@
|
|||
import { BaseCommand } from '@adonisjs/core/build/standalone';
|
||||
import crypto from 'crypto';
|
||||
import fs from 'fs';
|
||||
// import Config from '@ioc:Adonis/Core/Config';
|
||||
import Logger from '@ioc:Adonis/Core/Logger';
|
||||
import logger from '@adonisjs/core/services/logger';
|
||||
import { BaseCommand } from "@adonisjs/core/ace";
|
||||
import { CommandOptions } from "@adonisjs/core/types/ace";
|
||||
|
||||
export default class ValidateChecksum extends BaseCommand {
|
||||
/**
|
||||
|
@ -14,26 +15,14 @@ export default class ValidateChecksum extends BaseCommand {
|
|||
* Command description is displayed in the "help" output
|
||||
*/
|
||||
public static description = '';
|
||||
|
||||
public static settings = {
|
||||
/**
|
||||
* Set the following value to true, if you want to load the application
|
||||
* before running the command. Don't forget to call `node ace generate:manifest`
|
||||
* afterwards.
|
||||
*/
|
||||
loadApp: true,
|
||||
|
||||
/**
|
||||
* Set the following value to true, if you want this command to keep running until
|
||||
* you manually decide to exit the process. Don't forget to call
|
||||
* `node ace generate:manifest` afterwards.
|
||||
*/
|
||||
stayAlive: false,
|
||||
};
|
||||
static options: CommandOptions = {
|
||||
loadApp: true,
|
||||
staysAlive: false,
|
||||
};
|
||||
|
||||
public async run() {
|
||||
// this.logger.info('Hello world!')
|
||||
const { default: File } = await import('App/Models/File');
|
||||
const { default: File } = await import('#app/Models/File');
|
||||
// const { default: HashValue } = await (await (import ('App/Models/HashValue')));
|
||||
|
||||
// query all published files from database:
|
||||
|
@ -55,21 +44,21 @@ export default class ValidateChecksum extends BaseCommand {
|
|||
calculatedMd5FileHash = await this.checksumFile(filePath, 'md5');
|
||||
} catch (exception) {
|
||||
// this.logger.error(exception.message);
|
||||
Logger.error(exception.message);
|
||||
logger.error(exception.message);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (hashValue['md5'] === calculatedMd5FileHash) {
|
||||
Logger.info(`File id ${file.id} OK: stored md5 checksum: ${calculatedMd5FileHash}, same control md5 checksum: ${hashValue['md5']}`);
|
||||
logger.info(`File id ${file.id} OK: stored md5 checksum: ${calculatedMd5FileHash}, same control md5 checksum: ${hashValue['md5']}`);
|
||||
} else {
|
||||
Logger.error(
|
||||
logger.error(
|
||||
`File id ${file.id}: stored md5 checksum: ${calculatedMd5FileHash}, control md5 checksum: ${hashValue['md5']}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async checksumFile(path, hashName = 'md5'): Promise<string> {
|
||||
private async checksumFile(path: string, hashName = 'md5'): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const hash = crypto.createHash(hashName);
|
||||
const stream = fs.createReadStream(path);
|
||||
|
|
|
@ -1,19 +0,0 @@
|
|||
import { listDirectoryFiles } from '@adonisjs/core/build/standalone';
|
||||
import Application from '@ioc:Adonis/Core/Application';
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Exporting an array of commands
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Instead of manually exporting each file from this directory, we use the
|
||||
| helper `listDirectoryFiles` to recursively collect and export an array
|
||||
| of filenames.
|
||||
|
|
||||
| Couple of things to note:
|
||||
|
|
||||
| 1. The file path must be relative from the project root and not this directory.
|
||||
| 2. We must ignore this file to avoid getting into an infinite loop
|
||||
|
|
||||
*/
|
||||
export default listDirectoryFiles(__dirname, Application.appRoot, ['./commands/index']);
|
13
commands/index_test.ts
Normal file
13
commands/index_test.ts
Normal file
|
@ -0,0 +1,13 @@
|
|||
import { BaseCommand } from '@adonisjs/core/ace'
|
||||
import type { CommandOptions } from '@adonisjs/core/types/ace'
|
||||
|
||||
export default class IndexTest extends BaseCommand {
|
||||
static commandName = 'index:test'
|
||||
static description = ''
|
||||
|
||||
static options: CommandOptions = {}
|
||||
|
||||
async run() {
|
||||
this.logger.info('Hello world from "IndexTest"')
|
||||
}
|
||||
}
|
365
config/app.ts
365
config/app.ts
|
@ -6,13 +6,14 @@
|
|||
*/
|
||||
|
||||
import proxyAddr from 'proxy-addr';
|
||||
import Env from '@ioc:Adonis/Core/Env';
|
||||
import Application from '@ioc:Adonis/Core/Application';
|
||||
import type { ServerConfig } from '@ioc:Adonis/Core/Server';
|
||||
import type { LoggerConfig } from '@ioc:Adonis/Core/Logger';
|
||||
import type { ProfilerConfig } from '@ioc:Adonis/Core/Profiler';
|
||||
import type { ValidatorConfig } from '@ioc:Adonis/Core/Validator';
|
||||
import type { AssetsManagerConfig } from '@ioc:Adonis/Core/AssetsManager';
|
||||
import env from '#start/env';
|
||||
// import app from '@adonisjs/core/services/app';
|
||||
// import type { ProfilerConfig } from '@ioc:Adonis/Core/Profiler';
|
||||
// import type { AssetsManagerConfig } from '@ioc:Adonis/Core/AssetsManager';
|
||||
// import { ServerConfig } from "@adonisjs/core/services/server";
|
||||
// import { LoggerConfig } from "@adonisjs/core/types/logger";
|
||||
import { ValidatorConfig } from "@adonisjs/validator/types";
|
||||
import { defineConfig } from "@adonisjs/core/http";
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -27,7 +28,7 @@ import type { AssetsManagerConfig } from '@ioc:Adonis/Core/AssetsManager';
|
|||
| be decrypted.
|
||||
|
|
||||
*/
|
||||
export const appKey: string = Env.get('APP_KEY');
|
||||
export const appKey: string = env.get('APP_KEY');
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -38,176 +39,120 @@ export const appKey: string = Env.get('APP_KEY');
|
|||
| the config properties to make keep server secure.
|
||||
|
|
||||
*/
|
||||
export const http: ServerConfig = {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Allow method spoofing
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Method spoofing enables defining custom HTTP methods using a query string
|
||||
| `_method`. This is usually required when you are making traditional
|
||||
| form requests and wants to use HTTP verbs like `PUT`, `DELETE` and
|
||||
| so on.
|
||||
|
|
||||
*/
|
||||
allowMethodSpoofing: false,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Subdomain offset
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
subdomainOffset: 2,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Request Ids
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Setting this value to `true` will generate a unique request id for each
|
||||
| HTTP request and set it as `x-request-id` header.
|
||||
|
|
||||
*/
|
||||
generateRequestId: false,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Trusting proxy servers
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Define the proxy servers that AdonisJs must trust for reading `X-Forwarded`
|
||||
| headers.
|
||||
|
|
||||
*/
|
||||
trustProxy: proxyAddr.compile('loopback'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Generating Etag
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Whether or not to generate an etag for every response.
|
||||
|
|
||||
*/
|
||||
etag: false,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| JSONP Callback
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
jsonpCallbackName: 'callback',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Cookie settings
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
cookie: {
|
||||
domain: '',
|
||||
path: '/',
|
||||
maxAge: '2h',
|
||||
httpOnly: true,
|
||||
secure: false,
|
||||
sameSite: false,
|
||||
},
|
||||
};
|
||||
|
||||
/*
|
||||
export const http = defineConfig({
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Logger
|
||||
| Allow method spoofing
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Method spoofing enables defining custom HTTP methods using a query string
|
||||
| `_method`. This is usually required when you are making traditional
|
||||
| form requests and wants to use HTTP verbs like `PUT`, `DELETE` and
|
||||
| so on.
|
||||
|
|
||||
*/
|
||||
allowMethodSpoofing: false,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Subdomain offset
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
export const logger: LoggerConfig = {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Application name
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The name of the application you want to add to the log. It is recommended
|
||||
| to always have app name in every log line.
|
||||
|
|
||||
| The `APP_NAME` environment variable is automatically set by AdonisJS by
|
||||
| reading the `name` property from the `package.json` file.
|
||||
|
|
||||
*/
|
||||
name: Env.get('APP_NAME'),
|
||||
subdomainOffset: 2,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Toggle logger
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Enable or disable logger application wide
|
||||
|
|
||||
*/
|
||||
enabled: true,
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Request Ids
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Setting this value to `true` will generate a unique request id for each
|
||||
| HTTP request and set it as `x-request-id` header.
|
||||
|
|
||||
*/
|
||||
generateRequestId: false,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Logging level
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The level from which you want the logger to flush logs. It is recommended
|
||||
| to make use of the environment variable, so that you can define log levels
|
||||
| at deployment level and not code level.
|
||||
|
|
||||
*/
|
||||
level: Env.get('LOG_LEVEL', 'info'),
|
||||
redact: {
|
||||
paths: ['password', '*.password'],
|
||||
},
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Trusting proxy servers
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Define the proxy servers that AdonisJs must trust for reading `X-Forwarded`
|
||||
| headers.
|
||||
|
|
||||
*/
|
||||
trustProxy: proxyAddr.compile('loopback'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Generating Etag
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Whether or not to generate an etag for every response.
|
||||
|
|
||||
*/
|
||||
etag: false,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| JSONP Callback
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
jsonpCallbackName: 'callback',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Cookie settings
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
cookie: {
|
||||
domain: '',
|
||||
path: '/',
|
||||
maxAge: '2h',
|
||||
httpOnly: true,
|
||||
secure: false,
|
||||
sameSite: false,
|
||||
},
|
||||
});
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Pretty print
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| It is highly advised NOT to use `prettyPrint` in production, since it
|
||||
| can have huge impact on performance.
|
||||
|
|
||||
*/
|
||||
prettyPrint: Env.get('NODE_ENV') === 'development',
|
||||
};
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Profiler
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
export const profiler: ProfilerConfig = {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Toggle profiler
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Enable or disable profiler
|
||||
|
|
||||
*/
|
||||
enabled: true,
|
||||
// export const profiler: ProfilerConfig = {
|
||||
// /*
|
||||
// |--------------------------------------------------------------------------
|
||||
// | Toggle profiler
|
||||
// |--------------------------------------------------------------------------
|
||||
// |
|
||||
// | Enable or disable profiler
|
||||
// |
|
||||
// */
|
||||
// enabled: true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Blacklist actions/row labels
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Define an array of actions or row labels that you want to disable from
|
||||
| getting profiled.
|
||||
|
|
||||
*/
|
||||
blacklist: [],
|
||||
// /*
|
||||
// |--------------------------------------------------------------------------
|
||||
// | Blacklist actions/row labels
|
||||
// |--------------------------------------------------------------------------
|
||||
// |
|
||||
// | Define an array of actions or row labels that you want to disable from
|
||||
// | getting profiled.
|
||||
// |
|
||||
// */
|
||||
// blacklist: [],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Whitelist actions/row labels
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Define an array of actions or row labels that you want to whitelist for
|
||||
| the profiler. When whitelist is defined, then `blacklist` is ignored.
|
||||
|
|
||||
*/
|
||||
whitelist: [],
|
||||
};
|
||||
// /*
|
||||
// |--------------------------------------------------------------------------
|
||||
// | Whitelist actions/row labels
|
||||
// |--------------------------------------------------------------------------
|
||||
// |
|
||||
// | Define an array of actions or row labels that you want to whitelist for
|
||||
// | the profiler. When whitelist is defined, then `blacklist` is ignored.
|
||||
// |
|
||||
// */
|
||||
// whitelist: [],
|
||||
// };
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -228,52 +173,52 @@ export const validator: ValidatorConfig = {};
|
|||
| Configure the asset manager you are using to compile the frontend assets
|
||||
|
|
||||
*/
|
||||
export const assets: AssetsManagerConfig = {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Driver
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Currently we only support webpack encore and may introduce more drivers
|
||||
| in the future
|
||||
|
|
||||
*/
|
||||
driver: Env.get('ASSETS_DRIVER'),
|
||||
// export const assets: AssetsManagerConfig = {
|
||||
// /*
|
||||
// |--------------------------------------------------------------------------
|
||||
// | Driver
|
||||
// |--------------------------------------------------------------------------
|
||||
// |
|
||||
// | Currently we only support webpack encore and may introduce more drivers
|
||||
// | in the future
|
||||
// |
|
||||
// */
|
||||
// driver: env.get('ASSETS_DRIVER'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Public path
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Directory to search for the "manifest.json" and the "entrypoints.json"
|
||||
| files
|
||||
|
|
||||
*/
|
||||
publicPath: Application.publicPath('assets'),
|
||||
// /*
|
||||
// |--------------------------------------------------------------------------
|
||||
// | Public path
|
||||
// |--------------------------------------------------------------------------
|
||||
// |
|
||||
// | Directory to search for the "manifest.json" and the "entrypoints.json"
|
||||
// | files
|
||||
// |
|
||||
// */
|
||||
// publicPath: app.publicPath('assets'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Script tag
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Define attributes for the entryPointScripts tags
|
||||
|
|
||||
*/
|
||||
script: {
|
||||
attributes: {
|
||||
defer: true,
|
||||
},
|
||||
},
|
||||
// /*
|
||||
// |--------------------------------------------------------------------------
|
||||
// | Script tag
|
||||
// |--------------------------------------------------------------------------
|
||||
// |
|
||||
// | Define attributes for the entryPointScripts tags
|
||||
// |
|
||||
// */
|
||||
// script: {
|
||||
// attributes: {
|
||||
// defer: true,
|
||||
// },
|
||||
// },
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Style tag
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Define attributes for the entryPointStyles tags
|
||||
|
|
||||
*/
|
||||
style: {
|
||||
attributes: {},
|
||||
},
|
||||
};
|
||||
// /*
|
||||
// |--------------------------------------------------------------------------
|
||||
// | Style tag
|
||||
// |--------------------------------------------------------------------------
|
||||
// |
|
||||
// | Define attributes for the entryPointStyles tags
|
||||
// |
|
||||
// */
|
||||
// style: {
|
||||
// attributes: {},
|
||||
// },
|
||||
// };
|
||||
|
|
163
config/auth.ts
163
config/auth.ts
|
@ -1,86 +1,89 @@
|
|||
/**
|
||||
* Config source: https://git.io/JY0mp
|
||||
*
|
||||
* Feel free to let us know via PR, if you find something broken in this config
|
||||
* file.
|
||||
*/
|
||||
import { defineConfig } from '@adonisjs/auth';
|
||||
import { Authenticators } from '@adonisjs/auth/types';
|
||||
import { sessionGuard, sessionUserProvider } from '@adonisjs/auth/session';
|
||||
// import User from '#app/Models/User';
|
||||
// import { SessionLucidUserProviderOptions } from '@adonisjs/auth/types/session';
|
||||
import { Authenticator } from '@adonisjs/auth';
|
||||
import { GuardFactory } from '@adonisjs/auth/types';
|
||||
|
||||
import type { AuthConfig } from '@ioc:Adonis/Addons/Auth';
|
||||
// export declare function sessionUserProvider<Model extends LucidAuthenticatable>(config: SessionLucidUserProviderOptions<Model>): SessionLucidUserProvider<Model>;
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Authentication Mapping
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| List of available authentication mapping. You must first define them
|
||||
| inside the `contracts/auth.ts` file before mentioning them here.
|
||||
|
|
||||
*/
|
||||
const authConfig: AuthConfig = {
|
||||
guard: 'web',
|
||||
const authConfig = defineConfig({
|
||||
default: 'web',
|
||||
guards: {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Web Guard
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Web guard uses classic old school sessions for authenticating users.
|
||||
| If you are building a standard web application, it is recommended to
|
||||
| use web guard with session driver
|
||||
|
|
||||
*/
|
||||
web: {
|
||||
driver: 'session',
|
||||
|
||||
provider: {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Driver
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Name of the driver
|
||||
|
|
||||
*/
|
||||
driver: 'lucid',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Identifier key
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The identifier key is the unique key on the model. In most cases specifying
|
||||
| the primary key is the right choice.
|
||||
|
|
||||
*/
|
||||
identifierKey: 'id',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Uids
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Uids are used to search a user against one of the mentioned columns. During
|
||||
| login, the auth module will search the user mentioned value against one
|
||||
| of the mentioned columns to find their user record.
|
||||
|
|
||||
*/
|
||||
uids: ['email'],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Model
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The model to use for fetching or finding users. The model is imported
|
||||
| lazily since the config files are read way earlier in the lifecycle
|
||||
| of booting the app and the models may not be in a usable state at
|
||||
| that time.
|
||||
|
|
||||
*/
|
||||
model: () => import('App/Models/User'),
|
||||
},
|
||||
},
|
||||
web: sessionGuard({
|
||||
useRememberMeTokens: false,
|
||||
provider: sessionUserProvider({
|
||||
model: () => import('#app/Models/User'),
|
||||
}),
|
||||
}),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export default authConfig;
|
||||
|
||||
/**
|
||||
* Inferring types from the configured auth
|
||||
* guards.
|
||||
*/
|
||||
declare module '@adonisjs/auth/types' {
|
||||
// export type InferAuthenticators<
|
||||
// Config extends ConfigProvider<{
|
||||
// default: unknown;
|
||||
// guards: unknown;
|
||||
// }>,
|
||||
// > = Awaited<ReturnType<Config['resolver']>>['guards'];
|
||||
// interface ProvidersList {
|
||||
// /*
|
||||
// |--------------------------------------------------------------------------
|
||||
// | User Provider
|
||||
// |--------------------------------------------------------------------------
|
||||
// |
|
||||
// | The following provider uses Lucid models as a driver for fetching user
|
||||
// | details from the database for authentication.
|
||||
// |
|
||||
// | You can create multiple providers using the same underlying driver with
|
||||
// | different Lucid models.
|
||||
// |
|
||||
// */
|
||||
// // user: {
|
||||
// // implementation: SessionLucidUserProvider<typeof User>;
|
||||
// // config: LucidProviderConfig<typeof User>;
|
||||
// // };
|
||||
// user: {
|
||||
// implementation: SessionLucidUserProvider<typeof User>;
|
||||
// config: SessionLucidUserProviderOptions<typeof User>;
|
||||
// };
|
||||
// }
|
||||
|
||||
interface Authenticators extends InferAuthenticators<typeof authConfig> {}
|
||||
|
||||
// const PROVIDER_REAL_USER: unique symbol;
|
||||
// export type SessionGuardUser<RealUser> = {
|
||||
// getId(): string | number | BigInt;
|
||||
// getOriginal(): RealUser;
|
||||
// };
|
||||
|
||||
// export interface SessionUserProviderContract<User> {
|
||||
// [PROVIDER_REAL_USER]: User;
|
||||
// /**
|
||||
// * Create a user object that acts as an adapter between
|
||||
// * the guard and real user value.
|
||||
// */
|
||||
// createUserForGuard(user: User): Promise<SessionGuardUser<User>>;
|
||||
// /**
|
||||
// * Find a user by their id.
|
||||
// */
|
||||
// findById(identifier: string | number | BigInt): Promise<SessionGuardUser<User> | null>;
|
||||
// }
|
||||
}
|
||||
|
||||
// declare module '@adonisjs/core/types' {
|
||||
// interface EventsList extends InferAuthEvents<Authenticators> {}
|
||||
// }
|
||||
|
||||
declare module '@adonisjs/core/http' {
|
||||
interface HttpContext {
|
||||
auth: Authenticator<Authenticators extends Record<string, GuardFactory> ? Authenticators : never>;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,29 +5,31 @@
|
|||
* file.
|
||||
*/
|
||||
|
||||
import type { BodyParserConfig } from '@ioc:Adonis/Core/BodyParser';
|
||||
// import type { BodyParserConfig } from '@adonisjs/core/bodyparser';
|
||||
import env from '#start/env';
|
||||
import { defineConfig } from '@adonisjs/core/bodyparser';
|
||||
|
||||
const bodyParserConfig: BodyParserConfig = {
|
||||
const bodyParserConfig = defineConfig({
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| White listed methods
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| HTTP methods for which body parsing must be performed. It is a good practice
|
||||
| to avoid body parsing for `GET` requests.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| White listed methods
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| HTTP methods for which body parsing must be performed. It is a good practice
|
||||
| to avoid body parsing for `GET` requests.
|
||||
|
|
||||
*/
|
||||
whitelistedMethods: ['POST', 'PUT', 'PATCH', 'DELETE'],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| JSON parser settings
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The settings for the JSON parser. The types defines the request content
|
||||
| types which gets processed by the JSON parser.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| JSON parser settings
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The settings for the JSON parser. The types defines the request content
|
||||
| types which gets processed by the JSON parser.
|
||||
|
|
||||
*/
|
||||
json: {
|
||||
encoding: 'utf-8',
|
||||
limit: '1mb',
|
||||
|
@ -36,165 +38,166 @@ const bodyParserConfig: BodyParserConfig = {
|
|||
},
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Form parser settings
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The settings for the `application/x-www-form-urlencoded` parser. The types
|
||||
| defines the request content types which gets processed by the form parser.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Form parser settings
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The settings for the `application/x-www-form-urlencoded` parser. The types
|
||||
| defines the request content types which gets processed by the form parser.
|
||||
|
|
||||
*/
|
||||
form: {
|
||||
encoding: 'utf-8',
|
||||
limit: '1mb',
|
||||
queryString: {},
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Convert empty strings to null
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Convert empty form fields to null. HTML forms results in field string
|
||||
| value when the field is left blank. This option normalizes all the blank
|
||||
| field values to "null"
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Convert empty strings to null
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Convert empty form fields to null. HTML forms results in field string
|
||||
| value when the field is left blank. This option normalizes all the blank
|
||||
| field values to "null"
|
||||
|
|
||||
*/
|
||||
convertEmptyStringsToNull: true,
|
||||
|
||||
types: ['application/x-www-form-urlencoded'],
|
||||
},
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Raw body parser settings
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Raw body just reads the request body stream as a plain text, which you
|
||||
| can process by hand. This must be used when request body type is not
|
||||
| supported by the body parser.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Raw body parser settings
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Raw body just reads the request body stream as a plain text, which you
|
||||
| can process by hand. This must be used when request body type is not
|
||||
| supported by the body parser.
|
||||
|
|
||||
*/
|
||||
raw: {
|
||||
encoding: 'utf-8',
|
||||
limit: '1mb',
|
||||
queryString: {},
|
||||
// queryString: {},
|
||||
types: ['text/*'],
|
||||
},
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Multipart parser settings
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The settings for the `multipart/form-data` parser. The types defines the
|
||||
| request content types which gets processed by the form parser.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Multipart parser settings
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The settings for the `multipart/form-data` parser. The types defines the
|
||||
| request content types which gets processed by the form parser.
|
||||
|
|
||||
*/
|
||||
multipart: {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Auto process
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The auto process option will process uploaded files and writes them to
|
||||
| the `tmp` folder. You can turn it off and then manually use the stream
|
||||
| to pipe stream to a different destination.
|
||||
|
|
||||
| It is recommended to keep `autoProcess=true`. Unless you are processing bigger
|
||||
| file sizes.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Auto process
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The auto process option will process uploaded files and writes them to
|
||||
| the `tmp` folder. You can turn it off and then manually use the stream
|
||||
| to pipe stream to a different destination.
|
||||
|
|
||||
| It is recommended to keep `autoProcess=true`. Unless you are processing bigger
|
||||
| file sizes.
|
||||
|
|
||||
*/
|
||||
autoProcess: true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Files to be processed manually
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| You can turn off `autoProcess` for certain routes by defining
|
||||
| routes inside the following array.
|
||||
|
|
||||
| NOTE: Make sure the route pattern starts with a leading slash.
|
||||
|
|
||||
| Correct
|
||||
| ```js
|
||||
| /projects/:id/file
|
||||
| ```
|
||||
|
|
||||
| Incorrect
|
||||
| ```js
|
||||
| projects/:id/file
|
||||
| ```
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Files to be processed manually
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| You can turn off `autoProcess` for certain routes by defining
|
||||
| routes inside the following array.
|
||||
|
|
||||
| NOTE: Make sure the route pattern starts with a leading slash.
|
||||
|
|
||||
| Correct
|
||||
| ```js
|
||||
| /projects/:id/file
|
||||
| ```
|
||||
|
|
||||
| Incorrect
|
||||
| ```js
|
||||
| projects/:id/file
|
||||
| ```
|
||||
*/
|
||||
processManually: [],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Temporary file name
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When auto processing is on. We will use this method to compute the temporary
|
||||
| file name. AdonisJs will compute a unique `tmpPath` for you automatically,
|
||||
| However, you can also define your own custom method.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Temporary file name
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| When auto processing is on. We will use this method to compute the temporary
|
||||
| file name. AdonisJs will compute a unique `tmpPath` for you automatically,
|
||||
| However, you can also define your own custom method.
|
||||
|
|
||||
*/
|
||||
// tmpFileName () {
|
||||
// },
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Encoding
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Request body encoding
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Encoding
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Request body encoding
|
||||
|
|
||||
*/
|
||||
encoding: 'utf-8',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Convert empty strings to null
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Convert empty form fields to null. HTML forms results in field string
|
||||
| value when the field is left blank. This option normalizes all the blank
|
||||
| field values to "null"
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Convert empty strings to null
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Convert empty form fields to null. HTML forms results in field string
|
||||
| value when the field is left blank. This option normalizes all the blank
|
||||
| field values to "null"
|
||||
|
|
||||
*/
|
||||
convertEmptyStringsToNull: true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Max Fields
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The maximum number of fields allowed in the request body. The field includes
|
||||
| text inputs and files both.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Max Fields
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The maximum number of fields allowed in the request body. The field includes
|
||||
| text inputs and files both.
|
||||
|
|
||||
*/
|
||||
maxFields: 1000,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Request body limit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The total limit to the multipart body. This includes all request files
|
||||
| and fields data.
|
||||
|
|
||||
*/
|
||||
limit: '20mb',
|
||||
|--------------------------------------------------------------------------
|
||||
| Request body limit
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The total limit to the multipart body. This includes all request files
|
||||
| and fields data.
|
||||
|
|
||||
*/
|
||||
// limit: '20mb',
|
||||
limit: env.get('UPLOAD_LIMIT', '513mb'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Types
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The types that will be considered and parsed as multipart body.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Types
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The types that will be considered and parsed as multipart body.
|
||||
|
|
||||
*/
|
||||
types: ['multipart/form-data'],
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export default bodyParserConfig;
|
||||
|
|
227
config/cors.ts
227
config/cors.ts
|
@ -1,127 +1,120 @@
|
|||
/**
|
||||
* Config source: https://git.io/JfefC
|
||||
*
|
||||
* Feel free to let us know via PR, if you find something broken in this config
|
||||
* file.
|
||||
*/
|
||||
import { defineConfig } from "@adonisjs/cors";
|
||||
|
||||
import type { CorsConfig } from '@ioc:Adonis/Core/Cors';
|
||||
const corsConfig = defineConfig({
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Enabled
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| A boolean to enable or disable CORS integration from your AdonisJs
|
||||
| application.
|
||||
|
|
||||
| Setting the value to `true` will enable the CORS for all HTTP request. However,
|
||||
| you can define a function to enable/disable it on per request basis as well.
|
||||
|
|
||||
*/
|
||||
enabled: false,
|
||||
|
||||
const corsConfig: CorsConfig = {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Enabled
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| A boolean to enable or disable CORS integration from your AdonisJs
|
||||
| application.
|
||||
|
|
||||
| Setting the value to `true` will enable the CORS for all HTTP request. However,
|
||||
| you can define a function to enable/disable it on per request basis as well.
|
||||
|
|
||||
*/
|
||||
enabled: false,
|
||||
// You can also use a function that return true or false.
|
||||
// enabled: (request) => request.url().startsWith('/api')
|
||||
|
||||
// You can also use a function that return true or false.
|
||||
// enabled: (request) => request.url().startsWith('/api')
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Origin
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Set a list of origins to be allowed for `Access-Control-Allow-Origin`.
|
||||
| The value can be one of the following:
|
||||
|
|
||||
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
|
||||
|
|
||||
| Boolean (true) - Allow current request origin.
|
||||
| Boolean (false) - Disallow all.
|
||||
| String - Comma separated list of allowed origins.
|
||||
| Array - An array of allowed origins.
|
||||
| String (*) - A wildcard (*) to allow all request origins.
|
||||
| Function - Receives the current origin string and should return
|
||||
| one of the above values.
|
||||
|
|
||||
*/
|
||||
origin: true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Origin
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Set a list of origins to be allowed for `Access-Control-Allow-Origin`.
|
||||
| The value can be one of the following:
|
||||
|
|
||||
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
|
||||
|
|
||||
| Boolean (true) - Allow current request origin.
|
||||
| Boolean (false) - Disallow all.
|
||||
| String - Comma separated list of allowed origins.
|
||||
| Array - An array of allowed origins.
|
||||
| String (*) - A wildcard (*) to allow all request origins.
|
||||
| Function - Receives the current origin string and should return
|
||||
| one of the above values.
|
||||
|
|
||||
*/
|
||||
origin: true,
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Methods
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| An array of allowed HTTP methods for CORS. The `Access-Control-Request-Method`
|
||||
| is checked against the following list.
|
||||
|
|
||||
| Following is the list of default methods. Feel free to add more.
|
||||
*/
|
||||
methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Methods
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| An array of allowed HTTP methods for CORS. The `Access-Control-Request-Method`
|
||||
| is checked against the following list.
|
||||
|
|
||||
| Following is the list of default methods. Feel free to add more.
|
||||
*/
|
||||
methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Headers
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| List of headers to be allowed for `Access-Control-Allow-Headers` header.
|
||||
| The value can be one of the following:
|
||||
|
|
||||
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Headers
|
||||
|
|
||||
| Boolean(true) - Allow all headers mentioned in `Access-Control-Request-Headers`.
|
||||
| Boolean(false) - Disallow all headers.
|
||||
| String - Comma separated list of allowed headers.
|
||||
| Array - An array of allowed headers.
|
||||
| Function - Receives the current header and should return one of the above values.
|
||||
|
|
||||
*/
|
||||
headers: true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Headers
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| List of headers to be allowed for `Access-Control-Allow-Headers` header.
|
||||
| The value can be one of the following:
|
||||
|
|
||||
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Headers
|
||||
|
|
||||
| Boolean(true) - Allow all headers mentioned in `Access-Control-Request-Headers`.
|
||||
| Boolean(false) - Disallow all headers.
|
||||
| String - Comma separated list of allowed headers.
|
||||
| Array - An array of allowed headers.
|
||||
| Function - Receives the current header and should return one of the above values.
|
||||
|
|
||||
*/
|
||||
headers: true,
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Expose Headers
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| A list of headers to be exposed by setting `Access-Control-Expose-Headers`.
|
||||
| header. By default following 6 simple response headers are exposed.
|
||||
|
|
||||
| Cache-Control
|
||||
| Content-Language
|
||||
| Content-Type
|
||||
| Expires
|
||||
| Last-Modified
|
||||
| Pragma
|
||||
|
|
||||
| In order to add more headers, simply define them inside the following array.
|
||||
|
|
||||
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
|
||||
|
|
||||
*/
|
||||
exposeHeaders: ['cache-control', 'content-language', 'content-type', 'expires', 'last-modified', 'pragma'],
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Expose Headers
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| A list of headers to be exposed by setting `Access-Control-Expose-Headers`.
|
||||
| header. By default following 6 simple response headers are exposed.
|
||||
|
|
||||
| Cache-Control
|
||||
| Content-Language
|
||||
| Content-Type
|
||||
| Expires
|
||||
| Last-Modified
|
||||
| Pragma
|
||||
|
|
||||
| In order to add more headers, simply define them inside the following array.
|
||||
|
|
||||
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
|
||||
|
|
||||
*/
|
||||
exposeHeaders: ['cache-control', 'content-language', 'content-type', 'expires', 'last-modified', 'pragma'],
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Credentials
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Toggle `Access-Control-Allow-Credentials` header. If value is set to `true`,
|
||||
| then header will be set, otherwise not.
|
||||
|
|
||||
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
|
||||
|
|
||||
*/
|
||||
credentials: true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Credentials
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Toggle `Access-Control-Allow-Credentials` header. If value is set to `true`,
|
||||
| then header will be set, otherwise not.
|
||||
|
|
||||
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
|
||||
|
|
||||
*/
|
||||
credentials: true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| MaxAge
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Define `Access-Control-Max-Age` header in seconds.
|
||||
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
|
||||
|
|
||||
*/
|
||||
maxAge: 90,
|
||||
};
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| MaxAge
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Define `Access-Control-Max-Age` header in seconds.
|
||||
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
|
||||
|
|
||||
*/
|
||||
maxAge: 90,
|
||||
});
|
||||
|
||||
export default corsConfig;
|
||||
|
|
|
@ -5,52 +5,53 @@
|
|||
* file.
|
||||
*/
|
||||
|
||||
import Env from '@ioc:Adonis/Core/Env';
|
||||
import { DatabaseConfig } from '@ioc:Adonis/Lucid/Database';
|
||||
import env from '#start/env';
|
||||
// import { DatabaseConfig } from "@adonisjs/lucid/database";
|
||||
import { defineConfig } from "@adonisjs/lucid";
|
||||
|
||||
const databaseConfig: DatabaseConfig = {
|
||||
const databaseConfig = defineConfig({
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Connection
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The primary connection for making database queries across the application
|
||||
| You can use any key from the `connections` object defined in this same
|
||||
| file.
|
||||
|
|
||||
*/
|
||||
connection: env.get('DB_CONNECTION'),
|
||||
|
||||
connections: {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Connection
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The primary connection for making database queries across the application
|
||||
| You can use any key from the `connections` object defined in this same
|
||||
| file.
|
||||
|
|
||||
*/
|
||||
connection: Env.get('DB_CONNECTION'),
|
||||
|
||||
connections: {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| PostgreSQL config
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Configuration for PostgreSQL database. Make sure to install the driver
|
||||
| from npm when using this connection
|
||||
|
|
||||
| npm i pg
|
||||
|
|
||||
*/
|
||||
pg: {
|
||||
client: 'pg',
|
||||
connection: {
|
||||
host: Env.get('PG_HOST'),
|
||||
port: Env.get('PG_PORT'),
|
||||
user: Env.get('PG_USER'),
|
||||
password: Env.get('PG_PASSWORD', ''),
|
||||
database: Env.get('PG_DB_NAME'),
|
||||
},
|
||||
searchPath: ['gba', 'public'],
|
||||
migrations: {
|
||||
naturalSort: true,
|
||||
},
|
||||
healthCheck: false,
|
||||
debug: false,
|
||||
pool: { min: 1, max: 100 },
|
||||
},
|
||||
|--------------------------------------------------------------------------
|
||||
| PostgreSQL config
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Configuration for PostgreSQL database. Make sure to install the driver
|
||||
| from npm when using this connection
|
||||
|
|
||||
| npm i pg
|
||||
|
|
||||
*/
|
||||
pg: {
|
||||
client: 'pg',
|
||||
connection: {
|
||||
host: env.get('PG_HOST'),
|
||||
port: env.get('PG_PORT'),
|
||||
user: env.get('PG_USER'),
|
||||
password: env.get('PG_PASSWORD', ''),
|
||||
database: env.get('PG_DB_NAME'),
|
||||
},
|
||||
searchPath: ['gba', 'public'],
|
||||
migrations: {
|
||||
naturalSort: true,
|
||||
},
|
||||
healthCheck: false,
|
||||
debug: false,
|
||||
pool: { min: 1, max: 100 },
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export default databaseConfig;
|
||||
|
|
|
@ -5,8 +5,9 @@
|
|||
* file.
|
||||
*/
|
||||
|
||||
import Env from '@ioc:Adonis/Core/Env';
|
||||
import { driveConfig } from '@adonisjs/core/build/config';
|
||||
import env from '#start/env';
|
||||
// import { driveConfig } from '@adonisjs/core/build/config';
|
||||
import { driveConfig } from "@adonisjs/drive/build/config.js";
|
||||
// import Application from '@ioc:Adonis/Core/Application';
|
||||
|
||||
/*
|
||||
|
@ -28,7 +29,7 @@ export default driveConfig({
|
|||
| the `DRIVE_DISK` environment variable.
|
||||
|
|
||||
*/
|
||||
disk: Env.get('DRIVE_DISK', 'local'),
|
||||
disk: env.get('DRIVE_DISK', 'local'),
|
||||
|
||||
disks: {
|
||||
/*
|
||||
|
|
158
config/hash.ts
158
config/hash.ts
|
@ -5,9 +5,10 @@
|
|||
* file.
|
||||
*/
|
||||
|
||||
import Env from '@ioc:Adonis/Core/Env';
|
||||
import { hashConfig } from '@adonisjs/core/build/config';
|
||||
|
||||
import env from '#start/env';
|
||||
import { defineConfig } from "@adonisjs/core/hash";
|
||||
import { drivers } from "@adonisjs/core/hash";
|
||||
import { laravelDriver } from '../providers/HashDriver/index.js';
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Hash Config
|
||||
|
@ -17,80 +18,87 @@ import { hashConfig } from '@adonisjs/core/build/config';
|
|||
| defined inside `contracts` directory.
|
||||
|
|
||||
*/
|
||||
export default hashConfig({
|
||||
export default defineConfig({
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default hasher
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| By default we make use of the argon hasher to hash values. However, feel
|
||||
| free to change the default value
|
||||
|
|
||||
*/
|
||||
default: env.get('HASH_DRIVER', 'scrypt'),
|
||||
|
||||
list: {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Default hasher
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| By default we make use of the argon hasher to hash values. However, feel
|
||||
| free to change the default value
|
||||
|
|
||||
*/
|
||||
default: Env.get('HASH_DRIVER', 'scrypt'),
|
||||
|--------------------------------------------------------------------------
|
||||
| scrypt
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Scrypt mapping uses the Node.js inbuilt crypto module for creating
|
||||
| hashes.
|
||||
|
|
||||
| We are using the default configuration recommended within the Node.js
|
||||
| documentation.
|
||||
| https://nodejs.org/api/crypto.html#cryptoscryptpassword-salt-keylen-options-callback
|
||||
|
|
||||
*/
|
||||
scrypt: drivers.scrypt({
|
||||
cost: 16384,
|
||||
blockSize: 8,
|
||||
parallelization: 1,
|
||||
saltSize: 16,
|
||||
keyLength: 64,
|
||||
maxMemory: 32 * 1024 * 1024,
|
||||
}),
|
||||
|
||||
list: {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| scrypt
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Scrypt mapping uses the Node.js inbuilt crypto module for creating
|
||||
| hashes.
|
||||
|
|
||||
| We are using the default configuration recommended within the Node.js
|
||||
| documentation.
|
||||
| https://nodejs.org/api/crypto.html#cryptoscryptpassword-salt-keylen-options-callback
|
||||
|
|
||||
*/
|
||||
scrypt: {
|
||||
driver: 'scrypt',
|
||||
cost: 16384,
|
||||
blockSize: 8,
|
||||
parallelization: 1,
|
||||
saltSize: 16,
|
||||
keyLength: 64,
|
||||
maxMemory: 32 * 1024 * 1024,
|
||||
},
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Argon
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Argon mapping uses the `argon2` driver to hash values.
|
||||
|
|
||||
| Make sure you install the underlying dependency for this driver to work.
|
||||
| https://www.npmjs.com/package/phc-argon2.
|
||||
|
|
||||
| npm install phc-argon2
|
||||
|
|
||||
*/
|
||||
argon: drivers.argon2({
|
||||
variant: 'id',
|
||||
iterations: 3,
|
||||
memory: 4096,
|
||||
parallelism: 1,
|
||||
saltSize: 16,
|
||||
}),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Argon
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Argon mapping uses the `argon2` driver to hash values.
|
||||
|
|
||||
| Make sure you install the underlying dependency for this driver to work.
|
||||
| https://www.npmjs.com/package/phc-argon2.
|
||||
|
|
||||
| npm install phc-argon2
|
||||
|
|
||||
*/
|
||||
argon: {
|
||||
driver: 'argon2',
|
||||
variant: 'id',
|
||||
iterations: 3,
|
||||
memory: 4096,
|
||||
parallelism: 1,
|
||||
saltSize: 16,
|
||||
},
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Bcrypt
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Bcrypt mapping uses the `bcrypt` driver to hash values.
|
||||
|
|
||||
| Make sure you install the underlying dependency for this driver to work.
|
||||
| https://www.npmjs.com/package/phc-bcrypt.
|
||||
|
|
||||
| npm install phc-bcrypt
|
||||
|
|
||||
*/
|
||||
bcrypt: drivers.bcrypt({
|
||||
rounds: 10,
|
||||
}),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Bcrypt
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Bcrypt mapping uses the `bcrypt` driver to hash values.
|
||||
|
|
||||
| Make sure you install the underlying dependency for this driver to work.
|
||||
| https://www.npmjs.com/package/phc-bcrypt.
|
||||
|
|
||||
| npm install phc-bcrypt
|
||||
|
|
||||
*/
|
||||
bcrypt: {
|
||||
driver: 'bcrypt',
|
||||
rounds: 10,
|
||||
},
|
||||
},
|
||||
laravel: laravelDriver({
|
||||
rounds: 10,
|
||||
}),
|
||||
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
declare module '@adonisjs/core/types' {
|
||||
export interface HashersList extends InferHashers<typeof hashConfig> { }
|
||||
}
|
||||
|
|
|
@ -1,20 +1,57 @@
|
|||
/**
|
||||
* Feel free to let me know via PR,
|
||||
* if you find something broken in this config file.
|
||||
*/
|
||||
import { defineConfig } from '@adonisjs/inertia';
|
||||
import type { HttpContext } from '@adonisjs/core/http';
|
||||
|
||||
import { InertiaConfig } from '@ioc:EidelLev/Inertia';
|
||||
export default defineConfig({
|
||||
/**
|
||||
* Path to the Edge view that will be used as the root view for Inertia responses
|
||||
*/
|
||||
rootView: 'app',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Inertia-AdonisJS config
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
*/
|
||||
/**
|
||||
* Data that should be shared with all rendered pages
|
||||
*/
|
||||
sharedData: {
|
||||
errors: (ctx) => ctx.session.flashMessages.get('errors'),
|
||||
|
||||
export const inertia: InertiaConfig = {
|
||||
view: 'app',
|
||||
// ssr: {
|
||||
// enabled: false,
|
||||
// },
|
||||
};
|
||||
user_id: (ctx) => {
|
||||
return ctx.session.flashMessages.get('user_id');
|
||||
},
|
||||
|
||||
flash: (ctx) => {
|
||||
return {
|
||||
message: ctx.session.flashMessages.get('message'),
|
||||
warning: ctx.session.flashMessages.get('warning'),
|
||||
};
|
||||
},
|
||||
|
||||
// params: ({ params }) => params,
|
||||
authUser: async ({ auth }: HttpContext) => {
|
||||
if (auth.user) {
|
||||
await auth.user.load('roles');
|
||||
return auth.user;
|
||||
// {
|
||||
// 'id': auth.user.id,
|
||||
// 'login': auth.user.login,
|
||||
// };
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// import { InertiaConfig } from '@ioc:EidelLev/Inertia';
|
||||
|
||||
// /*
|
||||
// |--------------------------------------------------------------------------
|
||||
// | Inertia-AdonisJS config
|
||||
// |--------------------------------------------------------------------------
|
||||
// |
|
||||
// */
|
||||
|
||||
// export const inertia: InertiaConfig = {
|
||||
// view: 'app',
|
||||
// // ssr: {
|
||||
// // enabled: false,
|
||||
// // },
|
||||
// };
|
||||
|
|
35
config/logger.ts
Normal file
35
config/logger.ts
Normal file
|
@ -0,0 +1,35 @@
|
|||
import env from '#start/env'
|
||||
import app from '@adonisjs/core/services/app'
|
||||
import { defineConfig, targets } from '@adonisjs/core/logger'
|
||||
|
||||
const loggerConfig = defineConfig({
|
||||
default: 'app',
|
||||
|
||||
/**
|
||||
* The loggers object can be used to define multiple loggers.
|
||||
* By default, we configure only one logger (named "app").
|
||||
*/
|
||||
loggers: {
|
||||
app: {
|
||||
enabled: true,
|
||||
name: env.get('APP_NAME'),
|
||||
level: env.get('LOG_LEVEL'),
|
||||
transport: {
|
||||
targets: targets()
|
||||
.pushIf(!app.inProduction, targets.pretty())
|
||||
.pushIf(app.inProduction, targets.file({ destination: 1 }))
|
||||
.toArray(),
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
export default loggerConfig
|
||||
|
||||
/**
|
||||
* Inferring types for the list of loggers you have configured
|
||||
* in your application.
|
||||
*/
|
||||
declare module '@adonisjs/core/types' {
|
||||
export interface LoggersList extends InferLoggers<typeof loggerConfig> {}
|
||||
}
|
|
@ -1,4 +1,4 @@
|
|||
import Env from '@ioc:Adonis/Core/Env';
|
||||
import env from '#start/env';
|
||||
|
||||
interface OaiConfig {
|
||||
max: { listidentifiers: number; listrecords: number };
|
||||
|
@ -7,8 +7,8 @@ interface OaiConfig {
|
|||
}
|
||||
const config: OaiConfig = {
|
||||
max: {
|
||||
listidentifiers: parseInt(Env.get('OAI_LIST_SIZE', 100), 10),
|
||||
listrecords: parseInt(Env.get('OAI_LIST_SIZE', 100), 10),
|
||||
listidentifiers: parseInt(env.get('OAI_LIST_SIZE', 100), 10),
|
||||
listrecords: parseInt(env.get('OAI_LIST_SIZE', 100), 10),
|
||||
},
|
||||
workspacePath: 'workspace',
|
||||
redis: {
|
||||
|
|
|
@ -1,28 +1,9 @@
|
|||
/**
|
||||
* Config source: https://git.io/JemcF
|
||||
*
|
||||
* Feel free to let us know via PR, if you find something broken in this config
|
||||
* file.
|
||||
*/
|
||||
import env from '#start/env'
|
||||
import { defineConfig } from '@adonisjs/redis'
|
||||
import { InferConnections } from '@adonisjs/redis/types'
|
||||
|
||||
import Env from '@ioc:Adonis/Core/Env'
|
||||
import { redisConfig } from '@adonisjs/redis/build/config'
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Redis configuration
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Following is the configuration used by the Redis provider to connect to
|
||||
| the redis server and execute redis commands.
|
||||
|
|
||||
| Do make sure to pre-define the connections type inside `contracts/redis.ts`
|
||||
| file for AdonisJs to recognize connections.
|
||||
|
|
||||
| Make sure to check `contracts/redis.ts` file for defining extra connections
|
||||
*/
|
||||
export default redisConfig({
|
||||
connection: Env.get('REDIS_CONNECTION'),
|
||||
const redisConfig = defineConfig({
|
||||
connection: 'main',
|
||||
|
||||
connections: {
|
||||
/*
|
||||
|
@ -35,12 +16,21 @@ export default redisConfig({
|
|||
| redis driver.
|
||||
|
|
||||
*/
|
||||
local: {
|
||||
host: Env.get('REDIS_HOST'),
|
||||
port: Env.get('REDIS_PORT'),
|
||||
password: Env.get('REDIS_PASSWORD', ''),
|
||||
main: {
|
||||
host: env.get('REDIS_HOST'),
|
||||
port: env.get('REDIS_PORT'),
|
||||
password: env.get('REDIS_PASSWORD', ''),
|
||||
db: 0,
|
||||
keyPrefix: '',
|
||||
retryStrategy(times) {
|
||||
return times > 10 ? null : times * 50
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
export default redisConfig
|
||||
|
||||
declare module '@adonisjs/redis/types' {
|
||||
export interface RedisConnections extends InferConnections<typeof redisConfig> {}
|
||||
}
|
|
@ -5,112 +5,122 @@
|
|||
* file.
|
||||
*/
|
||||
|
||||
import Env from '@ioc:Adonis/Core/Env';
|
||||
import Application from '@ioc:Adonis/Core/Application';
|
||||
import { sessionConfig } from '@adonisjs/session/build/config';
|
||||
import env from '#start/env';
|
||||
import app from '@adonisjs/core/services/app';
|
||||
import { defineConfig, stores } from '@adonisjs/session';
|
||||
|
||||
export default sessionConfig({
|
||||
export default defineConfig({
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Enable/Disable sessions
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Setting the following property to "false" will disable the session for the
|
||||
| entire application
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Enable/Disable sessions
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Setting the following property to "false" will disable the session for the
|
||||
| entire application
|
||||
|
|
||||
*/
|
||||
enabled: true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Driver
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The session driver to use. You can choose between one of the following
|
||||
| drivers.
|
||||
|
|
||||
| - cookie (Uses signed cookies to store session values)
|
||||
| - file (Uses filesystem to store session values)
|
||||
| - redis (Uses redis. Make sure to install "@adonisjs/redis" as well)
|
||||
|
|
||||
| Note: Switching drivers will make existing sessions invalid.
|
||||
|
|
||||
*/
|
||||
driver: Env.get('SESSION_DRIVER'),
|
||||
|--------------------------------------------------------------------------
|
||||
| Driver
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The session driver to use. You can choose between one of the following
|
||||
| drivers.
|
||||
|
|
||||
| - cookie (Uses signed cookies to store session values)
|
||||
| - file (Uses filesystem to store session values)
|
||||
| - redis (Uses redis. Make sure to install "@adonisjs/redis" as well)
|
||||
|
|
||||
| Note: Switching drivers will make existing sessions invalid.
|
||||
|
|
||||
*/
|
||||
// driver: env.get('SESSION_DRIVER'),
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Cookie name
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The name of the cookie that will hold the session id.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Cookie name
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The name of the cookie that will hold the session id.
|
||||
|
|
||||
*/
|
||||
cookieName: 'adonis-session',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Clear session when browser closes
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Whether or not you want to destroy the session when browser closes. Setting
|
||||
| this value to `true` will ignore the `age`.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Clear session when browser closes
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Whether or not you want to destroy the session when browser closes. Setting
|
||||
| this value to `true` will ignore the `age`.
|
||||
|
|
||||
*/
|
||||
clearWithBrowser: false,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Session age
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The duration for which session stays active after no activity. A new HTTP
|
||||
| request to the server is considered as activity.
|
||||
|
|
||||
| The value can be a number in milliseconds or a string that must be valid
|
||||
| as per https://npmjs.org/package/ms package.
|
||||
|
|
||||
| Example: `2 days`, `2.5 hrs`, `1y`, `5s` and so on.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Session age
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The duration for which session stays active after no activity. A new HTTP
|
||||
| request to the server is considered as activity.
|
||||
|
|
||||
| The value can be a number in milliseconds or a string that must be valid
|
||||
| as per https://npmjs.org/package/ms package.
|
||||
|
|
||||
| Example: `2 days`, `2.5 hrs`, `1y`, `5s` and so on.
|
||||
|
|
||||
*/
|
||||
age: '2h',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Cookie values
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The cookie settings are used to setup the session id cookie and also the
|
||||
| driver will use the same values.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Cookie values
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The cookie settings are used to setup the session id cookie and also the
|
||||
| driver will use the same values.
|
||||
|
|
||||
*/
|
||||
cookie: {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
secure: app.inProduction,
|
||||
sameSite: false,
|
||||
},
|
||||
|
||||
/**
|
||||
* The store to use. Make sure to validate the environment
|
||||
* variable in order to infer the store name without any
|
||||
* errors.
|
||||
*/
|
||||
store: env.get('SESSION_DRIVER'),
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Configuration for the file driver
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The file driver needs absolute path to the directory in which sessions
|
||||
| must be stored.
|
||||
|
|
||||
*/
|
||||
file: {
|
||||
location: Application.tmpPath('sessions'),
|
||||
},
|
||||
|--------------------------------------------------------------------------
|
||||
| Configuration for the file driver
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The file driver needs absolute path to the directory in which sessions
|
||||
| must be stored.
|
||||
|
|
||||
*/
|
||||
// file: {
|
||||
// location: app.tmpPath('sessions'),
|
||||
// },
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Redis driver
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The redis connection you want session driver to use. The same connection
|
||||
| must be defined inside `config/redis.ts` file as well.
|
||||
|
|
||||
*/
|
||||
|--------------------------------------------------------------------------
|
||||
| Redis driver
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The redis connection you want session driver to use. The same connection
|
||||
| must be defined inside `config/redis.ts` file as well.
|
||||
|
|
||||
*/
|
||||
redisConnection: 'local',
|
||||
stores: {
|
||||
cookie: stores.cookie(),
|
||||
},
|
||||
});
|
||||
|
|
179
config/shield.ts
179
config/shield.ts
|
@ -1,24 +1,8 @@
|
|||
/**
|
||||
* Config source: https://git.io/Jvwvt
|
||||
*
|
||||
* Feel free to let us know via PR, if you find something broken in this config
|
||||
* file.
|
||||
*/
|
||||
import { defineConfig } from '@adonisjs/shield';
|
||||
|
||||
// import Env from '@ioc:Adonis/Core/Env'
|
||||
import { ShieldConfig } from '@ioc:Adonis/Addons/Shield';
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Content Security Policy
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Content security policy filters out the origins not allowed to execute
|
||||
| and load resources like scripts, styles and fonts. There are wide
|
||||
| variety of options to choose from.
|
||||
*/
|
||||
export const csp: ShieldConfig['csp'] = {
|
||||
/*
|
||||
export default defineConfig({
|
||||
csp: {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Enable/disable CSP
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -26,9 +10,9 @@ export const csp: ShieldConfig['csp'] = {
|
|||
| The CSP rules are disabled by default for seamless onboarding.
|
||||
|
|
||||
*/
|
||||
enabled: false,
|
||||
enabled: false,
|
||||
|
||||
/*
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Directives
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -44,9 +28,9 @@ export const csp: ShieldConfig['csp'] = {
|
|||
| }
|
||||
|
|
||||
*/
|
||||
directives: {},
|
||||
directives: {},
|
||||
|
||||
/*
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Report only
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -55,27 +39,17 @@ export const csp: ShieldConfig['csp'] = {
|
|||
| instead report them to a URL.
|
||||
|
|
||||
*/
|
||||
reportOnly: false,
|
||||
};
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| CSRF Protection
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| CSRF Protection adds another layer of security by making sure, actionable
|
||||
| routes does have a valid token to execute an action.
|
||||
|
|
||||
*/
|
||||
export const csrf: ShieldConfig['csrf'] = {
|
||||
/*
|
||||
reportOnly: false,
|
||||
},
|
||||
csrf: {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Enable/Disable CSRF
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
enabled: true,
|
||||
enabled: true,
|
||||
|
||||
/*
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Routes to Ignore
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -85,16 +59,16 @@ export const csrf: ShieldConfig['csrf'] = {
|
|||
| slash. Example:
|
||||
|
|
||||
| `/foo/bar`
|
||||
|
|
||||
| Also you can define a function that is evaluated on every HTTP Request.
|
||||
| ```
|
||||
| exceptRoutes: ({ request }) => request.url().includes('/api')
|
||||
| ```
|
||||
|
|
||||
| Also you can define a function that is evaluated on every HTTP Request.
|
||||
| ```
|
||||
| exceptRoutes: ({ request }) => request.url().includes('/api')
|
||||
| ```
|
||||
|
|
||||
*/
|
||||
exceptRoutes: [],
|
||||
exceptRoutes: [],
|
||||
|
||||
/*
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Enable Sharing Token Via Cookie
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -108,9 +82,9 @@ export const csrf: ShieldConfig['csrf'] = {
|
|||
| AJAX requests.
|
||||
|
|
||||
*/
|
||||
enableXsrfCookie: true,
|
||||
enableXsrfCookie: true,
|
||||
|
||||
/*
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Methods to Validate
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -118,76 +92,11 @@ export const csrf: ShieldConfig['csrf'] = {
|
|||
| Define an array of HTTP methods to be validated for a valid CSRF token.
|
||||
|
|
||||
*/
|
||||
methods: ['POST', 'PUT', 'PATCH', 'DELETE'],
|
||||
};
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| DNS Prefetching
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| DNS prefetching allows browsers to proactively perform domain name
|
||||
| resolution in background.
|
||||
|
|
||||
| Learn more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control
|
||||
|
|
||||
*/
|
||||
export const dnsPrefetch: ShieldConfig['dnsPrefetch'] = {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Enable/disable this feature
|
||||
|--------------------------------------------------------------------------
|
||||
*/
|
||||
enabled: true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Allow or Dis-Allow Explicitly
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The `enabled` boolean does not set `X-DNS-Prefetch-Control` header. However
|
||||
| the `allow` boolean controls the value of `X-DNS-Prefetch-Control` header.
|
||||
|
|
||||
| - When `allow = true`, then `X-DNS-Prefetch-Control = 'on'`
|
||||
| - When `allow = false`, then `X-DNS-Prefetch-Control = 'off'`
|
||||
|
|
||||
*/
|
||||
allow: true,
|
||||
};
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Iframe Options
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| xFrame defines whether or not your website can be embedded inside an
|
||||
| iframe. Choose from one of the following options.
|
||||
|
|
||||
| - DENY
|
||||
| - SAMEORIGIN
|
||||
| - ALLOW-FROM http://example.com
|
||||
|
|
||||
| Learn more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options
|
||||
*/
|
||||
export const xFrame: ShieldConfig['xFrame'] = {
|
||||
enabled: true,
|
||||
action: 'DENY',
|
||||
};
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Http Strict Transport Security
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| A security to ensure that a browser always makes a connection over
|
||||
| HTTPS.
|
||||
|
|
||||
| Learn more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Strict-Transport-Security
|
||||
|
|
||||
*/
|
||||
export const hsts: ShieldConfig['hsts'] = {
|
||||
enabled: true,
|
||||
/*
|
||||
methods: ['POST', 'PUT', 'PATCH', 'DELETE'],
|
||||
},
|
||||
hsts: {
|
||||
enabled: true,
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Max Age
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -196,9 +105,9 @@ export const hsts: ShieldConfig['hsts'] = {
|
|||
| accessed using HTTPS.
|
||||
|
|
||||
*/
|
||||
maxAge: '180 days',
|
||||
maxAge: '180 days',
|
||||
|
||||
/*
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Include Subdomains
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -206,9 +115,9 @@ export const hsts: ShieldConfig['hsts'] = {
|
|||
| Apply rules on the subdomains as well.
|
||||
|
|
||||
*/
|
||||
includeSubDomains: true,
|
||||
includeSubDomains: true,
|
||||
|
||||
/*
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Preloading
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -217,21 +126,9 @@ export const hsts: ShieldConfig['hsts'] = {
|
|||
| the HSTS policy. Learn more https://hstspreload.org/
|
||||
|
|
||||
*/
|
||||
preload: false,
|
||||
};
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| No Sniff
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Browsers have a habit of sniffing content-type of a response. Which means
|
||||
| files with .txt extension containing Javascript code will be executed as
|
||||
| Javascript. You can disable this behavior by setting nosniff to false.
|
||||
|
|
||||
| Learn more at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Content-Type-Options
|
||||
|
|
||||
*/
|
||||
export const contentTypeSniffing: ShieldConfig['contentTypeSniffing'] = {
|
||||
enabled: true,
|
||||
};
|
||||
preload: false,
|
||||
},
|
||||
contentTypeSniffing: {
|
||||
enabled: true,
|
||||
},
|
||||
});
|
||||
|
|
|
@ -1,89 +1,17 @@
|
|||
import { defineConfig } from '@adonisjs/static'
|
||||
|
||||
/**
|
||||
* Config source: https://git.io/Jfefl
|
||||
* Configuration options to tweak the static files middleware.
|
||||
* The complete set of options are documented on the
|
||||
* official documentation website.
|
||||
*
|
||||
* Feel free to let us know via PR, if you find something broken in this config
|
||||
* file.
|
||||
* https://docs.adonisjs.com/guides/static-assets
|
||||
*/
|
||||
const staticServerConfig = defineConfig({
|
||||
enabled: true,
|
||||
etag: true,
|
||||
lastModified: true,
|
||||
dotFiles: 'ignore',
|
||||
})
|
||||
|
||||
import { AssetsConfig } from '@ioc:Adonis/Core/Static';
|
||||
|
||||
const staticConfig: AssetsConfig = {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Enabled
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| A boolean to enable or disable serving static files. The static files
|
||||
| are served from the `public` directory inside the application root.
|
||||
| However, you can override the default path inside `.adonisrc.json`
|
||||
| file.
|
||||
|
|
||||
|
|
||||
*/
|
||||
enabled: true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Handling Dot Files
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Decide how you want the static assets server to handle the `dotfiles`.
|
||||
| By default, we ignore them as if they don't exists. However, you
|
||||
| can choose between one of the following options.
|
||||
|
|
||||
| - ignore: Behave as if the file doesn't exists. Results in 404.
|
||||
| - deny: Deny access to the file. Results in 403.
|
||||
| - allow: Serve the file contents
|
||||
|
|
||||
*/
|
||||
dotFiles: 'ignore',
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Generating Etag
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Handle whether or not to generate etags for the files. Etag allows browser
|
||||
| to utilize the cache when file hasn't been changed.
|
||||
|
|
||||
*/
|
||||
etag: true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Set Last Modified
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Whether or not to set the `Last-Modified` header in the response. Uses
|
||||
| the file system's last modified value.
|
||||
|
|
||||
*/
|
||||
lastModified: true,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Max age
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Set the value for the max-age directive. Set a higher value in production
|
||||
| if you fingerprint your assets.
|
||||
|
|
||||
| Learn more: https://docs.adonisjs.com/guides/deployment#serving-static-assets
|
||||
|
|
||||
*/
|
||||
maxAge: 0,
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Immutable
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| Set the immutable directive. Set it to `true` if the assets are generated
|
||||
| with a fingerprint. In others words the file name changes when the file
|
||||
| contents change.
|
||||
|
|
||||
*/
|
||||
immutable: false,
|
||||
};
|
||||
|
||||
export default staticConfig;
|
||||
export default staticServerConfig
|
|
@ -1,73 +1,63 @@
|
|||
/**
|
||||
* Contract source: https://git.io/JOdz5
|
||||
*
|
||||
* Feel free to let us know via PR, if you find something broken in this
|
||||
* file.
|
||||
*/
|
||||
// /**
|
||||
// * Contract source: https://git.io/JOdz5
|
||||
// *
|
||||
// * Feel free to let us know via PR, if you find something broken in this
|
||||
// * file.
|
||||
// */
|
||||
|
||||
import User from 'App/Models/User';
|
||||
// import User from '#app/Models/User';
|
||||
|
||||
declare module '@ioc:Adonis/Addons/Auth' {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Providers
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The providers are used to fetch users. The Auth module comes pre-bundled
|
||||
| with two providers that are `Lucid` and `Database`. Both uses database
|
||||
| to fetch user details.
|
||||
|
|
||||
| You can also create and register your own custom providers.
|
||||
|
|
||||
*/
|
||||
interface ProvidersList {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| User Provider
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The following provider uses Lucid models as a driver for fetching user
|
||||
| details from the database for authentication.
|
||||
|
|
||||
| You can create multiple providers using the same underlying driver with
|
||||
| different Lucid models.
|
||||
|
|
||||
*/
|
||||
user: {
|
||||
implementation: LucidProviderContract<typeof User>;
|
||||
config: LucidProviderConfig<typeof User>;
|
||||
};
|
||||
}
|
||||
// declare module '@ioc:Adonis/Addons/Auth' {
|
||||
// /*
|
||||
// |
|
||||
// interface ProvidersList {
|
||||
// /*
|
||||
// |--------------------------------------------------------------------------
|
||||
// | User Provider
|
||||
// |--------------------------------------------------------------------------
|
||||
// |
|
||||
// | The following provider uses Lucid models as a driver for fetching user
|
||||
// | details from the database for authentication.
|
||||
// |
|
||||
// | You can create multiple providers using the same underlying driver with
|
||||
// | different Lucid models.
|
||||
// |
|
||||
// */
|
||||
// user: {
|
||||
// implementation: LucidProviderContract<typeof User>;
|
||||
// config: LucidProviderConfig<typeof User>;
|
||||
// };
|
||||
// }
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Guards
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The guards are used for authenticating users using different drivers.
|
||||
| The auth module comes with 3 different guards.
|
||||
|
|
||||
| - SessionGuardContract
|
||||
| - BasicAuthGuardContract
|
||||
| - OATGuardContract ( Opaque access token )
|
||||
|
|
||||
| Every guard needs a provider for looking up users from the database.
|
||||
|
|
||||
*/
|
||||
interface GuardsList {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Web Guard
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The web guard uses sessions for maintaining user login state. It uses
|
||||
| the `user` provider for fetching user details.
|
||||
|
|
||||
*/
|
||||
web: {
|
||||
implementation: SessionGuardContract<'user', 'web'>;
|
||||
config: SessionGuardConfig<'user'>;
|
||||
client: SessionClientContract<'user'>;
|
||||
};
|
||||
}
|
||||
}
|
||||
// /*
|
||||
// |--------------------------------------------------------------------------
|
||||
// | Guards
|
||||
// |--------------------------------------------------------------------------
|
||||
// |
|
||||
// | The guards are used for authenticating users using different drivers.
|
||||
// | The auth module comes with 3 different guards.
|
||||
// |
|
||||
// | - SessionGuardContract
|
||||
// | - BasicAuthGuardContract
|
||||
// | - OATGuardContract ( Opaque access token )
|
||||
// |
|
||||
// | Every guard needs a provider for looking up users from the database.
|
||||
// |
|
||||
// */
|
||||
// interface GuardsList {
|
||||
// /*
|
||||
// |--------------------------------------------------------------------------
|
||||
// | Web Guard
|
||||
// |--------------------------------------------------------------------------
|
||||
// |
|
||||
// | The web guard uses sessions for maintaining user login state. It uses
|
||||
// | the `user` provider for fetching user details.
|
||||
// |
|
||||
// */
|
||||
// web: {
|
||||
// implementation: SessionGuardContract<'user', 'web'>;
|
||||
// config: SessionGuardConfig<'user'>;
|
||||
// client: SessionClientContract<'user'>;
|
||||
// };
|
||||
// }
|
||||
// }
|
||||
|
|
|
@ -5,9 +5,9 @@
|
|||
* file.
|
||||
*/
|
||||
|
||||
import type { InferDisksFromConfig } from '@adonisjs/core/build/config';
|
||||
import type driveConfig from '../config/drive';
|
||||
// import type { InferDisksFromConfig } from '@adonisjs/core/build/config';
|
||||
// import type driveConfig from '../config/drive.js';
|
||||
|
||||
declare module '@ioc:Adonis/Core/Drive' {
|
||||
interface DisksList extends InferDisksFromConfig<typeof driveConfig> {}
|
||||
}
|
||||
// declare module '@ioc:Adonis/Core/Drive' {
|
||||
// interface DisksList extends InferDisksFromConfig<typeof driveConfig> {}
|
||||
// }
|
||||
|
|
|
@ -1,23 +0,0 @@
|
|||
/**
|
||||
* Contract source: https://git.io/JTm6U
|
||||
*
|
||||
* Feel free to let us know via PR, if you find something broken in this contract
|
||||
* file.
|
||||
*/
|
||||
|
||||
declare module '@ioc:Adonis/Core/Env' {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Getting types for validated environment variables
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| The `default` export from the "../env.ts" file exports types for the
|
||||
| validated environment variables. Here we merge them with the `EnvTypes`
|
||||
| interface so that you can enjoy intellisense when using the "Env"
|
||||
| module.
|
||||
|
|
||||
*/
|
||||
|
||||
type CustomTypes = typeof import('../env').default;
|
||||
interface EnvTypes extends CustomTypes {}
|
||||
}
|
|
@ -1,31 +0,0 @@
|
|||
/**
|
||||
* Contract source: https://git.io/JfefG
|
||||
*
|
||||
* Feel free to let us know via PR, if you find something broken in this contract
|
||||
* file.
|
||||
*/
|
||||
|
||||
declare module '@ioc:Adonis/Core/Event' {
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
| Define typed events
|
||||
|--------------------------------------------------------------------------
|
||||
|
|
||||
| You can define types for events inside the following interface and
|
||||
| AdonisJS will make sure that all listeners and emit calls adheres
|
||||
| to the defined types.
|
||||
|
|
||||
| For example:
|
||||
|
|
||||
| interface EventsList {
|
||||
| 'new:user': UserModel
|
||||
| }
|
||||
|
|
||||
| Now calling `Event.emit('new:user')` will statically ensure that passed value is
|
||||
| an instance of the the UserModel only.
|
||||
|
|
||||
*/
|
||||
interface EventsList {
|
||||
//
|
||||
}
|
||||
}
|
|
@ -1,13 +0,0 @@
|
|||
/**
|
||||
* Contract source: https://git.io/Jfefs
|
||||
*
|
||||
* Feel free to let us know via PR, if you find something broken in this contract
|
||||
* file.
|
||||
*/
|
||||
|
||||
import type { InferListFromConfig } from '@adonisjs/core/build/config';
|
||||
import type hashConfig from '../config/hash';
|
||||
|
||||
declare module '@ioc:Adonis/Core/Hash' {
|
||||
interface HashersList extends InferListFromConfig<typeof hashConfig> {}
|
||||
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue
Block a user