- update to AdonisJS 6
Some checks failed
CI Pipeline / japa-tests (push) Failing after 1m15s

This commit is contained in:
Kaimbacher 2024-03-14 20:25:27 +01:00
parent f828ca4491
commit cb51a4136f
167 changed files with 21485 additions and 21212 deletions

View File

@ -14,4 +14,4 @@ PG_DB_NAME=lucid
REDIS_CONNECTION=local REDIS_CONNECTION=local
REDIS_HOST=127.0.0.1 REDIS_HOST=127.0.0.1
REDIS_PORT=6379 REDIS_PORT=6379
REDIS_PASSWORD= REDIS_PASSWORD=

16
ace
View File

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

View File

@ -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
View 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
View 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,
},
],
},
})

View File

@ -1,17 +1,17 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
export default class HomeController { 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) {}
} }

View File

@ -1,14 +1,14 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import Role from 'App/Models/Role'; import Role from '#app/Models/Role';
import Permission from 'App/Models/Permission'; import Permission from '#app/Models/Permission';
import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm'; import CreateRoleValidator from '#app/Validators/CreateRoleValidator';
import CreateRoleValidator from 'App/Validators/CreateRoleValidator'; import UpdateRoleValidator from '#app/Validators/UpdateRoleValidator';
import UpdateRoleValidator from 'App/Validators/UpdateRoleValidator'; import type { ModelQueryBuilderContract } from "@adonisjs/lucid/types/model";
import { RenderResponse } from '@ioc:EidelLev/Inertia';
// import { schema, rules } from '@ioc:Adonis/Core/Validator'; // import { schema, rules } from '@ioc:Adonis/Core/Validator';
export default class RoleController { 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(); let roles: ModelQueryBuilderContract<typeof Role, Role> = Role.query();
if (request.input('search')) { 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'); const permissions = await Permission.query().select('id', 'name').pluck('name', 'id');
return inertia.render('Admin/Role/Create', { return inertia.render('Admin/Role/Create', {
permissions: permissions, permissions: permissions,
}); });
} }
public async store({ request, response, session }: HttpContextContract) { public async store({ request, response, session }: HttpContext) {
// node ace make:validator CreateUser // node ace make:validator CreateUser
try { try {
// Step 2 - Validate request body against the schema // Step 2 - Validate request body against the schema
@ -79,7 +79,7 @@ export default class RoleController {
return response.redirect().toRoute('role.index'); 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 id = request.param('id');
const role = await Role.query().where('id', id).firstOrFail(); 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 id = request.param('id');
const role = await Role.query().where('id', id).firstOrFail(); 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 // node ace make:validator UpdateUser
const id = request.param('id'); const id = request.param('id');
const role = await Role.query().where('id', id).firstOrFail(); const role = await Role.query().where('id', id).firstOrFail();
@ -132,7 +132,7 @@ export default class RoleController {
return response.redirect().toRoute('settings.role.index'); 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 id = request.param('id');
const role = await Role.findOrFail(id); const role = await Role.findOrFail(id);
await role.delete(); await role.delete();

View File

@ -1,16 +1,15 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import User from 'App/Models/User'; import User from '#app/Models/User';
import Role from 'App/Models/Role'; import Role from '#app/Models/Role';
import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm'; import { ModelQueryBuilderContract } from "@adonisjs/lucid/types/model";
import CreateUserValidator from 'App/Validators/CreateUserValidator'; import CreateUserValidator from '#app/Validators/CreateUserValidator';
import UpdateUserValidator from 'App/Validators/UpdateUserValidator'; import UpdateUserValidator from '#app/Validators/UpdateUserValidator';
// import { RenderResponse } from '@ioc:EidelLev/Inertia';
// import { schema, rules } from '@ioc:Adonis/Core/Validator'; // import { schema, rules } from '@ioc:Adonis/Core/Validator';
// import Hash from '@ioc:Adonis/Core/Hash'; // import Hash from '@ioc:Adonis/Core/Hash';
// import { schema, rules } from '@ioc:Adonis/Core/Validator'; // import { schema, rules } from '@ioc:Adonis/Core/Validator';
export default class UsersController { export default class AdminUserController {
public async index({ auth, request, inertia }: HttpContextContract) { public async index({ auth, request, inertia }: HttpContext) {
const page = request.input('page', 1); const page = request.input('page', 1);
// const limit = 10 // const limit = 10
@ -48,7 +47,7 @@ export default class UsersController {
// .preload('focusInterests') // .preload('focusInterests')
// .preload('role') // .preload('role')
.paginate(page, 5); .paginate(page, 5);
// var test = request.all(); // var test = request.all();
return inertia.render('Admin/User/Index', { return inertia.render('Admin/User/Index', {
@ -63,7 +62,7 @@ export default class UsersController {
}); });
} }
public async create({ inertia }: HttpContextContract) { public async create({ inertia }: HttpContext) {
// let rolesPluck = {}; // let rolesPluck = {};
// (await Role.query().select('id', 'name')).forEach((user) => { // (await Role.query().select('id', 'name')).forEach((user) => {
// rolesPluck[user.id] = user.name; // 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 // node ace make:validator CreateUser
try { try {
// Step 2 - Validate request body against the schema // Step 2 - Validate request body against the schema
@ -97,7 +96,7 @@ export default class UsersController {
return response.redirect().toRoute('user.index'); return response.redirect().toRoute('user.index');
} }
public async show({ request, inertia }: HttpContextContract) { public async show({ request, inertia }: HttpContext) {
const id = request.param('id'); const id = request.param('id');
const user = await User.query().where('id', id).firstOrFail(); 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 id = request.param('id');
const user = await User.query().where('id', id).firstOrFail(); 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 // node ace make:validator UpdateUser
const id = request.param('id'); const id = request.param('id');
const user = await User.query().where('id', id).firstOrFail(); const user = await User.query().where('id', id).firstOrFail();
@ -154,7 +153,7 @@ export default class UsersController {
return response.redirect().toRoute('settings.user.index'); 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 id = request.param('id');
const user = await User.findOrFail(id); const user = await User.findOrFail(id);
await user.delete(); await user.delete();

View File

@ -1,10 +1,10 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import Person from 'App/Models/Person'; import Person from '#app/Models/Person';
// import Dataset from 'App/Models/Dataset'; // import Dataset from 'App/Models/Dataset';
// node ace make:controller Author // node ace make:controller Author
export default class AuthorsController { export default class AuthorsController {
public async index({}: HttpContextContract) { public async index({}: HttpContext) {
// select * from gba.persons // 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 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")); // where ("link_documents_persons"."role" = 'author') and ("persons"."id" = "link_documents_persons"."person_id"));
@ -19,7 +19,7 @@ export default class AuthorsController {
return authors; return authors;
} }
public async persons({ request }: HttpContextContract) { public async persons({ request }: HttpContext) {
const authors = Person.query().where('status', true); const authors = Person.query().where('status', true);
if (request.input('filter')) { if (request.input('filter')) {

View File

@ -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 { StatusCodes } from 'http-status-codes';
// import * as fs from 'fs'; // import * as fs from 'fs';
// import * as path from 'path'; // import * as path from 'path';
@ -7,7 +7,7 @@ const prefixes = ['von', 'van'];
// node ace make:controller Author // node ace make:controller Author
export default class AvatarController { export default class AvatarController {
public async generateAvatar({ request, response }: HttpContextContract) { public async generateAvatar({ request, response }: HttpContext) {
try { try {
const { name, background, textColor, size } = request.only(['name', 'background', 'textColor', 'size']); 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(' '); const parts = name.split(' ');
let initials = ''; let initials = '';

View File

@ -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 Person from 'App/Models/Person';
import Dataset from 'App/Models/Dataset'; import Dataset from '#app/Models/Dataset';
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
// node ace make:controller Author // node ace make:controller Author
export default class DatasetController { export default class DatasetController {
public async index({}: HttpContextContract) { public async index({}: HttpContext) {
// select * from gba.persons // 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 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")); // where ("link_documents_persons"."role" = 'author') and ("persons"."id" = "link_documents_persons"."person_id"));
@ -14,7 +14,7 @@ export default class DatasetController {
return datasets; return datasets;
} }
public async findAll({ response }: HttpContextContract) { public async findAll({ response }: HttpContext) {
try { try {
const datasets = await Dataset.query() const datasets = await Dataset.query()
.where('server_state', 'published') .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() const datasets = await Dataset.query()
.where('publish_id', params.publish_id) .where('publish_id', params.publish_id)
.preload('titles') .preload('titles')

View File

@ -1,5 +1,5 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import File from 'App/Models/File'; import File from '#app/Models/File';
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';
@ -7,7 +7,7 @@ import * as path from 'path';
// node ace make:controller Author // node ace make:controller Author
export default class FileController { export default class FileController {
// @Get("download/:id") // @Get("download/:id")
public async findOne({ response, params }: HttpContextContract) { public async findOne({ response, params }: HttpContext) {
const id = params.id; const id = params.id;
const file = await File.findOrFail(id); const file = await File.findOrFail(id);
// const file = await File.findOne({ // const file = await File.findOne({

View File

@ -1,9 +1,9 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import Database from '@ioc:Adonis/Lucid/Database'; import db from '@adonisjs/lucid/services/db';
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
export default class HomeController { export default class HomeController {
public async findDocumentsPerYear({ response, params }: HttpContextContract) { public async findDocumentsPerYear({ response, params }: HttpContext) {
const year = params.year; const year = params.year;
const from = parseInt(year); const from = parseInt(year);
const serverState = 'published'; const serverState = 'published';
@ -17,8 +17,8 @@ export default class HomeController {
// .preload('authors') // .preload('authors')
// .orderBy('server_date_published'); // .orderBy('server_date_published');
const datasets = await Database.from('documents as doc') const datasets = await db.from('documents as doc')
.select(['publish_id', 'server_date_published', Database.raw(`date_part('year', server_date_published) as pub_year`)]) .select(['publish_id', 'server_date_published', db.raw(`date_part('year', server_date_published) as pub_year`)])
.where('server_state', serverState) .where('server_state', serverState)
.innerJoin('link_documents_persons as ba', 'doc.id', 'ba.document_id') .innerJoin('link_documents_persons as ba', 'doc.id', 'ba.document_id')
.andWhereRaw(`date_part('year', server_date_published) = ?`, [from]) .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'; const serverState = 'published';
// Use raw SQL queries to select all cars which belongs to the user // Use raw SQL queries to select all cars which belongs to the user
try { 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 = ?', 'SELECT distinct EXTRACT(YEAR FROM server_date_published) as published_date FROM gba.documents WHERE server_state = ?',
[serverState], [serverState],
); );
// Pluck the ids of the cars // 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 // check if the cars is returned
// if (years.length > 0) { // if (years.length > 0) {
return response.status(StatusCodes.OK).json(years); 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 serverState = 'published';
// const year = params.year; // const year = params.year;
// const from = parseInt(year); // const from = parseInt(year);
@ -70,11 +70,11 @@ export default class HomeController {
const years = [2021, 2022, 2023]; // Add the second year 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([ .select([
Database.raw(`date_part('year', server_date_published) as pub_year`), db.raw(`date_part('year', server_date_published) as pub_year`),
Database.raw(`date_part('month', server_date_published) as pub_month`), db.raw(`date_part('month', server_date_published) as pub_month`),
Database.raw('COUNT(*) as count'), db.raw('COUNT(*) as count'),
]) ])
.where('server_state', serverState) .where('server_state', serverState)
// .innerJoin('link_documents_persons as ba', 'doc.id', 'ba.document_id') // .innerJoin('link_documents_persons as ba', 'doc.id', 'ba.document_id')

View File

@ -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 TotpSecret from 'App/Models/TotpSecret';
import User from 'App/Models/User'; import User from '#app/Models/User';
import TwoFactorAuthProvider from 'App/Services/TwoFactorAuthProvider'; import TwoFactorAuthProvider from '#app/Services/TwoFactorAuthProvider';
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
import { InvalidArgumentException } from 'node-exceptions'; 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 thats enabling 2FA and storing them to our database. // Here we are generating secret and recovery codes for the user thats enabling 2FA and storing them to our database.
export default class UserController { 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; const user = (await User.find(auth.user?.id)) as User;
// await user.load('totp_secret'); // await user.load('totp_secret');
// if (!user.totp_secret) { // if (!user.totp_secret) {

View File

@ -1,16 +1,20 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import User from 'App/Models/User'; import User from '#models/User';
// import Hash from '@ioc:Adonis/Core/Hash'; // import Hash from '@ioc:Adonis/Core/Hash';
// import InvalidCredentialException from 'App/Exceptions/InvalidCredentialException'; // 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 { LoginState } from 'Contracts/enums';
// import { StatusCodes } from 'http-status-codes'; // import { StatusCodes } from 'http-status-codes';
// interface MyHttpsContext extends HttpContext {
// auth: Authenticator<User>
// }
export default class AuthController { export default class AuthController {
// login function // login function{ request, auth, response }:HttpContext
public async login({ request, response, auth, session }: HttpContextContract) { public async login({ request, response, auth, session }: HttpContext) {
// console.log({ // console.log({
// registerBody: request.body(), // registerBody: request.body(),
// }); // });
@ -25,7 +29,9 @@ export default class AuthController {
// // attempt to verify credential and login user // // attempt to verify credential and login user
// await auth.use('web').attempt(email, plainPassword); // 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) { if (user.isTwoFactorEnabled) {
// session.put("login.id", user.id); // session.put("login.id", user.id);
// return view.render("pages/two-factor-challenge"); // return view.render("pages/two-factor-challenge");
@ -38,8 +44,9 @@ export default class AuthController {
// state: state, // state: state,
// new_user_id: user.id, // new_user_id: user.id,
// }); // });
} }
await auth.login(user);
await auth.use('web').login(user);
} catch (error) { } catch (error) {
// if login fails, return vague form message and redirect back // if login fails, return vague form message and redirect back
session.flash('message', 'Your username, email, or password is incorrect'); session.flash('message', 'Your username, email, or password is incorrect');
@ -50,7 +57,7 @@ export default class AuthController {
response.redirect('/apps/dashboard'); 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 { 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', session.get('login.id')).firstOrFail();
const user = await User.query().where('id', 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); const isValid = await TwoFactorAuthProvider.validate(user, code);
if (isValid) { if (isValid) {
// login user and redirect to dashboard // login user and redirect to dashboard
await auth.login(user); await auth.use('web').login(user);
response.redirect('/apps/dashboard'); response.redirect('/apps/dashboard');
} else { } else {
session.flash('message', 'Your tow factor code is incorrect'); session.flash('message', 'Your tow factor code is incorrect');
@ -70,17 +77,17 @@ export default class AuthController {
if (codes.includes(recoveryCode)) { if (codes.includes(recoveryCode)) {
user.twoFactorRecoveryCodes = codes.filter((c) => c !== recoveryCode); user.twoFactorRecoveryCodes = codes.filter((c) => c !== recoveryCode);
await user.save(); await user.save();
await auth.login(user); await auth.use('web').login(user);
response.redirect('/apps/dashboard'); response.redirect('/apps/dashboard');
} }
} }
} }
// logout function // logout function
public async logout({ auth, response }: HttpContextContract) { public async logout({ auth, response }: HttpContext) {
// await auth.logout(); // await auth.logout();
await auth.use('web').logout(); await auth.use('web').logout();
response.redirect('/app/login'); return response.redirect('/app/login');
// return response.status(200); // return response.status(200);
} }
} }

View File

@ -1,9 +1,9 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import User from 'App/Models/User'; import User from '#app/Models/User';
import { RenderResponse } from '@ioc:EidelLev/Inertia'; // import { RenderResponse } from '@ioc:EidelLev/Inertia';
import TwoFactorAuthProvider from 'App/Services/TwoFactorAuthProvider'; import TwoFactorAuthProvider from '#app/Services/TwoFactorAuthProvider';
import Hash from '@ioc:Adonis/Core/Hash'; import hash from '@adonisjs/core/services/hash';
import { schema, rules } from '@ioc:Adonis/Core/Validator'; import { schema, rules } from '@adonisjs/validator';
// Here we are generating secret and recovery codes for the user thats enabling 2FA and storing them to our database. // Here we are generating secret and recovery codes for the user thats enabling 2FA and storing them to our database.
export default class UserController { export default class UserController {
@ -12,7 +12,7 @@ export default class UserController {
* *
* @return \Inertia\Response * @return \Inertia\Response
*/ */
public async accountInfo({ inertia, auth }: HttpContextContract): RenderResponse { public async accountInfo({ inertia, auth }: HttpContext) {
// const user = auth.user; // const user = auth.user;
const user = (await User.find(auth.user?.id)) as User; const user = (await User.find(auth.user?.id)) as User;
// const id = request.param('id'); // 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({ const passwordSchema = schema.create({
old_password: schema.string({ trim: true }, [rules.required()]), old_password: schema.string({ trim: true }, [rules.required()]),
new_password: schema.string({ trim: true }, [rules.minLength(8), rules.maxLength(255), rules.confirmed('confirm_password')]), 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 { try {
const user = await auth.user; const user = await auth.user as User;
const { old_password, new_password } = request.only(['old_password', 'new_password']); const { old_password, new_password } = request.only(['old_password', 'new_password']);
// if (!(old_password && new_password && confirm_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 // 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) { 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 // Hash the new password before updating the user's password
@ -57,7 +57,7 @@ export default class UserController {
await user.save(); await user.save();
// return response.status(200).send({ message: 'Password updated successfully.' }); // 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'); return response.redirect().toRoute('settings.user.index');
} catch (error) { } catch (error) {
// return response.status(500).send({ message: 'Internal server 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: User | undefined = auth?.user;
const user = (await User.find(auth.user?.id)) as 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; const user = auth?.user;
user.twoFactorSecret = null; user.twoFactorSecret = null;

View File

@ -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 { Client } from '@opensearch-project/opensearch';
import User from 'App/Models/User'; import User from '#app/Models/User';
import Dataset from 'App/Models/Dataset'; import Dataset from '#app/Models/Dataset';
import DatasetIdentifier from 'App/Models/DatasetIdentifier'; import DatasetIdentifier from '#app/Models/DatasetIdentifier';
import XmlModel from 'App/Library/XmlModel'; import XmlModel from '#app/Library/XmlModel';
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces'; import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
import { create } from 'xmlbuilder2'; import { create } from 'xmlbuilder2';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { transform } from 'saxon-js'; import SaxonJS from 'saxon-js';
import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm'; import { schema } from '@adonisjs/validator';
import { schema, CustomMessages } from '@ioc:Adonis/Core/Validator';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
import Index from 'App/Library/Utils/Index'; import Index from '#app/Library/Utils/Index';
import { getDomain } from 'App/Utils/utility-functions'; import { getDomain } from '#app/Utils/utility-functions';
import { DoiClient } from 'App/Library/Doi/DoiClient'; import { DoiClient } from '#app/Library/Doi/DoiClient';
import DoiClientException from 'App/Exceptions/DoiClientException'; import DoiClientException from '#app/Exceptions/DoiClientException';
import Logger from '@ioc:Adonis/Core/Logger'; import logger from '@adonisjs/core/services/logger';
import { HttpException } from 'node-exceptions'; 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 // Create a new instance of the client
const client = new Client({ node: 'http://localhost:9200' }); // replace with your OpenSearch endpoint 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({}: 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 user = (await User.find(auth.user?.id)) as User;
const page = request.input('page', 1); const page = request.input('page', 1);
let datasets: ModelQueryBuilderContract<typeof Dataset, Dataset> = Dataset.query(); 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 id = request.param('id');
const dataset = await Dataset.query() const dataset = await Dataset.query()
.where('id', id) .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 = request.param('id');
// const { id } = params; // const { id } = params;
const dataset = await Dataset.findOrFail(id); 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'); const id = request.param('id');
// $dataset = Dataset::with('user:id,login')->findOrFail($id); // $dataset = Dataset::with('user:id,login')->findOrFail($id);
const dataset = await Dataset.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({ const approveDatasetSchema = schema.create({
reviewer_id: schema.number(), 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 id = request.param('id');
const dataset = await Dataset.query() 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({ const publishDatasetSchema = schema.create({
publisher_name: schema.string({ trim: true }), 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 id = request.param('id');
const dataset = await Dataset.query() const dataset = await Dataset.query()
.where('id', id) .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 dataId = request.param('publish_id');
const dataset = await Dataset.query() const dataset = await Dataset.query()
// .preload('xmlCache') // .preload('xmlCache')
@ -338,7 +339,7 @@ export default class DatasetsController {
const index_name = 'tethys-records'; const index_name = 'tethys-records';
await Index.indexDocument(dataset, index_name); await Index.indexDocument(dataset, index_name);
} catch (error) { } 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 // Log the error or handle it as needed
throw new HttpException(error.message); throw new HttpException(error.message);
} }
@ -351,12 +352,12 @@ export default class DatasetsController {
// return response.toRoute('editor.dataset.list').flash('message', xmlMeta); // 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({}: HttpContextContract) {}
public async update({ response }) { public async update({ response }: HttpContext) {
const id = 273; //request.param('id'); const id = 273; //request.param('id');
const dataset = await Dataset.query().preload('xmlCache').where('id', id).firstOrFail(); const dataset = await Dataset.query().preload('xmlCache').where('id', id).firstOrFail();
// add xml elements // add xml elements
@ -374,7 +375,7 @@ export default class DatasetsController {
const xmlString = xml.end({ prettyPrint: false }); const xmlString = xml.end({ prettyPrint: false });
let doc = ''; let doc = '';
try { try {
const result = await transform({ const result = await SaxonJS.transform({
// stylesheetFileName: `${config.TMP_BASE_DIR}/data-quality/rules/iati.sef.json`, // stylesheetFileName: `${config.TMP_BASE_DIR}/data-quality/rules/iati.sef.json`,
stylesheetText: this.proc, stylesheetText: this.proc,
destination: 'serialized', 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) { private async createXmlRecord(dataset: Dataset, datasetNode: XMLBuilder) {
const domNode = await this.getDatasetXmlDomNode(dataset); const domNode = await this.getDatasetXmlDomNode(dataset);

View File

@ -1,27 +1,31 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import { RequestContract } from '@ioc:Adonis/Core/Request'; // import { RequestContract } from '@ioc:Adonis/Core/Request';
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces'; import { Request } from '@adonisjs/core/http';
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
import { create } from 'xmlbuilder2'; import { create } from 'xmlbuilder2';
import dayjs, { Dayjs } from 'dayjs'; import dayjs, { Dayjs } from 'dayjs';
import utc from 'dayjs/plugin/utc'; import utc from 'dayjs/plugin/utc.js';
import timezone from 'dayjs/plugin/timezone'; import timezone from 'dayjs/plugin/timezone.js';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
import { transform } from 'saxon-js'; import SaxonJS from 'saxon-js';
// import { Xslt, xmlParse } from 'xslt-processor' // import { Xslt, xmlParse } from 'xslt-processor'
import { OaiErrorCodes, OaiModelError } from 'App/Exceptions/OaiErrorCodes'; import { OaiErrorCodes, OaiModelError } from '#app/Exceptions/OaiErrorCodes';
import { OaiModelException, BadOaiModelException } from 'App/Exceptions/OaiModelException'; import { OaiModelException, BadOaiModelException } from '#app/Exceptions/OaiModelException';
import Dataset from 'App/Models/Dataset'; import Dataset from '#app/Models/Dataset';
import Collection from 'App/Models/Collection'; import Collection from '#app/Models/Collection';
import { getDomain, preg_match } from 'App/Utils/utility-functions'; import { getDomain, preg_match } from '#app/Utils/utility-functions';
import XmlModel from 'App/Library/XmlModel'; import XmlModel from '#app/Library/XmlModel';
import Logger from '@ioc:Adonis/Core/Logger'; import logger from '@adonisjs/core/services/logger';
import ResumptionToken from 'App/Library/Oai/ResumptionToken'; import ResumptionToken from '#app/Library/Oai/ResumptionToken';
import { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm'; // import Config from '@ioc:Adonis/Core/Config';
import Config from '@ioc:Adonis/Core/Config'; import config from '@adonisjs/core/services/config'
import { inject } from '@adonisjs/fold'; // import { inject } from '@adonisjs/fold';
import { inject } from '@adonisjs/core'
// import { TokenWorkerContract } from "MyApp/Models/TokenWorker"; // 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 { interface XslTParameter {
[key: string]: any; [key: string]: any;
@ -39,7 +43,7 @@ interface ListParameter {
metadataPrefix: string; metadataPrefix: string;
} }
@inject(['App/Library/Oai/TokenWorkerContract']) @inject()
export default class OaiController { export default class OaiController {
private deliveringDocumentStates = ['published', 'deleted']; private deliveringDocumentStates = ['published', 'deleted'];
private sampleRegEx = /^[A-Za-zäüÄÜß0-9\-_.!~]+$/; private sampleRegEx = /^[A-Za-zäüÄÜß0-9\-_.!~]+$/;
@ -53,6 +57,7 @@ export default class OaiController {
private xml: XMLBuilder; private xml: XMLBuilder;
private proc; private proc;
constructor(public tokenWorker: TokenWorkerContract) { constructor(public tokenWorker: TokenWorkerContract) {
// Load the XSLT file // Load the XSLT file
this.proc = readFileSync('public/assets2/datasetxml2oai.sef.json'); this.proc = readFileSync('public/assets2/datasetxml2oai.sef.json');
@ -60,12 +65,12 @@ export default class OaiController {
dayjs.extend(timezone); 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.xml = create({ version: '1.0', encoding: 'UTF-8', standalone: true }, '<root></root>');
// this.proc = new XSLTProcessor(); // this.proc = new XSLTProcessor();
// const stylesheet = readFileSync(__dirname + "/datasetxml2oai.sef.json"); // const stylesheet = readFileSync(__dirname + "/datasetxml2oai.sef.json");
const xsltParameter = (this.xsltParameter = {}); const xsltParameter: XslTParameter = (this.xsltParameter = {});
let oaiRequest: Dictionary = {}; let oaiRequest: Dictionary = {};
if (request.method() === 'POST') { if (request.method() === 'POST') {
@ -106,7 +111,7 @@ export default class OaiController {
let xmlOutput; // = xmlString; let xmlOutput; // = xmlString;
try { try {
const result = await transform({ const result = await SaxonJS.transform({
// stylesheetFileName: `${config.TMP_BASE_DIR}/data-quality/rules/iati.sef.json`, // stylesheetFileName: `${config.TMP_BASE_DIR}/data-quality/rules/iati.sef.json`,
stylesheetText: this.proc, stylesheetText: this.proc,
destination: 'serialized', destination: 'serialized',
@ -130,7 +135,7 @@ export default class OaiController {
response.status(StatusCodes.OK).send(xmlOutput); response.status(StatusCodes.OK).send(xmlOutput);
} }
protected async handleRequest(oaiRequest: Dictionary, request: RequestContract) { protected async handleRequest(oaiRequest: Dictionary, request: Request) {
// Setup stylesheet // Setup stylesheet
// $this->loadStyleSheet('datasetxml2oai-pmh.xslt'); // $this->loadStyleSheet('datasetxml2oai-pmh.xslt');
@ -258,14 +263,14 @@ export default class OaiController {
protected async handleListIdentifiers(oaiRequest: Dictionary) { protected async handleListIdentifiers(oaiRequest: Dictionary) {
!this.tokenWorker.isConnected && (await this.tokenWorker.connect()); !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); await this.handleLists(oaiRequest, maxIdentifier);
} }
protected async handleListRecords(oaiRequest) { protected async handleListRecords(oaiRequest: Dictionary) {
!this.tokenWorker.isConnected && (await this.tokenWorker.connect()); !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); 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 resParam = oaiRequest['resumptionToken']; //e.g. "158886496600000"
const token = await this.tokenWorker.get(resParam); const token = await this.tokenWorker.get(resParam);
@ -352,7 +357,7 @@ export default class OaiController {
this.xsltParameter['oai_metadataPrefix'] = numWrapper.metadataPrefix; this.xsltParameter['oai_metadataPrefix'] = numWrapper.metadataPrefix;
} }
private async handleNoResumptionToken(oaiRequest: Dictionary, numWrapper) { private async handleNoResumptionToken(oaiRequest: Dictionary, numWrapper: ListParameter) {
// no resumptionToken is given // no resumptionToken is given
if ('metadataPrefix' in oaiRequest) { if ('metadataPrefix' in oaiRequest) {
numWrapper.metadataPrefix = oaiRequest['metadataPrefix']; numWrapper.metadataPrefix = oaiRequest['metadataPrefix'];
@ -622,7 +627,7 @@ export default class OaiController {
const msg = `Invalid SetSpec (data-type='${dataset.type}'). const msg = `Invalid SetSpec (data-type='${dataset.type}').
Allowed characters are [${this.sampleRegEx}].`; Allowed characters are [${this.sampleRegEx}].`;
// Log::error("OAI-PMH: $msg"); // Log::error("OAI-PMH: $msg");
Logger.error(`OAI-PMH: ${msg}`); logger.error(`OAI-PMH: ${msg}`);
return; return;
} }
const setSpec = 'data-type:' + dataset.type; const setSpec = 'data-type:' + dataset.type;

View File

@ -1,14 +1,19 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import User from 'App/Models/User'; import User from '#app/Models/User';
import Dataset from 'App/Models/Dataset'; import Dataset from '#app/Models/Dataset';
import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm'; import Field from '#app/Library/Field';
import Field from 'App/Library/Field'; import BaseModel from '#app/Models/BaseModel';
import BaseModel from 'App/Models/BaseModel';
import { DateTime } from 'luxon'; 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 { 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 user = (await User.find(auth.user?.id)) as User;
const page = request.input('page', 1); const page = request.input('page', 1);
let datasets: ModelQueryBuilderContract<typeof Dataset, Dataset> = Dataset.query(); 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 id = request.param('id');
const dataset = await Dataset.query() const dataset = await Dataset.query()
.where('id', id) .where('id', id)
@ -79,7 +84,7 @@ export default class DatasetsController {
} }
const fieldnames: Array<string> = await dataset.describe(); const fieldnames: Array<string> = await dataset.describe();
const fields = {}; const fields: Dictionary = {};
for (const fieldName of fieldnames) { for (const fieldName of fieldnames) {
const field: Field = dataset.getField(fieldName) as Field; const field: Field = dataset.getField(fieldName) as Field;
const modelClass = field.getValueModelClass(); 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 = request.param('id');
// const { id } = params; // const { id } = params;
const dataset = await Dataset.findOrFail(id); 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 id = request.param('id');
const dataset = await Dataset.query() const dataset = await Dataset.query()
.where('id', id) .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 id = request.param('id');
const dataset = await Dataset.query() const dataset = await Dataset.query()
.where('id', id) .where('id', id)

View File

@ -1,21 +1,22 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import User from 'App/Models/User'; import User from '#app/Models/User';
import Dataset from 'App/Models/Dataset'; import Dataset from '#app/Models/Dataset';
import License from 'App/Models/License'; import License from '#app/Models/License';
import Project from 'App/Models/Project'; import Project from '#app/Models/Project';
import Title from 'App/Models/Title'; import Title from '#app/Models/Title';
import Description from 'App/Models/Description'; import Description from '#app/Models/Description';
import Language from 'App/Models/Language'; import Language from '#app/Models/Language';
import Coverage from 'App/Models/Coverage'; import Coverage from '#app/Models/Coverage';
import Collection from 'App/Models/Collection'; import Collection from '#app/Models/Collection';
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator'; import { schema, rules } from '@adonisjs/validator';
import { CustomMessages } from "@adonisjs/validator/types";
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import Person from 'App/Models/Person'; import Person from '#app/Models/Person';
import Database from '@ioc:Adonis/Lucid/Database'; import db from '@adonisjs/lucid/services/db';
import { TransactionClientContract } from '@ioc:Adonis/Lucid/Database'; import { TransactionClientContract } from "@adonisjs/lucid/types/database";
import Subject from 'App/Models/Subject'; import Subject from '#app/Models/Subject';
import CreateDatasetValidator from 'App/Validators/CreateDatasetValidator'; import CreateDatasetValidator from '#app/Validators/CreateDatasetValidator';
import UpdateDatasetValidator from 'App/Validators/UpdateDatasetValidator'; import UpdateDatasetValidator from '#app/Validators/UpdateDatasetValidator';
import { import {
TitleTypes, TitleTypes,
DescriptionTypes, DescriptionTypes,
@ -25,20 +26,24 @@ import {
RelationTypes, RelationTypes,
DatasetTypes, DatasetTypes,
SubjectTypes, SubjectTypes,
} from 'Contracts/enums'; } from '#contracts/enums';
import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm'; import { ModelQueryBuilderContract } from "@adonisjs/lucid/types/model";
import DatasetReference from 'App/Models/DatasetReference'; import DatasetReference from '#app/Models/DatasetReference';
import { cuid } from '@ioc:Adonis/Core/Helpers'; import { cuid } from '@adonisjs/core/helpers';
import File from 'App/Models/File'; import File from '#app/Models/File';
import ClamScan from 'clamscan'; import ClamScan from 'clamscan';
import { ValidationException } from '@ioc:Adonis/Core/Validator'; import { ValidationException } from '@adonisjs/validator';
import Drive from '@ioc:Adonis/Core/Drive'; // import Drive from '@ioc:Adonis/Core/Drive';
import { Exception } from '@adonisjs/core/build/standalone'; import { Exception } from "@adonisjs/core/exceptions";
import { MultipartFileContract } from '@ioc:Adonis/Core/BodyParser'; import { MultipartFile } from '@adonisjs/core/types/bodyparser';
import * as crypto from 'crypto'; import * as crypto from 'crypto';
import app from '@adonisjs/core/services/app';
interface Dictionary {
[index: string]: string;
}
export default class DatasetController { 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 user = (await User.find(auth.user?.id)) as User;
const page = request.input('page', 1); const page = request.input('page', 1);
let datasets: ModelQueryBuilderContract<typeof Dataset, Dataset> = Dataset.query(); 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 licenses = await License.query().select('id', 'name_long').where('active', 'true').pluck('name_long', 'id');
const projects = await Project.query().pluck('label', '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({ const newDatasetSchema = schema.create({
language: schema.string({ trim: true }, [ language: schema.string({ trim: true }, [
rules.regex(/^[a-zA-Z0-9-_]+$/), //Must be alphanumeric with hyphens or underscores 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')]), rights: schema.string([rules.equalTo('true')]),
}); });
await request.validate({ schema: newDatasetSchema, messages: this.messages });
try { try {
// Step 2 - Validate request body against the schema // Step 2 - Validate request body against the schema
@ -162,7 +168,7 @@ export default class DatasetController {
return response.redirect().back(); return response.redirect().back();
} }
public async secondStep({ request, response }: HttpContextContract) { public async secondStep({ request, response }: HttpContext) {
const newDatasetSchema = schema.create({ const newDatasetSchema = schema.create({
// first step // first step
language: schema.string({ trim: true }, [ language: schema.string({ trim: true }, [
@ -217,7 +223,7 @@ export default class DatasetController {
return response.redirect().back(); return response.redirect().back();
} }
public async thirdStep({ request, response }: HttpContextContract) { public async thirdStep({ request, response }: HttpContext) {
const newDatasetSchema = schema.create({ const newDatasetSchema = schema.create({
// first step // first step
language: schema.string({ trim: true }, [ language: schema.string({ trim: true }, [
@ -305,7 +311,7 @@ export default class DatasetController {
return response.redirect().back(); 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 // node ace make:validator CreateDataset
try { try {
// Step 2 - Validate request body against the schema // Step 2 - Validate request body against the schema
@ -320,7 +326,7 @@ export default class DatasetController {
let trx: TransactionClientContract | null = null; let trx: TransactionClientContract | null = null;
try { try {
trx = await Database.transaction(); trx = await db.transaction();
const user = (await User.find(auth.user?.id)) as User; const user = (await User.find(auth.user?.id)) as User;
await this.createDatasetAndAssociations(user, request, trx); await this.createDatasetAndAssociations(user, request, trx);
@ -341,7 +347,7 @@ export default class DatasetController {
// return response.redirect().back(); // 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: // Create a new instance of the Dataset model:
const dataset = new Dataset(); const dataset = new Dataset();
dataset.type = request.input('type'); dataset.type = request.input('type');
@ -422,7 +428,7 @@ export default class DatasetController {
} }
// save data files // save data files
const uploadedFiles = request.files('files'); const uploadedFiles: MultipartFile[] = request.files('files');
for (const [index, file] of uploadedFiles.entries()) { for (const [index, file] of uploadedFiles.entries()) {
try { try {
await this.scanFileForViruses(file.tmpPath); //, 'gitea.lan', 3310); 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 mimeType = file.headers['content-type'] || 'application/octet-stream'; // Fallback to a default MIME type
const datasetFolder = `files/${dataset.id}`; const datasetFolder = `files/${dataset.id}`;
// const size = file.size; // const size = file.size;
await file.moveToDisk( await file.move(
datasetFolder, app.makePath( datasetFolder),
{ {
name: fileName, name: fileName,
overwrite: true, // overwrite in case of conflict overwrite: true, // overwrite in case of conflict
}, },
'local',
); );
// save file metadata into db // save file metadata into db
const newFile = new File(); const newFile = new File();
@ -476,7 +481,7 @@ export default class DatasetController {
return `file-${randomString1}-${randomString2}-${randomString3}-${randomString4}-${randomString5}.${extension}`; 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 clamscan = await (new ClamScan().init());
const opts: ClamScan.Options = { const opts: ClamScan.Options = {
removeInfected: true, // If true, removes infected files 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 // Helper function to extract pivot attributes from a person object
private extractPivotAttributes(person: any) { private extractPivotAttributes(person: any) {
const pivotAttributes = {}; const pivotAttributes: Dictionary = {};
for (const key in person) { for (const key in person) {
if (key.startsWith('pivot_')) { if (key.startsWith('pivot_')) {
// pivotAttributes[key] = person[key]; // pivotAttributes[key] = person[key];
@ -596,7 +601,7 @@ export default class DatasetController {
}; };
// public async release({ params, view }) { // 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 id = request.param('id');
const dataset = await Dataset.query() 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 id = request.param('id');
const dataset = await Dataset.query().preload('files').where('id', id).firstOrFail(); const dataset = await Dataset.query().preload('files').where('id', id).firstOrFail();
@ -655,7 +660,10 @@ export default class DatasetController {
}); });
try { try {
await request.validate({ schema: newSchema }); await request.validate({
schema: newSchema,
// reporter: validator.reporters.vanilla,
});
} catch (error) { } catch (error) {
// return response.badRequest(error.messages); // return response.badRequest(error.messages);
throw error; throw error;
@ -698,7 +706,7 @@ export default class DatasetController {
// throw new GeneralException(trans('exceptions.publish.release.update_error')); // 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 id = request.param('id');
const datasetQuery = Dataset.query().where('id', id); const datasetQuery = Dataset.query().where('id', id);
datasetQuery datasetQuery
@ -789,7 +797,7 @@ export default class DatasetController {
}); });
} }
public async update({ request, response, session }: HttpContextContract) { public async update({ request, response, session }: HttpContext) {
try { try {
// await request.validate({ schema: newDatasetSchema, messages: this.messages }); // await request.validate({ schema: newDatasetSchema, messages: this.messages });
await request.validate(UpdateDatasetValidator); await request.validate(UpdateDatasetValidator);
@ -804,7 +812,7 @@ export default class DatasetController {
let trx: TransactionClientContract | null = null; let trx: TransactionClientContract | null = null;
try { try {
trx = await Database.transaction(); trx = await db.transaction();
// const user = (await User.find(auth.user?.id)) as User; // const user = (await User.find(auth.user?.id)) as User;
// await this.createDatasetAndAssociations(user, request, trx); // await this.createDatasetAndAssociations(user, request, trx);
const dataset = await Dataset.findOrFail(id); const dataset = await Dataset.findOrFail(id);
@ -897,7 +905,7 @@ export default class DatasetController {
} }
// handle new uploaded files: // handle new uploaded files:
const uploadedFiles: MultipartFileContract[] = request.files('files'); const uploadedFiles: MultipartFile[] = request.files('files');
if (Array.isArray(uploadedFiles) && uploadedFiles.length > 0) { if (Array.isArray(uploadedFiles) && uploadedFiles.length > 0) {
for (const [index, fileData] of uploadedFiles.entries()) { for (const [index, fileData] of uploadedFiles.entries()) {
try { try {
@ -911,7 +919,11 @@ export default class DatasetController {
// move to disk: // move to disk:
const fileName = `file-${cuid()}.${fileData.extname}`; const fileName = `file-${cuid()}.${fileData.extname}`;
const datasetFolder = `files/${dataset.id}`; 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; // let path = coverImage.filePath;
//save to db: //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'); const id = request.param('id');
try { try {
const dataset = await Dataset.query() 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 { try {
const dataset = await Dataset.query().where('id', params.id).preload('files').firstOrFail(); const dataset = await Dataset.query().where('id', params.id).preload('files').firstOrFail();
@ -1041,7 +1053,7 @@ export default class DatasetController {
if (folderContents.length === 0) { if (folderContents.length === 0) {
await Drive.delete(datasetFolder); await Drive.delete(datasetFolder);
} }
// delete dataset wirh relation from db // delete dataset wirh relation in db
await dataset.delete(); await dataset.delete();
session.flash({ message: 'You have deleted 1 dataset!' }); session.flash({ message: 'You have deleted 1 dataset!' });
return response.redirect().toRoute('dataset.list'); return response.redirect().toRoute('dataset.list');
@ -1059,7 +1071,7 @@ export default class DatasetController {
} else if (error instanceof Exception) { } else if (error instanceof Exception) {
// General exception handling // General exception handling
return response return response
.flash({ errors: { error: error.message } }) .flash('errors', { error: error.message })
.redirect() .redirect()
.back(); .back();
} else { } else {

View File

@ -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 User from 'App/Models/User';
// import Dataset from 'App/Models/Dataset'; // import Dataset from 'App/Models/Dataset';
// import License from 'App/Models/License'; // 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 Collection from 'App/Models/Collection';
// import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator'; // import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
// import dayjs from 'dayjs'; // import dayjs from 'dayjs';
import Person from 'App/Models/Person'; import Person from '#app/Models/Person';
import { ModelQueryBuilderContract } from "@adonisjs/lucid/types/model";
import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm';
export default class PersonController { 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 user = (await User.find(auth.user?.id)) as User;
const page = request.input('page', 1); const page = request.input('page', 1);
let persons: ModelQueryBuilderContract<typeof Person, Person> = Person.query(); let persons: ModelQueryBuilderContract<typeof Person, Person> = Person.query();

View File

@ -12,24 +12,53 @@
| properly. | 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'; export default class HttpExceptionHandler extends ExceptionHandler {
import Logger from '@ioc:Adonis/Core/Logger'; /**
import HttpExceptionHandler from '@ioc:Adonis/Core/HttpExceptionHandler'; * 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 = { * Status pages are used to display a custom HTML pages for certain error
'401,403': 'errors/unauthorized', * codes. You might want to enable them in production only, but feel
'404': 'errors/not-found', * free to enable them in development as well.
'500..599': 'errors/server-error', */
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() { // constructor() {
super(Logger); // super(logger);
} // }
public async handle(error: any, ctx: HttpContextContract) { public async handle(error: any, ctx: HttpContext) {
const { response, request, inertia } = ctx; const { response, request, session } = ctx;
/** /**
* Handle failed authentication attempt * Handle failed authentication attempt
@ -44,11 +73,16 @@ export default class ExceptionHandler extends HttpExceptionHandler {
// } // }
// https://github.com/inertiajs/inertia-laravel/issues/56 // https://github.com/inertiajs/inertia-laravel/issues/56
if (request.header('X-Inertia') && [500, 503, 404, 403, 401].includes(response.getStatus())) { // let test = response.getStatus(); //200
return inertia.render('Error', { // let header = request.header('X-Inertia'); // true
status: response.getStatus(), if (request.header('X-Inertia') && [500, 503, 404, 403, 401, 200].includes(response.getStatus())) {
message: error.message, // 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) // ->toResponse($request)
// ->setStatusCode($response->status()); // ->setStatusCode($response->status());
} }
@ -58,4 +92,14 @@ export default class ExceptionHandler extends HttpExceptionHandler {
*/ */
return super.handle(error, ctx); 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);
}
} }

View File

@ -1,5 +1,5 @@
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
import HTTPException from './HttpException'; import HTTPException from './HttpException.js';
class InternalServerErrorException extends HTTPException { class InternalServerErrorException extends HTTPException {
constructor(message?: string) { constructor(message?: string) {

View File

@ -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 * Unable to find user
*/ */
public static invalidUid() { 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; return error;
} }
/** /**
* Invalid user password * Invalid user password
*/ */
public static invalidPassword() { 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; return error;
} }
/** /**
* Flash error message and redirect the user back * Flash error message and redirect the user back
*/ */
private respondWithRedirect(error, ctx) { private respondWithRedirect(error: any, ctx: HttpContext) {
// if (!ctx.session) { // if (!ctx.session) {
// return ctx.response.status(this.status).send(this.responseText); // return ctx.response.status(this.status).send(this.responseText);
// } // }
@ -59,7 +60,7 @@ export default class InvalidCredentialException extends Exception {
* Handle this exception by itself * Handle this exception by itself
*/ */
public handle(error, ctx) { public handle(error: any, ctx: HttpContext) {
// return response.status(403).view.render("errors/unauthorized", { // return response.status(403).view.render("errors/unauthorized", {
// error: error, // error: error,
// }); // });

View File

@ -1,6 +1,6 @@
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
// import HTTPException from './HttpException'; // import HTTPException from './HttpException';
import { OaiErrorCodes } from './OaiErrorCodes'; import { OaiErrorCodes } from './OaiErrorCodes.js';
export class ErrorCode { export class ErrorCode {
public static readonly Unauthenticated = 'Unauthenticated'; public static readonly Unauthenticated = 'Unauthenticated';

View File

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

View File

@ -1,11 +1,12 @@
// import { Client } from 'guzzle'; // import { Client } from 'guzzle';
// import { Log } from '@adonisjs/core/build/standalone'; // import { Log } from '@adonisjs/core/build/standalone';
// import { DoiInterface } from './interfaces/DoiInterface'; // import { DoiInterface } from './interfaces/DoiInterface';
import DoiClientContract from 'App/Library/Doi/DoiClientContract'; import DoiClientContract from '#app/Library/Doi/DoiClientContract';
import DoiClientException from 'App/Exceptions/DoiClientException'; import DoiClientException from '#app/Exceptions/DoiClientException';
import { StatusCodes } from 'http-status-codes'; import { StatusCodes } from 'http-status-codes';
import Logger from '@ioc:Adonis/Core/Logger'; import logger from '@adonisjs/core/services/logger';
import axios, { AxiosResponse } from 'axios'; import { AxiosResponse } from 'axios';
import axios from 'axios';
export class DoiClient implements DoiClientContract { export class DoiClient implements DoiClientContract {
public username: string; public username: string;
@ -22,7 +23,7 @@ export class DoiClient implements DoiClientContract {
if (this.username === '' || this.password === '' || this.serviceUrl === '') { if (this.username === '' || this.password === '' || this.serviceUrl === '') {
const message = 'issing configuration settings to properly initialize DOI client'; const message = 'issing configuration settings to properly initialize DOI client';
Logger.error(message); logger.error(message);
throw new DoiClientException(StatusCodes.BAD_REQUEST, message); throw new DoiClientException(StatusCodes.BAD_REQUEST, message);
} }
} }
@ -49,7 +50,7 @@ export class DoiClient implements DoiClientContract {
'Content-Type': 'application/xml;charset=UTF-8', 'Content-Type': 'application/xml;charset=UTF-8',
}; };
try { 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 // Response Codes
// 201 Created: operation successful // 201 Created: operation successful
@ -60,11 +61,11 @@ export class DoiClient implements DoiClientContract {
// let test = metadataResponse.data; // 'OK (10.21388/TETHYS.213)' // let test = metadataResponse.data; // 'OK (10.21388/TETHYS.213)'
if (metadataResponse.status !== 201) { if (metadataResponse.status !== 201) {
const message = `Unexpected DataCite MDS response code ${metadataResponse.status}`; const message = `Unexpected DataCite MDS response code ${metadataResponse.status}`;
Logger.error(message); logger.error(message);
throw new DoiClientException(metadataResponse.status, 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, auth,
headers, headers,
}); });
@ -77,7 +78,7 @@ export class DoiClient implements DoiClientContract {
// 412 Precondition failed: metadata must be uploaded first. // 412 Precondition failed: metadata must be uploaded first.
if (doiResponse.status !== 201) { if (doiResponse.status !== 201) {
const message = `Unexpected DataCite MDS response code ${doiResponse.status}`; const message = `Unexpected DataCite MDS response code ${doiResponse.status}`;
Logger.error(message); logger.error(message);
throw new DoiClientException(doiResponse.status, message); throw new DoiClientException(doiResponse.status, message);
} }
@ -85,7 +86,7 @@ export class DoiClient implements DoiClientContract {
} catch (error) { } catch (error) {
// const message = `request for registering DOI failed with ${error.message}`; // const message = `request for registering DOI failed with ${error.message}`;
// Handle the error, log it, or rethrow as needed // 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); throw new DoiClientException(error.response.status, error.response.data);
} }
} }

View File

@ -1,4 +1,5 @@
// import ResumptionToken from './ResumptionToken'; // import ResumptionToken from './ResumptionToken';
import { AxiosResponse } from 'axios';
export default interface DoiClientContract { export default interface DoiClientContract {
username: string; username: string;
@ -6,7 +7,7 @@ export default interface DoiClientContract {
serviceUrl: string; serviceUrl: string;
// prefix: string; // prefix: string;
// base_domain: 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>; // get(key: string): Promise<ResumptionToken | null>;
// set(token: ResumptionToken): Promise<string>; // set(token: ResumptionToken): Promise<string>;
} }

View File

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

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

View File

@ -1,9 +1,9 @@
import ResumptionToken from './ResumptionToken'; import ResumptionToken from './ResumptionToken.js';
import { createClient, RedisClientType } from 'redis'; import { createClient, RedisClientType } from 'redis';
import InternalServerErrorException from 'App/Exceptions/InternalServerException'; import InternalServerErrorException from '#app/Exceptions/InternalServerException';
import { sprintf } from 'sprintf-js'; import { sprintf } from 'sprintf-js';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import TokenWorkerContract from './TokenWorker'; import TokenWorkerContract from './TokenWorkerContract.js';
export default class TokenWorkerService implements TokenWorkerContract { export default class TokenWorkerService implements TokenWorkerContract {
protected filePrefix = 'rs_'; protected filePrefix = 'rs_';

View File

@ -1,8 +1,8 @@
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces'; import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
import { create } from 'xmlbuilder2'; import { create } from 'xmlbuilder2';
import Dataset from 'App/Models/Dataset'; import Dataset from '#app/Models/Dataset';
import Field from './Field'; import Field from './Field.js';
import BaseModel from 'App/Models/BaseModel'; import BaseModel from '#app/Models/BaseModel';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
export default class Strategy { export default class Strategy {
@ -10,7 +10,7 @@ export default class Strategy {
private config; private config;
private xml: XMLBuilder; private xml: XMLBuilder;
constructor(config) { constructor(config: any) {
this.version = 1.0; this.version = 1.0;
this.config = config; this.config = config;
} }
@ -45,11 +45,11 @@ export default class Strategy {
for (const fieldname of fieldsDiff) { for (const fieldname of fieldsDiff) {
const field = model.getField(fieldname); 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(); const modelClass = field.getValueModelClass();
let fieldValues = field.getValue(); let fieldValues = field.getValue();
@ -107,7 +107,7 @@ export default class Strategy {
childNode.att('Timezone', zoneName); childNode.att('Timezone', zoneName);
} }
private mapModelAttributes(myObject, childNode: XMLBuilder) { private mapModelAttributes(myObject: any, childNode: XMLBuilder) {
Object.keys(myObject).forEach((prop) => { Object.keys(myObject).forEach((prop) => {
let value = myObject[prop]; let value = myObject[prop];
// console.log(`${prop}: ${value}`); // console.log(`${prop}: ${value}`);
@ -161,7 +161,7 @@ export default class Strategy {
return fieldValues?.toString().trim(); return fieldValues?.toString().trim();
} }
private createModelNode(model) { private createModelNode(model: Dataset) {
const className = 'Rdr_' + model.constructor.name.split('\\').pop(); //Rdr_Dataset const className = 'Rdr_' + model.constructor.name.split('\\').pop(); //Rdr_Dataset
// return dom.createElement(className); // return dom.createElement(className);
return this.xml.root().ele(className); return this.xml.root().ele(className);

View File

@ -1,18 +1,20 @@
import Dataset from 'App/Models/Dataset'; import Dataset from '#app/Models/Dataset';
import { Client } from '@opensearch-project/opensearch'; import { Client } from '@opensearch-project/opensearch';
import { create } from 'xmlbuilder2'; import { create } from 'xmlbuilder2';
import { transform } from 'saxon-js'; import SaxonJS from 'saxon-js';
import XmlModel from 'App/Library/XmlModel'; import XmlModel from '#app/Library/XmlModel';
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces'; import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
import Logger from '@ioc:Adonis/Core/Logger'; import logger from '@adonisjs/core/services/logger';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
// import Config from '@ioc:Adonis/Core/Config'; // 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 opensearchNode = process.env.OPENSEARCH_HOST || 'localhost';
// const client = new Client({ node: `http://${opensearchNode}` }); // replace with your OpenSearch endpoint // const client = new Client({ node: `http://${opensearchNode}` }); // replace with your OpenSearch endpoint
interface XslTParameter {
[key: string]: any;
}
export default { export default {
// opensearchNode: process.env.OPENSEARCH_HOST || 'localhost', // opensearchNode: process.env.OPENSEARCH_HOST || 'localhost',
client: new Client({ node: `http://${process.env.OPENSEARCH_HOST || 'localhost'}` }), // replace with your OpenSearch endpoint 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> { async getDoiRegisterString(dataset: Dataset): Promise<string | undefined> {
try { try {
const proc = readFileSync('public/assets2/doi_datacite.sef.json'); 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>'); let xml = create({ version: '1.0', encoding: 'UTF-8', standalone: true }, '<root></root>');
const datasetNode = xml.root().ele('Dataset'); const datasetNode = xml.root().ele('Dataset');
await createXmlRecord(dataset, datasetNode); await createXmlRecord(dataset, datasetNode);
@ -50,7 +52,7 @@ export default {
let xmlOutput; // = xmlString; let xmlOutput; // = xmlString;
try { try {
const result = await transform({ const result = await SaxonJS.transform({
// stylesheetFileName: `${config.TMP_BASE_DIR}/data-quality/rules/iati.sef.json`, // stylesheetFileName: `${config.TMP_BASE_DIR}/data-quality/rules/iati.sef.json`,
stylesheetText: proc, stylesheetText: proc,
destination: 'serialized', destination: 'serialized',
@ -61,12 +63,12 @@ export default {
}); });
xmlOutput = result.principalResult; xmlOutput = result.principalResult;
} catch (error) { } 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; return xmlOutput;
} catch (error) { } 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, body: document,
refresh: true, 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) { } 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>'); let xml = create({ version: '1.0', encoding: 'UTF-8', standalone: true }, '<root></root>');
const datasetNode = xml.root().ele('Dataset'); const datasetNode = xml.root().ele('Dataset');
await createXmlRecord(dataset, datasetNode); await createXmlRecord(dataset, datasetNode);
const xmlString = xml.end({ prettyPrint: false }); const xmlString = xml.end({ prettyPrint: false });
try { try {
const result = await transform({ const result = await SaxonJS.transform({
stylesheetText: proc, stylesheetText: proc,
destination: 'serialized', destination: 'serialized',
sourceText: xmlString, sourceText: xmlString,
}); });
return result.principalResult; return result.principalResult;
} catch (error) { } 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 ''; return '';
} }
}, },

View File

@ -1,7 +1,7 @@
import DocumentXmlCache from 'App/Models/DocumentXmlCache'; import DocumentXmlCache from '#app/Models/DocumentXmlCache';
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces'; import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
import Dataset from 'App/Models/Dataset'; import Dataset from '#app/Models/Dataset';
import Strategy from './Strategy'; import Strategy from './Strategy.js';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
import { builder } from 'xmlbuilder2'; import { builder } from 'xmlbuilder2';

View File

@ -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();
}
}

View File

@ -1,13 +1,14 @@
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import { HttpContext } from '@adonisjs/core/http';
import Config from '@ioc:Adonis/Core/Config'; // import Config from '@ioc:Adonis/Core/Config';
import Database from '@ioc:Adonis/Lucid/Database'; import config from '@adonisjs/core/services/config';
import User from 'App/Models/User'; import db from '@adonisjs/lucid/services/db';
import { Exception } from '@adonisjs/core/build/standalone'; import User from '#app/Models/User';
import { Exception } from '@adonisjs/core/exceptions';
const permissionTable = Config.get('rolePermission.permission_table', 'permissions'); const permissionTable = config.get('rolePermission.permission_table', 'permissions');
const rolePermissionTable = Config.get('rolePermission.role_permission_table', 'role_has_permissions'); const rolePermissionTable = config.get('rolePermission.role_permission_table', 'role_has_permissions');
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', 'link_accounts_roles');
/** /**
* Permission authentication to check if user has any of the specified permissions * Permission authentication to check if user has any of the specified permissions
@ -18,7 +19,7 @@ export default class Can {
/** /**
* Handle request * 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 * Check if user is logged-in
*/ */
@ -31,9 +32,10 @@ export default class Can {
// return response.unauthorized({ // return response.unauthorized({
// error: `Doesn't have required role(s): ${permissionNames.join(',')}`, // 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> { private async checkHasPermissions(user: User, permissionNames: Array<string>): Promise<boolean> {
@ -66,7 +68,7 @@ export default class Can {
rows: { rows: {
0: { permissioncount }, 0: { permissioncount },
}, },
} = await Database.rawQuery( } = await db.rawQuery(
'SELECT count("p"."name") as permissionCount FROM ' + 'SELECT count("p"."name") as permissionCount FROM ' +
roleTable + roleTable +
' r INNER JOIN ' + ' r INNER JOIN ' +

View File

@ -1,11 +1,12 @@
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import { HttpContext } from '@adonisjs/core/http';
import Config from '@ioc:Adonis/Core/Config'; // import Config from '@ioc:Adonis/Core/Config';
import Database from '@ioc:Adonis/Lucid/Database'; import config from '@adonisjs/core/services/config'
import User from 'App/Models/User'; import db from '@adonisjs/lucid/services/db';
import User from '#app/Models/User';
// import { Exception } from '@adonisjs/core/build/standalone' // import { Exception } from '@adonisjs/core/build/standalone'
const roleTable = Config.get('rolePermission.role_table', 'roles'); const roleTable = config.get('rolePermission.role_table', 'roles');
const userRoleTable = Config.get('rolePermission.user_role_table', 'user_roles'); const userRoleTable = config.get('rolePermission.user_role_table', 'user_roles');
/** /**
* Role authentication to check if user has any of the specified roles * Role authentication to check if user has any of the specified roles
@ -16,7 +17,7 @@ export default class Is {
/** /**
* Handle request * 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. * Check if user is logged-in or not.
*/ */
@ -33,7 +34,8 @@ export default class Is {
// 401, // 401,
// "E_INVALID_AUTH_UID"); // "E_INVALID_AUTH_UID");
} }
await next(); // await next();
return next()
} }
private async checkHasRoles(user: User, roleNames: Array<string>): Promise<boolean> { private async checkHasRoles(user: User, roleNames: Array<string>): Promise<boolean> {
@ -46,7 +48,7 @@ export default class Is {
0: { 0: {
0: { roleCount }, 0: { roleCount },
}, },
} = await Database.rawQuery( } = await db.rawQuery(
'SELECT count(`ur`.`id`) as roleCount FROM ' + 'SELECT count(`ur`.`id`) as roleCount FROM ' +
userRoleTable + userRoleTable +
' ur INNER JOIN ' + ' ur INNER JOIN ' +

View File

@ -1,23 +1,25 @@
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import Database from '@ioc:Adonis/Lucid/Database'; import db from '@adonisjs/lucid/services/db';
import Config from '@ioc:Adonis/Core/Config'; import config from '@adonisjs/core/services/config';
import User from 'app/Models/User'; import User from '#app/Models/User';
import { Exception } from '@adonisjs/core/build/standalone'; import { Exception } from '@adonisjs/core/exceptions';
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 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 // node ace make:middleware role
export default class Role { export default class Role {
// .middleware(['auth', 'role:admin,moderator']) // .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. // Check if user is logged-in or not.
// let expression = ""; // let expression = "";
// if (Array.isArray(args)) { // if (Array.isArray(args)) {
// expression = args.join(" || "); // expression = args.join(" || ");
// } // }
let user = await auth.user; let user = auth.user as User;
if (!user) { if (!user) {
return response.unauthorized({ error: 'Must be logged in' }); 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): ${userRoles.join(',')}`,
// // error: `Doesn't have required role(s)`, // // 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 // code for middleware goes here. ABOVE THE NEXT CALL
@ -62,7 +64,7 @@ export default class Role {
rows: { rows: {
0: { rolecount }, 0: { rolecount },
}, },
} = await Database.rawQuery( } = await db.rawQuery(
'SELECT count("r"."id") as roleCount FROM ' + 'SELECT count("r"."id") as roleCount FROM ' +
roleTable + roleTable +
' r INNER JOIN ' + ' r INNER JOIN ' +

View File

@ -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 * Silent auth middleware can be used as a global middleware to silent check
@ -10,7 +10,7 @@ export default class SilentAuthMiddleware {
/** /**
* Handle request * 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 * 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. * set to the instance of the currently logged in user.

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

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

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

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

View File

@ -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'; // import { ManyToManyQueryClient } from '@ioc:Adonis/Lucid/Orm';
// export class CustomManyToManyQueryClient extends ManyToManyQueryClient { // export class CustomManyToManyQueryClient extends ManyToManyQueryClient {
@ -29,6 +29,8 @@ export default class BaseModel extends LucidBaseModel {
*/ */
// private fillInvoked: boolean = false; // private fillInvoked: boolean = false;
[key: string]: any;
public static fillable: string[] = []; public static fillable: string[] = [];
public fill(attributes: any, allowExtraProperties: boolean = false): this { public fill(attributes: any, allowExtraProperties: boolean = false): this {
@ -47,7 +49,7 @@ export default class BaseModel extends LucidBaseModel {
// this.fillInvoked = true; // this.fillInvoked = true;
return this; return this;
} }
/** /**
* Merge bulk attributes with existing attributes. * Merge bulk attributes with existing attributes.
* *
@ -118,6 +120,8 @@ export default class BaseModel extends LucidBaseModel {
} }
} }
// export class DatasetRelatedBaseModel extends LucidBaseModel { // export class DatasetRelatedBaseModel extends LucidBaseModel {
// public dataset: BelongsTo<typeof Dataset>; // public dataset: BelongsTo<typeof Dataset>;
// } // }

View File

@ -1,7 +1,9 @@
import { column, SnakeCaseNamingStrategy, manyToMany, ManyToMany, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm'; import { column, SnakeCaseNamingStrategy, manyToMany, belongsTo } from '@adonisjs/lucid/orm';
import Dataset from './Dataset'; import Dataset from './Dataset.js';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
import CollectionRole from './CollectionRole'; 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 { export default class Collection extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();

View File

@ -1,6 +1,7 @@
import { column, SnakeCaseNamingStrategy, hasMany, HasMany } from '@ioc:Adonis/Lucid/Orm'; import { column, SnakeCaseNamingStrategy, hasMany } from '@adonisjs/lucid/orm';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
import Collection from './Collection'; import Collection from './Collection.js';
import type { HasMany } from "@adonisjs/lucid/types/relations";
export default class CollectionRole extends BaseModel { export default class CollectionRole extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();

View File

@ -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 { DateTime } from 'luxon';
import Dataset from './Dataset'; import Dataset from './Dataset.js';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
export default class Coverage extends BaseModel { export default class Coverage extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();

View File

@ -2,31 +2,31 @@ import {
column, column,
SnakeCaseNamingStrategy, SnakeCaseNamingStrategy,
manyToMany, manyToMany,
ManyToMany,
belongsTo, belongsTo,
BelongsTo,
hasMany, hasMany,
HasMany,
computed, computed,
hasOne, hasOne
HasOne, } from '@adonisjs/lucid/orm';
} from '@ioc:Adonis/Lucid/Orm';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import Person from './Person'; import Person from './Person.js';
import User from './User'; import User from './User.js';
import Title from './Title'; import Title from './Title.js';
import Description from './Description'; import Description from './Description.js';
import License from './License'; import License from './License.js';
import Subject from './Subject'; import Subject from './Subject.js';
import File from './File'; import File from './File.js';
import Coverage from './Coverage'; import Coverage from './Coverage.js';
import DatasetReference from './DatasetReference'; import DatasetReference from './DatasetReference.js';
import Collection from './Collection'; import Collection from './Collection.js';
import DatasetIdentifier from './DatasetIdentifier'; import DatasetIdentifier from './DatasetIdentifier.js';
import Project from './Project'; import Project from './Project.js';
import DocumentXmlCache from './DocumentXmlCache'; import DocumentXmlCache from './DocumentXmlCache.js';
import DatasetExtension from 'App/Models/Traits/DatasetExtension'; // Adjust the import path 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 { export default class Dataset extends DatasetExtension {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();

View File

@ -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 { DateTime } from 'luxon';
import Dataset from './Dataset'; import Dataset from './Dataset.js';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
export default class DatasetIdentifier extends BaseModel { export default class DatasetIdentifier extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();

View File

@ -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 { DateTime } from 'luxon';
import Dataset from './Dataset'; import Dataset from './Dataset.js';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
export default class DatasetReference extends BaseModel { export default class DatasetReference extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();

View File

@ -1,6 +1,7 @@
import { column, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm'; import { column, belongsTo } from '@adonisjs/lucid/orm';
import Dataset from './Dataset'; import Dataset from './Dataset.js';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
export default class Description extends BaseModel { export default class Description extends BaseModel {
public static primaryKey = 'id'; public static primaryKey = 'id';

View File

@ -1,9 +1,10 @@
import { column, BaseModel, SnakeCaseNamingStrategy, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm'; import { column, BaseModel, SnakeCaseNamingStrategy, belongsTo } from '@adonisjs/lucid/orm';
import Dataset from './Dataset'; import Dataset from './Dataset.js';
import { builder, create } from 'xmlbuilder2'; import { builder, create } from 'xmlbuilder2';
import { XMLBuilder } from 'xmlbuilder2/lib/interfaces'; import { XMLBuilder } from 'xmlbuilder2/lib/interfaces.js';
import Database from '@ioc:Adonis/Lucid/Database'; import db from '@adonisjs/lucid/services/db';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
export default class DocumentXmlCache extends BaseModel { export default class DocumentXmlCache extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); 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 // Assuming 'DocumentXmlCache' has a table with a 'server_date_modified' column in your database
public static async hasValidEntry(datasetId: number, datasetServerDateModified: DateTime): Promise<boolean> { 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 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('document_id', datasetId)
.where('server_date_modified', '>=', serverDateModifiedString) // Check if server_date_modified is newer or equal .where('server_date_modified', '>=', serverDateModifiedString) // Check if server_date_modified is newer or equal
.first(); .first();

View File

@ -1,13 +1,22 @@
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
import { column, hasMany, HasMany, belongsTo, BelongsTo, SnakeCaseNamingStrategy, computed } from '@ioc:Adonis/Lucid/Orm'; import { column, hasMany, belongsTo, SnakeCaseNamingStrategy, computed } from '@adonisjs/lucid/orm';
import HashValue from './HashValue'; import HashValue from './HashValue.js';
import Dataset from './Dataset'; import Dataset from './Dataset.js';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
// import { Buffer } from 'buffer'; // import { Buffer } from 'buffer';
import * as fs from 'fs'; import * as fs from 'fs';
import crypto from 'crypto'; 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 { export default class File extends BaseModel {
// private readonly _data: Uint8Array; // private readonly _data: Uint8Array;
@ -162,7 +171,7 @@ export default class File extends BaseModel {
await super.delete(); 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) => { return new Promise((resolve, reject) => {
const hash = crypto.createHash(hashName); const hash = crypto.createHash(hashName);
const stream = fs.createReadStream(path); const stream = fs.createReadStream(path);

View File

@ -1,5 +1,6 @@
import { column, BaseModel, belongsTo, BelongsTo, SnakeCaseNamingStrategy } from '@ioc:Adonis/Lucid/Orm'; import { column, BaseModel, belongsTo, SnakeCaseNamingStrategy } from '@adonisjs/lucid/orm';
import File from './File'; import File from './File.js';
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
export default class HashValue extends BaseModel { export default class HashValue extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();

View File

@ -1,5 +1,5 @@
import { column, SnakeCaseNamingStrategy } from '@ioc:Adonis/Lucid/Orm'; import { column, SnakeCaseNamingStrategy } from '@adonisjs/lucid/orm';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
// import { DateTime } from 'luxon'; // import { DateTime } from 'luxon';
export default class Language extends BaseModel { export default class Language extends BaseModel {

View File

@ -1,5 +1,5 @@
import { column, SnakeCaseNamingStrategy } from '@ioc:Adonis/Lucid/Orm'; import { column, SnakeCaseNamingStrategy } from '@adonisjs/lucid/orm';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
export default class License extends BaseModel { export default class License extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();

View File

@ -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 { DateTime } from 'luxon';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import Role from 'App/Models/Role'; import Role from '#app/Models/Role';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
import type { ManyToMany } from "@adonisjs/lucid/types/relations";
export default class Permission extends BaseModel { export default class Permission extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();
@ -44,12 +45,12 @@ export default class Permission extends BaseModel {
}) })
public updated_at: DateTime; public updated_at: DateTime;
@beforeCreate() // @beforeCreate()
@beforeUpdate() // @beforeUpdate()
public static async resetDate(role) { // public static async resetDate(role) {
role.created_at = this.formatDateTime(role.created_at); // role.created_at = this.formatDateTime(role.created_at);
role.updated_at = this.formatDateTime(role.updated_at); // role.updated_at = this.formatDateTime(role.updated_at);
} // }
// public static boot() { // public static boot() {
// super.boot() // super.boot()
@ -64,22 +65,22 @@ export default class Permission extends BaseModel {
// }) // })
// } // }
private static formatDateTime(datetime) { // private static formatDateTime(datetime) {
let value = new Date(datetime); // let value = new Date(datetime);
return datetime // return datetime
? value.getFullYear() + // ? value.getFullYear() +
'-' + // '-' +
(value.getMonth() + 1) + // (value.getMonth() + 1) +
'-' + // '-' +
value.getDate() + // value.getDate() +
' ' + // ' ' +
value.getHours() + // value.getHours() +
':' + // ':' +
value.getMinutes() + // value.getMinutes() +
':' + // ':' +
value.getSeconds() // value.getSeconds()
: datetime; // : datetime;
} // }
// @belongsTo(() => Role) // @belongsTo(() => Role)
// public role: BelongsTo<typeof Role>; // public role: BelongsTo<typeof Role>;

View File

@ -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 { DateTime } from 'luxon';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import Dataset from './Dataset'; import Dataset from './Dataset.js';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
import type { ManyToMany } from "@adonisjs/lucid/types/relations";
export default class Person extends BaseModel { export default class Person extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();

View File

@ -1,6 +1,6 @@
import { column, SnakeCaseNamingStrategy } from '@ioc:Adonis/Lucid/Orm'; import { column, SnakeCaseNamingStrategy } from '@adonisjs/lucid/orm';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
export default class Project extends BaseModel { export default class Project extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();

View File

@ -1,10 +1,11 @@
import { column, SnakeCaseNamingStrategy, manyToMany, ManyToMany, beforeCreate, beforeUpdate } from '@ioc:Adonis/Lucid/Orm'; import { column, SnakeCaseNamingStrategy, manyToMany, beforeCreate, beforeUpdate } from '@adonisjs/lucid/orm';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
// import moment from 'moment'; // import moment from 'moment';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import User from './User'; import User from './User.js';
import Permission from 'App/Models/Permission'; import Permission from '#app/Models/Permission';
import type { ManyToMany } from "@adonisjs/lucid/types/relations";
export default class Role extends BaseModel { export default class Role extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();
@ -46,7 +47,7 @@ export default class Role extends BaseModel {
@beforeCreate() @beforeCreate()
@beforeUpdate() @beforeUpdate()
public static async resetDate(role) { public static async resetDate(role: Role) {
role.created_at = this.formatDateTime(role.created_at); role.created_at = this.formatDateTime(role.created_at);
role.updated_at = this.formatDateTime(role.updated_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); let value = new Date(datetime);
return datetime return datetime
? value.getFullYear() + ? value.getFullYear() +

View File

@ -1,9 +1,10 @@
import { column, SnakeCaseNamingStrategy, manyToMany, ManyToMany, computed} from '@ioc:Adonis/Lucid/Orm'; import { column, SnakeCaseNamingStrategy, manyToMany, computed} from '@adonisjs/lucid/orm';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
import dayjs from 'dayjs'; 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 { export default class Subject extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();

View File

@ -1,6 +1,8 @@
import { column, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm'; import { column, belongsTo } from '@adonisjs/lucid/orm';
import Dataset from './Dataset'; import Dataset from './Dataset.js';
import BaseModel from './BaseModel'; import BaseModel from './BaseModel.js';
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
// import { DatasetRelatedBaseModel } from './BaseModel'; // import { DatasetRelatedBaseModel } from './BaseModel';
export default class Title extends BaseModel { export default class Title extends BaseModel {

View File

@ -1,8 +1,10 @@
import { column, BaseModel, SnakeCaseNamingStrategy, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm'; import { column, BaseModel, SnakeCaseNamingStrategy, belongsTo } from '@adonisjs/lucid/orm';
import User from './User'; import User from './User.js';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
import dayjs from 'dayjs'; 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 { export default class TotpSecret extends BaseModel {
public static namingStrategy = new SnakeCaseNamingStrategy(); public static namingStrategy = new SnakeCaseNamingStrategy();
@ -21,16 +23,16 @@ export default class TotpSecret extends BaseModel {
// public twoFactorSecret: string; // public twoFactorSecret: string;
@column({ @column({
serializeAs: null, serializeAs: null,
consume: (value: string) => (value ? JSON.parse(Encryption.decrypt(value) ?? '{}') : null), consume: (value: string) => (value ? JSON.parse(encryption.decrypt(value) ?? '{}') : null),
prepare: (value: string) => Encryption.encrypt(JSON.stringify(value)), prepare: (value: string) => encryption.encrypt(JSON.stringify(value)),
}) })
public twoFactorSecret?: string | null; public twoFactorSecret?: string | null;
// serializeAs: null removes the model properties from the serialized output. // serializeAs: null removes the model properties from the serialized output.
@column({ @column({
serializeAs: null, serializeAs: null,
consume: (value: string) => (value ? JSON.parse(Encryption.decrypt(value) ?? '[]') : []), consume: (value: string) => (value ? JSON.parse(encryption.decrypt(value) ?? '[]') : []),
prepare: (value: string[]) => Encryption.encrypt(JSON.stringify(value)), prepare: (value: string[]) => encryption.encrypt(JSON.stringify(value)),
}) })
public twoFactorRecoveryCodes?: string[] | null; public twoFactorRecoveryCodes?: string[] | null;

View File

@ -1,15 +1,15 @@
import Title from 'App/Models/Title'; import Title from '#app/Models/Title';
import Description from 'App/Models/Description'; import Description from '#app/Models/Description';
import License from 'App/Models/License'; import License from '#app/Models/License';
import Person from 'App/Models/Person'; import Person from '#app/Models/Person';
import DatasetReference from 'App/Models/DatasetReference'; import DatasetReference from '#app/Models/DatasetReference';
import DatasetIdentifier from 'App/Models/DatasetIdentifier'; import DatasetIdentifier from '#app/Models/DatasetIdentifier';
import Subject from 'App/Models/Subject'; import Subject from '#app/Models/Subject';
import File from 'App/Models/File'; import File from '#app/Models/File';
import Coverage from 'App/Models/Coverage'; import Coverage from '#app/Models/Coverage';
import Collection from 'App/Models/Collection'; import Collection from '#app/Models/Collection';
import { BaseModel as LucidBaseModel } from '@ioc:Adonis/Lucid/Orm'; import { BaseModel as LucidBaseModel } from '@adonisjs/lucid/orm';
import Field from 'App/Library/Field'; import Field from '#app/Library/Field';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
// @StaticImplements<LucidModel>() // @StaticImplements<LucidModel>()
@ -31,11 +31,12 @@ export type DatasetRelatedModel =
| typeof File; | typeof File;
export default abstract class DatasetExtension extends LucidBaseModel { export default abstract class DatasetExtension extends LucidBaseModel {
public abstract id; public abstract id: number;
public externalFields: Record<string, any> = this.getExternalFields(); public externalFields: Record<string, any> = this.getExternalFields();
// which fields shoud#t be published // which fields shoud#t be published
protected internalFields: Record<string, any> = {}; protected internalFields: Record<string, any> = {};
protected fields: Record<string, any> = {}; protected fields: Record<string, any> = {};
[key: string]: any;
private getExternalFields(): Record<string, any> { private getExternalFields(): Record<string, any> {
// External fields definition // External fields definition

View File

@ -1,13 +1,25 @@
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
import { column, beforeSave, manyToMany, ManyToMany, hasMany, HasMany } from '@ioc:Adonis/Lucid/Orm'; import { withAuthFinder } from '@adonisjs/auth';
import Hash from '@ioc:Adonis/Core/Hash'; import { column, beforeSave, manyToMany, hasMany } from '@adonisjs/lucid/orm';
import Role from './Role'; import hash from '@adonisjs/core/services/hash';
import Database from '@ioc:Adonis/Lucid/Database'; import Role from './Role.js';
import Config from '@ioc:Adonis/Core/Config'; import db from '@adonisjs/lucid/services/db';
import Dataset from './Dataset'; // import Config from '@ioc:Adonis/Core/Config';
import BaseModel from './BaseModel'; import config from '@adonisjs/core/services/config';
import Encryption from '@ioc:Adonis/Core/Encryption'; import Dataset from './Dataset.js';
import { TotpState } from 'Contracts/enums'; 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'; // import TotpSecret from './TotpSecret';
// export default interface IUser { // export default interface IUser {
@ -20,13 +32,14 @@ import { TotpState } from 'Contracts/enums';
// // async (user): Promise<void>; // // async (user): Promise<void>;
// } // }
const permissionTable = Config.get('rolePermission.permission_table', 'permissions'); // const permissionTable = config.get('rolePermission.permission_table', 'permissions');
const rolePermissionTable = Config.get('rolePermission.role_permission_table', 'role_has_permissions'); // const rolePermissionTable = config.get('rolePermission.role_permission_table', 'role_has_permissions');
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', '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'; public static table = 'accounts';
@column({ isPrimary: true }) @column({ isPrimary: true })
@ -50,16 +63,16 @@ export default class User extends BaseModel {
// serializeAs: null removes the model properties from the serialized output. // serializeAs: null removes the model properties from the serialized output.
@column({ @column({
serializeAs: null, serializeAs: null,
consume: (value: string) => (value ? JSON.parse(Encryption.decrypt(value) ?? '{}') : null), consume: (value: string) => (value ? JSON.parse(encryption.decrypt(value) ?? '{}') : null),
prepare: (value: string) => Encryption.encrypt(JSON.stringify(value)), prepare: (value: string) => encryption.encrypt(JSON.stringify(value)),
}) })
public twoFactorSecret?: string | null; public twoFactorSecret?: string | null;
// serializeAs: null removes the model properties from the serialized output. // serializeAs: null removes the model properties from the serialized output.
@column({ @column({
serializeAs: null, serializeAs: null,
consume: (value: string) => (value ? JSON.parse(Encryption.decrypt(value) ?? '[]') : []), consume: (value: string) => (value ? JSON.parse(encryption.decrypt(value) ?? '[]') : []),
prepare: (value: string[]) => Encryption.encrypt(JSON.stringify(value)), prepare: (value: string[]) => encryption.encrypt(JSON.stringify(value)),
}) })
public twoFactorRecoveryCodes?: string[] | null; public twoFactorRecoveryCodes?: string[] | null;
@ -72,14 +85,14 @@ export default class User extends BaseModel {
// public totp_secret: HasOne<typeof TotpSecret>; // public totp_secret: HasOne<typeof TotpSecret>;
@beforeSave() @beforeSave()
public static async hashPassword(user) { public static async hashPassword(user: User) {
if (user.$dirty.password) { if (user.$dirty.password) {
user.password = await Hash.make(user.password); user.password = await hash.use('laravel').make(user.password);
} }
} }
public get isTwoFactorEnabled(): boolean { public get isTwoFactorEnabled(): boolean {
return Boolean(this?.twoFactorSecret && this.state == TotpState.STATE_ENABLED); return Boolean(this?.twoFactorSecret && this.state == TotpState.STATE_ENABLED);
// return Boolean(this.totp_secret?.twoFactorSecret); // return Boolean(this.totp_secret?.twoFactorSecret);
} }
@ -109,6 +122,12 @@ export default class User extends BaseModel {
} }
private async checkHasPermissions(user: User, permissionNames: Array<string>): Promise<boolean> { 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 permissionPlaceHolder = '(';
let placeholders = new Array(permissionNames.length).fill('?'); let placeholders = new Array(permissionNames.length).fill('?');
permissionPlaceHolder += placeholders.join(','); permissionPlaceHolder += placeholders.join(',');
@ -118,7 +137,7 @@ export default class User extends BaseModel {
rows: { rows: {
0: { permissioncount }, 0: { permissioncount },
}, },
} = await Database.rawQuery( } = await db.rawQuery(
'SELECT count("p"."name") as permissionCount FROM ' + 'SELECT count("p"."name") as permissionCount FROM ' +
roleTable + roleTable +
' r INNER JOIN ' + ' r INNER JOIN ' +

View File

@ -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 User from '#app/Models/User';
import Role from 'App/Models/Role'; import Role from '#app/Models/Role';
import { DateTime } from 'luxon'; import { DateTime } from 'luxon';
import type { BelongsTo } from "@adonisjs/lucid/types/relations";
// import moment from 'moment' // import moment from 'moment'
export default class UserRole extends BaseModel { 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); let value = new Date(datetime);
return datetime return datetime
? value.getFullYear() + ? value.getFullYear() +

View File

@ -1,19 +1,18 @@
import Database, { // import db from '@adonisjs/lucid/services/db';
// DatabaseQueryBuilderContract, // // import Config from '@ioc:Adonis/Core/Config';
QueryClientContract, // import config from '@adonisjs/core/services/config';
TransactionClientContract, // import { QueryClientContract } from "@adonisjs/lucid/types/database";
} from '@ioc:Adonis/Lucid/Database'; // import { TransactionClientContract } from "@adonisjs/lucid/types/database";
import Config from '@ioc:Adonis/Core/Config';
export function getUserRoles(userId: number, trx?: TransactionClientContract): Promise<Array<string>> { // export function getUserRoles(userId: number, trx?: TransactionClientContract): Promise<Array<string>> {
const { userRole } = Config.get('acl.joinTables'); // const { userRole } = config.get('acl.joinTables');
return ((trx || Database) as QueryClientContract | TransactionClientContract) // return ((trx || db) as QueryClientContract | TransactionClientContract)
.query() // .query()
.from('roles') // .from('roles')
.distinct('roles.slug') // .distinct('roles.slug')
.leftJoin(userRole, `${userRole}.role_id`, 'roles.id') // .leftJoin(userRole, `${userRole}.role_id`, 'roles.id')
.where(`${userRole}.user_id`, userId) // .where(`${userRole}.user_id`, userId)
.then((res) => { // .then((res) => {
return res.map((r) => r.slug); // return res.map((r) => r.slug);
}); // });
} // }

View File

@ -1,10 +1,11 @@
import Config from '@ioc:Adonis/Core/Config'; // import Config from '@ioc:Adonis/Core/Config';
import User from 'App/Models/User'; import config from '@adonisjs/core/services/config'
import { generateSecret, verifyToken } from 'node-2fa/dist/index'; import User from '#app/Models/User';
import { generateSecret, verifyToken } from 'node-2fa/dist/index.js';
// import cryptoRandomString from 'crypto-random-string'; // import cryptoRandomString from 'crypto-random-string';
import QRCode from 'qrcode'; import QRCode from 'qrcode';
import crypto from 'crypto'; import crypto from 'crypto';
import { TotpState } from 'Contracts/enums'; import { TotpState } from '#contracts/enums';
// npm install node-2fa --save // npm install node-2fa --save
// npm install crypto-random-string --save // npm install crypto-random-string --save
@ -13,7 +14,7 @@ import { TotpState } from 'Contracts/enums';
// npm i --save-dev @types/qrcode // npm i --save-dev @types/qrcode
class TwoFactorAuthProvider { 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. * generateSecret will generate a user-specific 32-character secret.

View File

@ -1,8 +1,9 @@
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator'; import { schema, rules } from '@adonisjs/validator';
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import { CustomMessages } from "@adonisjs/validator/types";
export default class AuthValidator { export default class AuthValidator {
constructor(protected ctx: HttpContextContract) {} constructor(protected ctx: HttpContext) {}
/* /*
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data. * Define schema to validate the "shape", "type", "formatting" and "integrity" of data.

View File

@ -1,10 +1,11 @@
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator'; import { schema, rules } from '@adonisjs/validator';
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import dayjs from 'dayjs'; 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 { export default class CreateDatasetValidator {
constructor(protected ctx: HttpContextContract) {} constructor(protected ctx: HttpContext) {}
/* /*
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data. * 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( files: schema.array([rules.minLength(1)]).members(
schema.file({ schema.file({
size: '100mb', size: '512mb',
extnames: ['jpg', 'gif', 'png', 'tif', 'pdf'], extnames: ['jpg', 'gif', 'png', 'tif', 'pdf', 'zip', 'fgb', 'nc', 'qml', 'ovr', 'gpkg', 'gml', 'gpx', 'kml', 'kmz', 'json'],
}), }),
), ),
// upload: schema.object().members({ // upload: schema.object().members({

View File

@ -1,8 +1,9 @@
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator'; import { schema, rules } from '@adonisjs/validator';
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import { CustomMessages } from "@adonisjs/validator/types";
export default class CreateRoleValidator { export default class CreateRoleValidator {
constructor(protected ctx: HttpContextContract) {} constructor(protected ctx: HttpContext) {}
/* /*
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data. * Define schema to validate the "shape", "type", "formatting" and "integrity" of data.

View File

@ -1,8 +1,9 @@
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator'; import { schema, rules } from '@adonisjs/validator';
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import { CustomMessages } from "@adonisjs/validator/types";
export default class CreateUserValidator { export default class CreateUserValidator {
constructor(protected ctx: HttpContextContract) {} constructor(protected ctx: HttpContext) {}
/* /*
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data. * Define schema to validate the "shape", "type", "formatting" and "integrity" of data.

View File

@ -1,10 +1,11 @@
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator'; import { schema, rules } from '@adonisjs/validator';
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import dayjs from 'dayjs'; 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 { export default class UpdateDatasetValidator {
constructor(protected ctx: HttpContextContract) {} constructor(protected ctx: HttpContext) {}
/* /*
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data. * Define schema to validate the "shape", "type", "formatting" and "integrity" of data.

View File

@ -1,12 +1,14 @@
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator'; import { schema, rules } from '@adonisjs/validator';
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import { CustomMessages } from "@adonisjs/validator/types";
// import { Request } from '@adonisjs/core/build/standalone'; // import { Request } from '@adonisjs/core/build/standalone';
export default class UpdateRoleValidator { export default class UpdateRoleValidator {
protected ctx: HttpContextContract; protected ctx: HttpContext;
public schema; public schema;
constructor(ctx: HttpContextContract) { constructor(ctx: HttpContext) {
this.ctx = ctx; this.ctx = ctx;
this.schema = this.createSchema(); this.schema = this.createSchema();
} }

View File

@ -1,12 +1,14 @@
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator'; import { schema, rules } from '@adonisjs/validator';
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'; import type { HttpContext } from '@adonisjs/core/http';
import { CustomMessages } from "@adonisjs/validator/types";
// import { Request } from '@adonisjs/core/build/standalone'; // import { Request } from '@adonisjs/core/build/standalone';
export default class UpdateUserValidator { export default class UpdateUserValidator {
protected ctx: HttpContextContract; protected ctx: HttpContext;
public schema; public schema;
constructor(ctx: HttpContextContract) { constructor(ctx: HttpContext) {
this.ctx = ctx; this.ctx = ctx;
this.schema = this.createSchema(); this.schema = this.createSchema();
} }

47
bin/console.ts Normal file
View 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
View 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
View 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)
})

View File

@ -1,44 +1,34 @@
import { BaseCommand, flags } from '@adonisjs/core/build/standalone';
// import Logger from '@ioc:Adonis/Core/Logger'; // 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 { create } from 'xmlbuilder2';
import Dataset from 'App/Models/Dataset'; import Dataset from '#app/Models/Dataset';
import XmlModel from 'App/Library/XmlModel'; import XmlModel from '#app/Library/XmlModel';
import { readFileSync } from 'fs'; import { readFileSync } from 'fs';
import { transform } from 'saxon-js'; import SaxonJS from 'saxon-js';
import { Client } from '@opensearch-project/opensearch'; 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 opensearchNode = process.env.OPENSEARCH_HOST || 'localhost';
const client = new Client({ node: `http://${opensearchNode}` }); // replace with your OpenSearch endpoint const client = new Client({ node: `http://${opensearchNode}` }); // replace with your OpenSearch endpoint
export default class IndexDatasets extends BaseCommand { export default class IndexDatasets extends BaseCommand {
public static commandName = 'index:datasets'; static commandName = 'index:datasets';
public static description = 'Index datasets based on publish_id'; static description = 'Index datasets based on publish_id';
@flags.number({ alias: 'p' }) @flags.number({ alias: 'p' })
public publish_id: number; public publish_id: number;
public static settings = { static options: CommandOptions = {
/**
* 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, loadApp: true,
staysAlive: false,
/**
* 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,
}; };
public async run() { async run() {
this.logger.info('Hello world!'); this.logger.info('Hello world!');
// const { default: Dataset } = await import('App/Models/Dataset'); const { default: Dataset } = await import('#app/Models/Dataset');
const datasets = await this.getDatasets(); const datasets = await Dataset.query().where('server_state', 'published').exec(); //this.getDatasets();
const proc = readFileSync('public/assets2/solr.sef.json'); const proc = readFileSync('public/assets2/solr.sef.json');
const index_name = 'tethys-records'; const index_name = 'tethys-records';
@ -50,13 +40,15 @@ export default class IndexDatasets extends BaseCommand {
} }
} }
private async getDatasets(): Promise<Dataset[]> { // private async getDatasets(): Promise<any[]> {
const query = Dataset.query().preload('xmlCache').where('server_state', 'published'); // // const { default: Dataset } = await import('#app/Models/Dataset');
if (this.publish_id) { // // const Dataset = (await import('#app/Models/Dataset')).default
query.where('publish_id', this.publish_id); // const query = Dataset.query().where('server_state', 'published');
} // if (this.publish_id) {
return await query; // query.where('publish_id', this.publish_id);
} // }
// return await query;
// }
private async indexDocument(dataset: Dataset, index_name: string, proc: Buffer): Promise<void> { private async indexDocument(dataset: Dataset, index_name: string, proc: Buffer): Promise<void> {
try { 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>'); let xml = create({ version: '1.0', encoding: 'UTF-8', standalone: true }, '<root></root>');
const datasetNode = xml.root().ele('Dataset'); const datasetNode = xml.root().ele('Dataset');
await this.createXmlRecord(dataset, datasetNode); await this.createXmlRecord(dataset, datasetNode);
const xmlString = xml.end({ prettyPrint: false }); const xmlString = xml.end({ prettyPrint: false });
try { try {
const result = await transform({ const result = await SaxonJS.transform({
stylesheetText: proc, stylesheetText: proc,
destination: 'serialized', destination: 'serialized',
sourceText: xmlString, sourceText: xmlString,

View File

@ -1,8 +1,9 @@
import { BaseCommand } from '@adonisjs/core/build/standalone';
import crypto from 'crypto'; import crypto from 'crypto';
import fs from 'fs'; import fs from 'fs';
// import Config from '@ioc:Adonis/Core/Config'; // 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 { export default class ValidateChecksum extends BaseCommand {
/** /**
@ -14,26 +15,14 @@ export default class ValidateChecksum extends BaseCommand {
* Command description is displayed in the "help" output * Command description is displayed in the "help" output
*/ */
public static description = ''; public static description = '';
static options: CommandOptions = {
public static settings = { loadApp: true,
/** staysAlive: false,
* 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,
};
public async run() { public async run() {
// this.logger.info('Hello world!') // 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'))); // const { default: HashValue } = await (await (import ('App/Models/HashValue')));
// query all published files from database: // query all published files from database:
@ -55,21 +44,21 @@ export default class ValidateChecksum extends BaseCommand {
calculatedMd5FileHash = await this.checksumFile(filePath, 'md5'); calculatedMd5FileHash = await this.checksumFile(filePath, 'md5');
} catch (exception) { } catch (exception) {
// this.logger.error(exception.message); // this.logger.error(exception.message);
Logger.error(exception.message); logger.error(exception.message);
continue; continue;
} }
if (hashValue['md5'] === calculatedMd5FileHash) { 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 { } else {
Logger.error( logger.error(
`File id ${file.id}: stored md5 checksum: ${calculatedMd5FileHash}, control md5 checksum: ${hashValue['md5']}`, `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) => { return new Promise((resolve, reject) => {
const hash = crypto.createHash(hashName); const hash = crypto.createHash(hashName);
const stream = fs.createReadStream(path); const stream = fs.createReadStream(path);

View File

@ -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
View 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"')
}
}

View File

@ -6,13 +6,14 @@
*/ */
import proxyAddr from 'proxy-addr'; import proxyAddr from 'proxy-addr';
import Env from '@ioc:Adonis/Core/Env'; import env from '#start/env';
import Application from '@ioc:Adonis/Core/Application'; // import app from '@adonisjs/core/services/app';
import type { ServerConfig } from '@ioc:Adonis/Core/Server'; // import type { ProfilerConfig } from '@ioc:Adonis/Core/Profiler';
import type { LoggerConfig } from '@ioc:Adonis/Core/Logger'; // import type { AssetsManagerConfig } from '@ioc:Adonis/Core/AssetsManager';
import type { ProfilerConfig } from '@ioc:Adonis/Core/Profiler'; // import { ServerConfig } from "@adonisjs/core/services/server";
import type { ValidatorConfig } from '@ioc:Adonis/Core/Validator'; // import { LoggerConfig } from "@adonisjs/core/types/logger";
import type { AssetsManagerConfig } from '@ioc:Adonis/Core/AssetsManager'; 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. | 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. | the config properties to make keep server secure.
| |
*/ */
export const http: ServerConfig = { export const http = defineConfig({
/* /*
|--------------------------------------------------------------------------
| 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,
},
};
/*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| 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 = { subdomainOffset: 2,
/*
|--------------------------------------------------------------------------
| 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'),
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Toggle logger | Request Ids
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| Enable or disable logger application wide | Setting this value to `true` will generate a unique request id for each
| | HTTP request and set it as `x-request-id` header.
*/ |
enabled: true, */
generateRequestId: false,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Logging level | Trusting proxy servers
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The level from which you want the logger to flush logs. It is recommended | Define the proxy servers that AdonisJs must trust for reading `X-Forwarded`
| to make use of the environment variable, so that you can define log levels | headers.
| at deployment level and not code level. |
| */
*/ trustProxy: proxyAddr.compile('loopback'),
level: Env.get('LOG_LEVEL', 'info'),
redact: { /*
paths: ['password', '*.password'], |--------------------------------------------------------------------------
}, | 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 | Profiler
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
*/ */
export const profiler: ProfilerConfig = { // export const profiler: ProfilerConfig = {
/* // /*
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| Toggle profiler // | Toggle profiler
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| // |
| Enable or disable profiler // | Enable or disable profiler
| // |
*/ // */
enabled: true, // enabled: true,
/* // /*
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| Blacklist actions/row labels // | Blacklist actions/row labels
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| // |
| Define an array of actions or row labels that you want to disable from // | Define an array of actions or row labels that you want to disable from
| getting profiled. // | getting profiled.
| // |
*/ // */
blacklist: [], // blacklist: [],
/* // /*
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| Whitelist actions/row labels // | Whitelist actions/row labels
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| // |
| Define an array of actions or row labels that you want to whitelist for // | Define an array of actions or row labels that you want to whitelist for
| the profiler. When whitelist is defined, then `blacklist` is ignored. // | the profiler. When whitelist is defined, then `blacklist` is ignored.
| // |
*/ // */
whitelist: [], // whitelist: [],
}; // };
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@ -228,52 +173,52 @@ export const validator: ValidatorConfig = {};
| Configure the asset manager you are using to compile the frontend assets | Configure the asset manager you are using to compile the frontend assets
| |
*/ */
export const assets: AssetsManagerConfig = { // export const assets: AssetsManagerConfig = {
/* // /*
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| Driver // | Driver
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| // |
| Currently we only support webpack encore and may introduce more drivers // | Currently we only support webpack encore and may introduce more drivers
| in the future // | in the future
| // |
*/ // */
driver: Env.get('ASSETS_DRIVER'), // driver: env.get('ASSETS_DRIVER'),
/* // /*
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| Public path // | Public path
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| // |
| Directory to search for the "manifest.json" and the "entrypoints.json" // | Directory to search for the "manifest.json" and the "entrypoints.json"
| files // | files
| // |
*/ // */
publicPath: Application.publicPath('assets'), // publicPath: app.publicPath('assets'),
/* // /*
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| Script tag // | Script tag
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| // |
| Define attributes for the entryPointScripts tags // | Define attributes for the entryPointScripts tags
| // |
*/ // */
script: { // script: {
attributes: { // attributes: {
defer: true, // defer: true,
}, // },
}, // },
/* // /*
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| Style tag // | Style tag
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| // |
| Define attributes for the entryPointStyles tags // | Define attributes for the entryPointStyles tags
| // |
*/ // */
style: { // style: {
attributes: {}, // attributes: {},
}, // },
}; // };

View File

@ -1,86 +1,89 @@
/** import { defineConfig } from '@adonisjs/auth';
* Config source: https://git.io/JY0mp import { Authenticators } from '@adonisjs/auth/types';
* import { sessionGuard, sessionUserProvider } from '@adonisjs/auth/session';
* Feel free to let us know via PR, if you find something broken in this config // import User from '#app/Models/User';
* file. // 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>;
/* const authConfig = defineConfig({
|-------------------------------------------------------------------------- default: 'web',
| 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',
guards: { guards: {
/* web: sessionGuard({
|-------------------------------------------------------------------------- useRememberMeTokens: false,
| Web Guard provider: sessionUserProvider({
|-------------------------------------------------------------------------- model: () => import('#app/Models/User'),
| }),
| 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'),
},
},
}, },
}; });
export default authConfig; 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>;
}
}

View File

@ -5,29 +5,31 @@
* file. * 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 | White listed methods
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| HTTP methods for which body parsing must be performed. It is a good practice | HTTP methods for which body parsing must be performed. It is a good practice
| to avoid body parsing for `GET` requests. | to avoid body parsing for `GET` requests.
| |
*/ */
whitelistedMethods: ['POST', 'PUT', 'PATCH', 'DELETE'], whitelistedMethods: ['POST', 'PUT', 'PATCH', 'DELETE'],
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| JSON parser settings | JSON parser settings
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The settings for the JSON parser. The types defines the request content | The settings for the JSON parser. The types defines the request content
| types which gets processed by the JSON parser. | types which gets processed by the JSON parser.
| |
*/ */
json: { json: {
encoding: 'utf-8', encoding: 'utf-8',
limit: '1mb', limit: '1mb',
@ -36,165 +38,166 @@ const bodyParserConfig: BodyParserConfig = {
}, },
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Form parser settings | Form parser settings
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The settings for the `application/x-www-form-urlencoded` parser. The types | The settings for the `application/x-www-form-urlencoded` parser. The types
| defines the request content types which gets processed by the form parser. | defines the request content types which gets processed by the form parser.
| |
*/ */
form: { form: {
encoding: 'utf-8', encoding: 'utf-8',
limit: '1mb', limit: '1mb',
queryString: {}, queryString: {},
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Convert empty strings to null | Convert empty strings to null
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| Convert empty form fields to null. HTML forms results in field string | 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 | value when the field is left blank. This option normalizes all the blank
| field values to "null" | field values to "null"
| |
*/ */
convertEmptyStringsToNull: true, convertEmptyStringsToNull: true,
types: ['application/x-www-form-urlencoded'], types: ['application/x-www-form-urlencoded'],
}, },
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Raw body parser settings | Raw body parser settings
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| Raw body just reads the request body stream as a plain text, which you | 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 | can process by hand. This must be used when request body type is not
| supported by the body parser. | supported by the body parser.
| |
*/ */
raw: { raw: {
encoding: 'utf-8', encoding: 'utf-8',
limit: '1mb', limit: '1mb',
queryString: {}, // queryString: {},
types: ['text/*'], types: ['text/*'],
}, },
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Multipart parser settings | Multipart parser settings
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The settings for the `multipart/form-data` parser. The types defines the | The settings for the `multipart/form-data` parser. The types defines the
| request content types which gets processed by the form parser. | request content types which gets processed by the form parser.
| |
*/ */
multipart: { multipart: {
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Auto process | Auto process
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The auto process option will process uploaded files and writes them to | 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 | the `tmp` folder. You can turn it off and then manually use the stream
| to pipe stream to a different destination. | to pipe stream to a different destination.
| |
| It is recommended to keep `autoProcess=true`. Unless you are processing bigger | It is recommended to keep `autoProcess=true`. Unless you are processing bigger
| file sizes. | file sizes.
| |
*/ */
autoProcess: true, autoProcess: true,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Files to be processed manually | Files to be processed manually
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| You can turn off `autoProcess` for certain routes by defining | You can turn off `autoProcess` for certain routes by defining
| routes inside the following array. | routes inside the following array.
| |
| NOTE: Make sure the route pattern starts with a leading slash. | NOTE: Make sure the route pattern starts with a leading slash.
| |
| Correct | Correct
| ```js | ```js
| /projects/:id/file | /projects/:id/file
| ``` | ```
| |
| Incorrect | Incorrect
| ```js | ```js
| projects/:id/file | projects/:id/file
| ``` | ```
*/ */
processManually: [], processManually: [],
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Temporary file name | Temporary file name
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| When auto processing is on. We will use this method to compute the temporary | 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, | file name. AdonisJs will compute a unique `tmpPath` for you automatically,
| However, you can also define your own custom method. | However, you can also define your own custom method.
| |
*/ */
// tmpFileName () { // tmpFileName () {
// }, // },
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Encoding | Encoding
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| Request body encoding | Request body encoding
| |
*/ */
encoding: 'utf-8', encoding: 'utf-8',
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Convert empty strings to null | Convert empty strings to null
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| Convert empty form fields to null. HTML forms results in field string | 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 | value when the field is left blank. This option normalizes all the blank
| field values to "null" | field values to "null"
| |
*/ */
convertEmptyStringsToNull: true, convertEmptyStringsToNull: true,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Max Fields | Max Fields
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The maximum number of fields allowed in the request body. The field includes | The maximum number of fields allowed in the request body. The field includes
| text inputs and files both. | text inputs and files both.
| |
*/ */
maxFields: 1000, maxFields: 1000,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Request body limit | Request body limit
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The total limit to the multipart body. This includes all request files | The total limit to the multipart body. This includes all request files
| and fields data. | and fields data.
| |
*/ */
limit: '20mb', // limit: '20mb',
limit: env.get('UPLOAD_LIMIT', '513mb'),
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Types | Types
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The types that will be considered and parsed as multipart body. | The types that will be considered and parsed as multipart body.
| |
*/ */
types: ['multipart/form-data'], types: ['multipart/form-data'],
}, },
}; });
export default bodyParserConfig; export default bodyParserConfig;

View File

@ -1,127 +1,120 @@
/** import { defineConfig } from "@adonisjs/cors";
* Config source: https://git.io/JfefC
*
* Feel free to let us know via PR, if you find something broken in this config
* file.
*/
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 = { // You can also use a function that return true or false.
/* // enabled: (request) => request.url().startsWith('/api')
|--------------------------------------------------------------------------
| 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') |--------------------------------------------------------------------------
| 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 | Methods
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| Set a list of origins to be allowed for `Access-Control-Allow-Origin`. | An array of allowed HTTP methods for CORS. The `Access-Control-Request-Method`
| The value can be one of the following: | is checked against the following list.
| |
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin | Following is the list of default methods. Feel free to add more.
| */
| Boolean (true) - Allow current request origin. methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],
| 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 | Headers
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| An array of allowed HTTP methods for CORS. The `Access-Control-Request-Method` | List of headers to be allowed for `Access-Control-Allow-Headers` header.
| is checked against the following list. | The value can be one of the following:
| |
| Following is the list of default methods. Feel free to add more. | https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Headers
*/ |
methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'], | 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 | Expose Headers
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| List of headers to be allowed for `Access-Control-Allow-Headers` header. | A list of headers to be exposed by setting `Access-Control-Expose-Headers`.
| The value can be one of the following: | header. By default following 6 simple response headers are exposed.
| |
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Headers | Cache-Control
| | Content-Language
| Boolean(true) - Allow all headers mentioned in `Access-Control-Request-Headers`. | Content-Type
| Boolean(false) - Disallow all headers. | Expires
| String - Comma separated list of allowed headers. | Last-Modified
| Array - An array of allowed headers. | Pragma
| Function - Receives the current header and should return one of the above values. |
| | In order to add more headers, simply define them inside the following array.
*/ |
headers: true, | 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 | Credentials
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| A list of headers to be exposed by setting `Access-Control-Expose-Headers`. | Toggle `Access-Control-Allow-Credentials` header. If value is set to `true`,
| header. By default following 6 simple response headers are exposed. | then header will be set, otherwise not.
| |
| Cache-Control | https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
| Content-Language |
| Content-Type */
| Expires credentials: true,
| 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 | MaxAge
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| Toggle `Access-Control-Allow-Credentials` header. If value is set to `true`, | Define `Access-Control-Max-Age` header in seconds.
| then header will be set, otherwise not. | https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
| |
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials */
| maxAge: 90,
*/ });
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,
};
export default corsConfig; export default corsConfig;

View File

@ -5,52 +5,53 @@
* file. * file.
*/ */
import Env from '@ioc:Adonis/Core/Env'; import env from '#start/env';
import { DatabaseConfig } from '@ioc:Adonis/Lucid/Database'; // 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 | PostgreSQL config
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The primary connection for making database queries across the application | Configuration for PostgreSQL database. Make sure to install the driver
| You can use any key from the `connections` object defined in this same | from npm when using this connection
| file. |
| | npm i pg
*/ |
connection: Env.get('DB_CONNECTION'), */
pg: {
connections: { client: 'pg',
/* connection: {
|-------------------------------------------------------------------------- host: env.get('PG_HOST'),
| PostgreSQL config port: env.get('PG_PORT'),
|-------------------------------------------------------------------------- user: env.get('PG_USER'),
| password: env.get('PG_PASSWORD', ''),
| Configuration for PostgreSQL database. Make sure to install the driver database: env.get('PG_DB_NAME'),
| from npm when using this connection },
| searchPath: ['gba', 'public'],
| npm i pg migrations: {
| naturalSort: true,
*/ },
pg: { healthCheck: false,
client: 'pg', debug: false,
connection: { pool: { min: 1, max: 100 },
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; export default databaseConfig;

View File

@ -5,8 +5,9 @@
* file. * file.
*/ */
import Env from '@ioc:Adonis/Core/Env'; import env from '#start/env';
import { driveConfig } from '@adonisjs/core/build/config'; // import { driveConfig } from '@adonisjs/core/build/config';
import { driveConfig } from "@adonisjs/drive/build/config.js";
// import Application from '@ioc:Adonis/Core/Application'; // import Application from '@ioc:Adonis/Core/Application';
/* /*
@ -28,7 +29,7 @@ export default driveConfig({
| the `DRIVE_DISK` environment variable. | the `DRIVE_DISK` environment variable.
| |
*/ */
disk: Env.get('DRIVE_DISK', 'local'), disk: env.get('DRIVE_DISK', 'local'),
disks: { disks: {
/* /*

View File

@ -5,9 +5,10 @@
* file. * file.
*/ */
import Env from '@ioc:Adonis/Core/Env'; import env from '#start/env';
import { hashConfig } from '@adonisjs/core/build/config'; import { defineConfig } from "@adonisjs/core/hash";
import { drivers } from "@adonisjs/core/hash";
import { laravelDriver } from '../providers/HashDriver/index.js';
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Hash Config | Hash Config
@ -17,80 +18,87 @@ import { hashConfig } from '@adonisjs/core/build/config';
| defined inside `contracts` directory. | 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 | scrypt
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| By default we make use of the argon hasher to hash values. However, feel | Scrypt mapping uses the Node.js inbuilt crypto module for creating
| free to change the default value | hashes.
| |
*/ | We are using the default configuration recommended within the Node.js
default: Env.get('HASH_DRIVER', 'scrypt'), | 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: { /*
/* |--------------------------------------------------------------------------
|-------------------------------------------------------------------------- | Argon
| scrypt |--------------------------------------------------------------------------
|-------------------------------------------------------------------------- |
| | Argon mapping uses the `argon2` driver to hash values.
| Scrypt mapping uses the Node.js inbuilt crypto module for creating |
| hashes. | Make sure you install the underlying dependency for this driver to work.
| | https://www.npmjs.com/package/phc-argon2.
| We are using the default configuration recommended within the Node.js |
| documentation. | npm install phc-argon2
| https://nodejs.org/api/crypto.html#cryptoscryptpassword-salt-keylen-options-callback |
| */
*/ argon: drivers.argon2({
scrypt: { variant: 'id',
driver: 'scrypt', iterations: 3,
cost: 16384, memory: 4096,
blockSize: 8, parallelism: 1,
parallelization: 1, saltSize: 16,
saltSize: 16, }),
keyLength: 64,
maxMemory: 32 * 1024 * 1024,
},
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Argon | Bcrypt
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| Argon mapping uses the `argon2` driver to hash values. | Bcrypt mapping uses the `bcrypt` driver to hash values.
| |
| Make sure you install the underlying dependency for this driver to work. | Make sure you install the underlying dependency for this driver to work.
| https://www.npmjs.com/package/phc-argon2. | https://www.npmjs.com/package/phc-bcrypt.
| |
| npm install phc-argon2 | npm install phc-bcrypt
| |
*/ */
argon: { bcrypt: drivers.bcrypt({
driver: 'argon2', rounds: 10,
variant: 'id', }),
iterations: 3,
memory: 4096,
parallelism: 1,
saltSize: 16,
},
/* laravel: laravelDriver({
|-------------------------------------------------------------------------- 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,
},
},
}); });
declare module '@adonisjs/core/types' {
export interface HashersList extends InferHashers<typeof hashConfig> { }
}

View File

@ -1,20 +1,57 @@
/** import { defineConfig } from '@adonisjs/inertia';
* Feel free to let me know via PR, import type { HttpContext } from '@adonisjs/core/http';
* if you find something broken in this config file.
*/
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',
/* /**
|-------------------------------------------------------------------------- * Data that should be shared with all rendered pages
| Inertia-AdonisJS config */
|-------------------------------------------------------------------------- sharedData: {
| errors: (ctx) => ctx.session.flashMessages.get('errors'),
*/
export const inertia: InertiaConfig = { user_id: (ctx) => {
view: 'app', return ctx.session.flashMessages.get('user_id');
// ssr: { },
// enabled: false,
// }, 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
View 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> {}
}

View File

@ -1,4 +1,4 @@
import Env from '@ioc:Adonis/Core/Env'; import env from '#start/env';
interface OaiConfig { interface OaiConfig {
max: { listidentifiers: number; listrecords: number }; max: { listidentifiers: number; listrecords: number };
@ -7,8 +7,8 @@ interface OaiConfig {
} }
const config: OaiConfig = { const config: OaiConfig = {
max: { max: {
listidentifiers: 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), listrecords: parseInt(env.get('OAI_LIST_SIZE', 100), 10),
}, },
workspacePath: 'workspace', workspacePath: 'workspace',
redis: { redis: {

View File

@ -1,28 +1,9 @@
/** import env from '#start/env'
* Config source: https://git.io/JemcF import { defineConfig } from '@adonisjs/redis'
* import { InferConnections } from '@adonisjs/redis/types'
* Feel free to let us know via PR, if you find something broken in this config
* file.
*/
import Env from '@ioc:Adonis/Core/Env' const redisConfig = defineConfig({
import { redisConfig } from '@adonisjs/redis/build/config' connection: 'main',
/*
|--------------------------------------------------------------------------
| 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'),
connections: { connections: {
/* /*
@ -35,12 +16,21 @@ export default redisConfig({
| redis driver. | redis driver.
| |
*/ */
local: { main: {
host: Env.get('REDIS_HOST'), host: env.get('REDIS_HOST'),
port: Env.get('REDIS_PORT'), port: env.get('REDIS_PORT'),
password: Env.get('REDIS_PASSWORD', ''), password: env.get('REDIS_PASSWORD', ''),
db: 0, db: 0,
keyPrefix: '', keyPrefix: '',
retryStrategy(times) {
return times > 10 ? null : times * 50
},
}, },
}, },
}) })
export default redisConfig
declare module '@adonisjs/redis/types' {
export interface RedisConnections extends InferConnections<typeof redisConfig> {}
}

View File

@ -5,112 +5,122 @@
* file. * file.
*/ */
import Env from '@ioc:Adonis/Core/Env'; import env from '#start/env';
import Application from '@ioc:Adonis/Core/Application'; import app from '@adonisjs/core/services/app';
import { sessionConfig } from '@adonisjs/session/build/config'; import { defineConfig, stores } from '@adonisjs/session';
export default sessionConfig({ export default defineConfig({
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Enable/Disable sessions | Enable/Disable sessions
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| Setting the following property to "false" will disable the session for the | Setting the following property to "false" will disable the session for the
| entire application | entire application
| |
*/ */
enabled: true, enabled: true,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Driver | Driver
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The session driver to use. You can choose between one of the following | The session driver to use. You can choose between one of the following
| drivers. | drivers.
| |
| - cookie (Uses signed cookies to store session values) | - cookie (Uses signed cookies to store session values)
| - file (Uses filesystem to store session values) | - file (Uses filesystem to store session values)
| - redis (Uses redis. Make sure to install "@adonisjs/redis" as well) | - redis (Uses redis. Make sure to install "@adonisjs/redis" as well)
| |
| Note: Switching drivers will make existing sessions invalid. | Note: Switching drivers will make existing sessions invalid.
| |
*/ */
driver: Env.get('SESSION_DRIVER'), // driver: env.get('SESSION_DRIVER'),
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Cookie name | Cookie name
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The name of the cookie that will hold the session id. | The name of the cookie that will hold the session id.
| |
*/ */
cookieName: 'adonis-session', cookieName: 'adonis-session',
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Clear session when browser closes | Clear session when browser closes
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| Whether or not you want to destroy the session when browser closes. Setting | Whether or not you want to destroy the session when browser closes. Setting
| this value to `true` will ignore the `age`. | this value to `true` will ignore the `age`.
| |
*/ */
clearWithBrowser: false, clearWithBrowser: false,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Session age | Session age
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The duration for which session stays active after no activity. A new HTTP | The duration for which session stays active after no activity. A new HTTP
| request to the server is considered as activity. | request to the server is considered as activity.
| |
| The value can be a number in milliseconds or a string that must be valid | The value can be a number in milliseconds or a string that must be valid
| as per https://npmjs.org/package/ms package. | as per https://npmjs.org/package/ms package.
| |
| Example: `2 days`, `2.5 hrs`, `1y`, `5s` and so on. | Example: `2 days`, `2.5 hrs`, `1y`, `5s` and so on.
| |
*/ */
age: '2h', age: '2h',
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Cookie values | Cookie values
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The cookie settings are used to setup the session id cookie and also the | The cookie settings are used to setup the session id cookie and also the
| driver will use the same values. | driver will use the same values.
| |
*/ */
cookie: { cookie: {
path: '/', path: '/',
httpOnly: true, httpOnly: true,
secure: app.inProduction,
sameSite: false, 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 | Configuration for the file driver
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The file driver needs absolute path to the directory in which sessions | The file driver needs absolute path to the directory in which sessions
| must be stored. | must be stored.
| |
*/ */
file: { // file: {
location: Application.tmpPath('sessions'), // location: app.tmpPath('sessions'),
}, // },
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Redis driver | Redis driver
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| |
| The redis connection you want session driver to use. The same connection | The redis connection you want session driver to use. The same connection
| must be defined inside `config/redis.ts` file as well. | must be defined inside `config/redis.ts` file as well.
| |
*/ */
redisConnection: 'local', redisConnection: 'local',
stores: {
cookie: stores.cookie(),
},
}); });

View File

@ -1,24 +1,8 @@
/** import { defineConfig } from '@adonisjs/shield';
* Config source: https://git.io/Jvwvt
*
* Feel free to let us know via PR, if you find something broken in this config
* file.
*/
// import Env from '@ioc:Adonis/Core/Env' export default defineConfig({
import { ShieldConfig } from '@ioc:Adonis/Addons/Shield'; csp: {
/*
/*
|--------------------------------------------------------------------------
| 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'] = {
/*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Enable/disable CSP | Enable/disable CSP
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@ -26,9 +10,9 @@ export const csp: ShieldConfig['csp'] = {
| The CSP rules are disabled by default for seamless onboarding. | The CSP rules are disabled by default for seamless onboarding.
| |
*/ */
enabled: false, enabled: false,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Directives | Directives
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@ -44,9 +28,9 @@ export const csp: ShieldConfig['csp'] = {
| } | }
| |
*/ */
directives: {}, directives: {},
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Report only | Report only
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@ -55,27 +39,17 @@ export const csp: ShieldConfig['csp'] = {
| instead report them to a URL. | instead report them to a URL.
| |
*/ */
reportOnly: false, reportOnly: false,
}; },
csrf: {
/* /*
|--------------------------------------------------------------------------
| 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'] = {
/*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Enable/Disable CSRF | Enable/Disable CSRF
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
*/ */
enabled: true, enabled: true,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Routes to Ignore | Routes to Ignore
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@ -85,16 +59,16 @@ export const csrf: ShieldConfig['csrf'] = {
| slash. Example: | slash. Example:
| |
| `/foo/bar` | `/foo/bar`
| |
| Also you can define a function that is evaluated on every HTTP Request. | Also you can define a function that is evaluated on every HTTP Request.
| ``` | ```
| exceptRoutes: ({ request }) => request.url().includes('/api') | exceptRoutes: ({ request }) => request.url().includes('/api')
| ``` | ```
| |
*/ */
exceptRoutes: [], exceptRoutes: [],
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Enable Sharing Token Via Cookie | Enable Sharing Token Via Cookie
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@ -108,9 +82,9 @@ export const csrf: ShieldConfig['csrf'] = {
| AJAX requests. | AJAX requests.
| |
*/ */
enableXsrfCookie: true, enableXsrfCookie: true,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Methods to Validate | 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. | Define an array of HTTP methods to be validated for a valid CSRF token.
| |
*/ */
methods: ['POST', 'PUT', 'PATCH', 'DELETE'], methods: ['POST', 'PUT', 'PATCH', 'DELETE'],
}; },
hsts: {
/* enabled: true,
|-------------------------------------------------------------------------- /*
| 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,
/*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Max Age | Max Age
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@ -196,9 +105,9 @@ export const hsts: ShieldConfig['hsts'] = {
| accessed using HTTPS. | accessed using HTTPS.
| |
*/ */
maxAge: '180 days', maxAge: '180 days',
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Include Subdomains | Include Subdomains
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@ -206,9 +115,9 @@ export const hsts: ShieldConfig['hsts'] = {
| Apply rules on the subdomains as well. | Apply rules on the subdomains as well.
| |
*/ */
includeSubDomains: true, includeSubDomains: true,
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Preloading | Preloading
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
@ -217,21 +126,9 @@ export const hsts: ShieldConfig['hsts'] = {
| the HSTS policy. Learn more https://hstspreload.org/ | the HSTS policy. Learn more https://hstspreload.org/
| |
*/ */
preload: false, preload: false,
}; },
contentTypeSniffing: {
/* enabled: true,
|-------------------------------------------------------------------------- },
| 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,
};

View File

@ -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 * https://docs.adonisjs.com/guides/static-assets
* file.
*/ */
const staticServerConfig = defineConfig({
enabled: true,
etag: true,
lastModified: true,
dotFiles: 'ignore',
})
import { AssetsConfig } from '@ioc:Adonis/Core/Static'; export default staticServerConfig
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;

View File

@ -1,73 +1,63 @@
/** // /**
* Contract source: https://git.io/JOdz5 // * Contract source: https://git.io/JOdz5
* // *
* Feel free to let us know via PR, if you find something broken in this // * Feel free to let us know via PR, if you find something broken in this
* file. // * file.
*/ // */
import User from 'App/Models/User'; // import User from '#app/Models/User';
declare module '@ioc:Adonis/Addons/Auth' { // declare module '@ioc:Adonis/Addons/Auth' {
/* // /*
|-------------------------------------------------------------------------- // |
| Providers // interface ProvidersList {
|-------------------------------------------------------------------------- // /*
| // |--------------------------------------------------------------------------
| The providers are used to fetch users. The Auth module comes pre-bundled // | User Provider
| with two providers that are `Lucid` and `Database`. Both uses database // |--------------------------------------------------------------------------
| to fetch user details. // |
| // | The following provider uses Lucid models as a driver for fetching user
| You can also create and register your own custom providers. // | details from the database for authentication.
| // |
*/ // | You can create multiple providers using the same underlying driver with
interface ProvidersList { // | different Lucid models.
/* // |
|-------------------------------------------------------------------------- // */
| User Provider // user: {
|-------------------------------------------------------------------------- // implementation: LucidProviderContract<typeof User>;
| // config: LucidProviderConfig<typeof User>;
| 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 // | Guards
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| // |
| The guards are used for authenticating users using different drivers. // | The guards are used for authenticating users using different drivers.
| The auth module comes with 3 different guards. // | The auth module comes with 3 different guards.
| // |
| - SessionGuardContract // | - SessionGuardContract
| - BasicAuthGuardContract // | - BasicAuthGuardContract
| - OATGuardContract ( Opaque access token ) // | - OATGuardContract ( Opaque access token )
| // |
| Every guard needs a provider for looking up users from the database. // | Every guard needs a provider for looking up users from the database.
| // |
*/ // */
interface GuardsList { // interface GuardsList {
/* // /*
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| Web Guard // | Web Guard
|-------------------------------------------------------------------------- // |--------------------------------------------------------------------------
| // |
| The web guard uses sessions for maintaining user login state. It uses // | The web guard uses sessions for maintaining user login state. It uses
| the `user` provider for fetching user details. // | the `user` provider for fetching user details.
| // |
*/ // */
web: { // web: {
implementation: SessionGuardContract<'user', 'web'>; // implementation: SessionGuardContract<'user', 'web'>;
config: SessionGuardConfig<'user'>; // config: SessionGuardConfig<'user'>;
client: SessionClientContract<'user'>; // client: SessionClientContract<'user'>;
}; // };
} // }
} // }

View File

@ -5,9 +5,9 @@
* file. * file.
*/ */
import type { InferDisksFromConfig } from '@adonisjs/core/build/config'; // import type { InferDisksFromConfig } from '@adonisjs/core/build/config';
import type driveConfig from '../config/drive'; // import type driveConfig from '../config/drive.js';
declare module '@ioc:Adonis/Core/Drive' { // declare module '@ioc:Adonis/Core/Drive' {
interface DisksList extends InferDisksFromConfig<typeof driveConfig> {} // interface DisksList extends InferDisksFromConfig<typeof driveConfig> {}
} // }

View File

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

View File

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

Some files were not shown because too many files have changed in this diff Show More