forked from geolba/tethys.backend
- additional functionality for DatasetController.ts
- additional validation rules like 'uniqueArray' - additional Lucid models like BaseModel.ts for filling attributes, Title.ts, Description.ts - npm updates for @adonisjs/core
This commit is contained in:
parent
c4f4eff0d9
commit
e0ff71b117
44 changed files with 2002 additions and 1556 deletions
|
@ -1,17 +1,17 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
|
||||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
|
||||
export default class HomeController {
|
||||
public async index({}: HttpContextContract) {}
|
||||
public async index({}: HttpContextContract) {}
|
||||
|
||||
public async create({}: HttpContextContract) {}
|
||||
public async create({}: HttpContextContract) {}
|
||||
|
||||
public async store({}: HttpContextContract) {}
|
||||
public async store({}: HttpContextContract) {}
|
||||
|
||||
public async show({}: HttpContextContract) {}
|
||||
public async show({}: HttpContextContract) {}
|
||||
|
||||
public async edit({}: HttpContextContract) {}
|
||||
public async edit({}: HttpContextContract) {}
|
||||
|
||||
public async update({}: HttpContextContract) {}
|
||||
public async update({}: HttpContextContract) {}
|
||||
|
||||
public async destroy({}: HttpContextContract) {}
|
||||
public async destroy({}: HttpContextContract) {}
|
||||
}
|
||||
|
|
|
@ -8,197 +8,207 @@ import { RenderResponse } from '@ioc:EidelLev/Inertia';
|
|||
// import { schema, rules } from '@ioc:Adonis/Core/Validator';
|
||||
|
||||
export default class UsersController {
|
||||
public async index({ auth, request, inertia }: HttpContextContract) {
|
||||
const page = request.input('page', 1);
|
||||
// const limit = 10
|
||||
public async index({ auth, request, inertia }: HttpContextContract) {
|
||||
const page = request.input('page', 1);
|
||||
// const limit = 10
|
||||
|
||||
let users: ModelQueryBuilderContract<typeof User, User> = User.query();
|
||||
let users: ModelQueryBuilderContract<typeof User, User> = User.query();
|
||||
|
||||
if (request.input('search')) {
|
||||
// users = users.whereRaw('name like %?%', [request.input('search')])
|
||||
const searchTerm = request.input('search');
|
||||
users.where('login', 'ilike', `%${searchTerm}%`);
|
||||
}
|
||||
if (request.input('search')) {
|
||||
// users = users.whereRaw('name like %?%', [request.input('search')])
|
||||
const searchTerm = request.input('search');
|
||||
users.where('login', 'ilike', `%${searchTerm}%`);
|
||||
}
|
||||
|
||||
if (request.input('sort')) {
|
||||
type SortOrder = 'asc' | 'desc' | undefined;
|
||||
let attribute = request.input('sort');
|
||||
let sort_order: SortOrder = 'asc';
|
||||
if (request.input('sort')) {
|
||||
type SortOrder = 'asc' | 'desc' | undefined;
|
||||
let attribute = request.input('sort');
|
||||
let sort_order: SortOrder = 'asc';
|
||||
|
||||
// if (strncmp($attribute, '-', 1) === 0) {
|
||||
if (attribute.substr(0, 1) == '-') {
|
||||
sort_order = 'desc';
|
||||
// attribute = substr(attribute, 1);
|
||||
attribute = attribute.substr(1);
|
||||
}
|
||||
// $users->orderBy($attribute, $sort_order);
|
||||
users.orderBy(attribute, sort_order);
|
||||
} else {
|
||||
// users.orderBy('created_at', 'desc');
|
||||
users.orderBy('id', 'asc');
|
||||
}
|
||||
// if (strncmp($attribute, '-', 1) === 0) {
|
||||
if (attribute.substr(0, 1) == '-') {
|
||||
sort_order = 'desc';
|
||||
// attribute = substr(attribute, 1);
|
||||
attribute = attribute.substr(1);
|
||||
}
|
||||
// $users->orderBy($attribute, $sort_order);
|
||||
users.orderBy(attribute, sort_order);
|
||||
} else {
|
||||
// users.orderBy('created_at', 'desc');
|
||||
users.orderBy('id', 'asc');
|
||||
}
|
||||
|
||||
// const users = await User.query().orderBy('login').paginate(page, limit);
|
||||
// const users = await User.query().orderBy('login').paginate(page, limit);
|
||||
|
||||
let usersResult = await users // User.query()
|
||||
// .orderBy('login')
|
||||
// .filter(qs)
|
||||
// .preload('focusInterests')
|
||||
// .preload('role')
|
||||
.paginate(page, 5);
|
||||
let usersResult = await users // User.query()
|
||||
// .orderBy('login')
|
||||
// .filter(qs)
|
||||
// .preload('focusInterests')
|
||||
// .preload('role')
|
||||
.paginate(page, 5);
|
||||
|
||||
// var test = request.all();
|
||||
// var test = request.all();
|
||||
|
||||
return inertia.render('Admin/User/Index', {
|
||||
// testing: 'this is a test',
|
||||
users: usersResult.toJSON(),
|
||||
filters: request.all(),
|
||||
can: {
|
||||
create: await auth.user?.can(['user-create']),
|
||||
edit: await auth.user?.can(['user-edit']),
|
||||
delete: await auth.user?.can(['user-delete']),
|
||||
},
|
||||
});
|
||||
}
|
||||
return inertia.render('Admin/User/Index', {
|
||||
// testing: 'this is a test',
|
||||
users: usersResult.toJSON(),
|
||||
filters: request.all(),
|
||||
can: {
|
||||
create: await auth.user?.can(['user-create']),
|
||||
edit: await auth.user?.can(['user-edit']),
|
||||
delete: await auth.user?.can(['user-delete']),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
public async create({ inertia }: HttpContextContract) {
|
||||
// let rolesPluck = {};
|
||||
// (await Role.query().select('id', 'name')).forEach((user) => {
|
||||
// rolesPluck[user.id] = user.name;
|
||||
// });
|
||||
const roles = await Role.query().select('id', 'name').pluck('name', 'id');
|
||||
public async create({ inertia }: HttpContextContract) {
|
||||
// let rolesPluck = {};
|
||||
// (await Role.query().select('id', 'name')).forEach((user) => {
|
||||
// rolesPluck[user.id] = user.name;
|
||||
// });
|
||||
const roles = await Role.query().select('id', 'name').pluck('name', 'id');
|
||||
|
||||
return inertia.render('Admin/User/Create', {
|
||||
roles: roles,
|
||||
});
|
||||
}
|
||||
return inertia.render('Admin/User/Create', {
|
||||
roles: roles,
|
||||
});
|
||||
}
|
||||
|
||||
public async store({ request, response, session }: HttpContextContract) {
|
||||
// node ace make:validator CreateUser
|
||||
try {
|
||||
// Step 2 - Validate request body against the schema
|
||||
await request.validate(CreateUserValidator);
|
||||
// console.log({ payload });
|
||||
} catch (error) {
|
||||
// Step 3 - Handle errors
|
||||
// return response.badRequest(error.messages);
|
||||
throw error;
|
||||
}
|
||||
const input = request.only(['login', 'email', 'password']);
|
||||
const user = await User.create(input);
|
||||
if (request.input('roles')) {
|
||||
const roles: Array<number> = request.input('roles');
|
||||
await user.related('roles').attach(roles);
|
||||
}
|
||||
public async store({ request, response, session }: HttpContextContract) {
|
||||
// node ace make:validator CreateUser
|
||||
try {
|
||||
// Step 2 - Validate request body against the schema
|
||||
await request.validate(CreateUserValidator);
|
||||
// console.log({ payload });
|
||||
} catch (error) {
|
||||
// Step 3 - Handle errors
|
||||
// return response.badRequest(error.messages);
|
||||
throw error;
|
||||
}
|
||||
const input = request.only(['login', 'email', 'password']);
|
||||
const user = await User.create(input);
|
||||
if (request.input('roles')) {
|
||||
const roles: Array<number> = request.input('roles');
|
||||
await user.related('roles').attach(roles);
|
||||
}
|
||||
|
||||
session.flash('message', 'User has been created successfully');
|
||||
return response.redirect().toRoute('user.index');
|
||||
}
|
||||
session.flash('message', 'User has been created successfully');
|
||||
return response.redirect().toRoute('user.index');
|
||||
}
|
||||
|
||||
public async show({ request, inertia }: HttpContextContract) {
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
public async show({ request, inertia }: HttpContextContract) {
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
|
||||
const roles = await Role.query().pluck('name', 'id');
|
||||
// const userHasRoles = user.roles;
|
||||
const userRoles = await user.related('roles').query().orderBy('name').pluck('id');
|
||||
const roles = await Role.query().pluck('name', 'id');
|
||||
// const userHasRoles = user.roles;
|
||||
const userRoles = await user.related('roles').query().orderBy('name').pluck('id');
|
||||
|
||||
return inertia.render('Admin/User/Show', {
|
||||
roles: roles,
|
||||
user: user,
|
||||
userHasRoles: userRoles,
|
||||
});
|
||||
}
|
||||
return inertia.render('Admin/User/Show', {
|
||||
roles: roles,
|
||||
user: user,
|
||||
userHasRoles: userRoles,
|
||||
});
|
||||
}
|
||||
|
||||
public async edit({ request, inertia }: HttpContextContract) {
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
public async edit({ request, inertia }: HttpContextContract) {
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
|
||||
const roles = await Role.query().pluck('name', 'id');
|
||||
// const userHasRoles = user.roles;
|
||||
const userHasRoles = await user.related('roles').query().orderBy('name').pluck('id');
|
||||
// let test = Object.keys(userHasRoles).map((key) => userHasRoles[key]);
|
||||
return inertia.render('Admin/User/Edit', {
|
||||
roles: roles,
|
||||
user: user,
|
||||
userHasRoles: Object.keys(userHasRoles).map((key) => userHasRoles[key]), //convert object to array with role ids
|
||||
});
|
||||
}
|
||||
const roles = await Role.query().pluck('name', 'id');
|
||||
// const userHasRoles = user.roles;
|
||||
const userHasRoles = await user.related('roles').query().orderBy('name').pluck('id');
|
||||
// let test = Object.keys(userHasRoles).map((key) => userHasRoles[key]);
|
||||
return inertia.render('Admin/User/Edit', {
|
||||
roles: roles,
|
||||
user: user,
|
||||
userHasRoles: Object.keys(userHasRoles).map((key) => userHasRoles[key]), //convert object to array with role ids
|
||||
});
|
||||
}
|
||||
|
||||
public async update({ request, response, session }: HttpContextContract) {
|
||||
// node ace make:validator UpdateUser
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
public async update({ request, response, session }: HttpContextContract) {
|
||||
// node ace make:validator UpdateUser
|
||||
const id = request.param('id');
|
||||
const user = await User.query().where('id', id).firstOrFail();
|
||||
|
||||
// validate update form
|
||||
await request.validate(UpdateUserValidator);
|
||||
// validate update form
|
||||
await request.validate(UpdateUserValidator);
|
||||
|
||||
// password is optional
|
||||
let input;
|
||||
if (request.input('password')) {
|
||||
input = request.only(['login', 'email', 'password']);
|
||||
} else {
|
||||
input = request.only(['login', 'email']);
|
||||
}
|
||||
await user.merge(input).save();
|
||||
// await user.save();
|
||||
// password is optional
|
||||
let input;
|
||||
if (request.input('password')) {
|
||||
input = request.only(['login', 'email', 'password']);
|
||||
} else {
|
||||
input = request.only(['login', 'email']);
|
||||
}
|
||||
await user.merge(input).save();
|
||||
// await user.save();
|
||||
|
||||
if (request.input('roles')) {
|
||||
const roles: Array<number> = request.input('roles');
|
||||
await user.related('roles').sync(roles);
|
||||
}
|
||||
if (request.input('roles')) {
|
||||
const roles: Array<number> = request.input('roles');
|
||||
await user.related('roles').sync(roles);
|
||||
}
|
||||
|
||||
session.flash('message', 'User has been updated successfully');
|
||||
return response.redirect().toRoute('user.index');
|
||||
}
|
||||
session.flash('message', 'User has been updated successfully');
|
||||
return response.redirect().toRoute('user.index');
|
||||
}
|
||||
|
||||
public async destroy({ request, response, session }: HttpContextContract) {
|
||||
const id = request.param('id');
|
||||
const user = await User.findOrFail(id);
|
||||
await user.delete();
|
||||
public async destroy({ request, response, session }: HttpContextContract) {
|
||||
const id = request.param('id');
|
||||
const user = await User.findOrFail(id);
|
||||
await user.delete();
|
||||
|
||||
session.flash('message', `User ${user.login} has been deleted.`);
|
||||
return response.redirect().toRoute('user.index');
|
||||
}
|
||||
session.flash('message', `User ${user.login} has been deleted.`);
|
||||
return response.redirect().toRoute('user.index');
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the user a form to change their personal information & password.
|
||||
*
|
||||
* @return — \Inertia\Response
|
||||
*/
|
||||
public accountInfo({ inertia, auth }: HttpContextContract): RenderResponse {
|
||||
const user = auth.user;
|
||||
// const id = request.param('id');
|
||||
// const user = await User.query().where('id', id).firstOrFail();
|
||||
/**
|
||||
* Show the user a form to change their personal information & password.
|
||||
*
|
||||
* @return — \Inertia\Response
|
||||
*/
|
||||
public accountInfo({ inertia, auth }: HttpContextContract): RenderResponse {
|
||||
const user = auth.user;
|
||||
// const id = request.param('id');
|
||||
// const user = await User.query().where('id', id).firstOrFail();
|
||||
|
||||
return inertia.render('Admin/User/AccountInfo', {
|
||||
user: user,
|
||||
});
|
||||
}
|
||||
return inertia.render('Admin/User/AccountInfo', {
|
||||
user: user,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Save the modified personal information for a user.
|
||||
*
|
||||
* @param HttpContextContract ctx
|
||||
* @return : RedirectContract
|
||||
*/
|
||||
public async accountInfoStore({ request, response, auth, session }: HttpContextContract) {
|
||||
// validate update form
|
||||
await request.validate(UpdateUserValidator);
|
||||
/**
|
||||
* Save the modified personal information for a user.
|
||||
*
|
||||
* @param HttpContextContract ctx
|
||||
* @return : RedirectContract
|
||||
*/
|
||||
public async accountInfoStore({ request, response, auth, session }: HttpContextContract) {
|
||||
// validate update form
|
||||
await request.validate(UpdateUserValidator);
|
||||
|
||||
const payload = request.only(['login', 'email']);
|
||||
auth.user?.merge(payload);
|
||||
const user = await auth.user?.save();
|
||||
// $user = \Auth::user()->update($request->except(['_token']));
|
||||
let message;
|
||||
if (user) {
|
||||
message = 'Account updated successfully.';
|
||||
} else {
|
||||
message = 'Error while saving. Please try again.';
|
||||
}
|
||||
const payload = request.only(['login', 'email']);
|
||||
auth.user?.merge(payload);
|
||||
const user = await auth.user?.save();
|
||||
// $user = \Auth::user()->update($request->except(['_token']));
|
||||
let message;
|
||||
if (user) {
|
||||
message = 'Account updated successfully.';
|
||||
} else {
|
||||
message = 'Error while saving. Please try again.';
|
||||
}
|
||||
|
||||
session.flash(message);
|
||||
return response.redirect().toRoute('admin.account.info');
|
||||
//->with('message', __($message));
|
||||
}
|
||||
session.flash(message);
|
||||
return response.redirect().toRoute('admin.account.info');
|
||||
//->with('message', __($message));
|
||||
}
|
||||
|
||||
// private async syncRoles(userId: number, roleIds: Array<number>) {
|
||||
// const user = await User.findOrFail(userId)
|
||||
// // const roles: Role[] = await Role.query().whereIn('id', roleIds);
|
||||
|
||||
// // await user.roles().sync(roles.rows.map(role => role.id))
|
||||
// await user.related("roles").sync(roleIds);
|
||||
|
||||
// return user
|
||||
// }
|
||||
}
|
||||
|
|
|
@ -25,10 +25,8 @@ export default class AuthorsController {
|
|||
if (request.input('filter')) {
|
||||
// users = users.whereRaw('name like %?%', [request.input('search')])
|
||||
const searchTerm = request.input('filter');
|
||||
authors
|
||||
.whereILike('first_name', `%${searchTerm}%`)
|
||||
.orWhereILike('last_name', `%${searchTerm}%`);
|
||||
// .orWhere('email', 'like', `%${searchTerm}%`);
|
||||
authors.whereILike('first_name', `%${searchTerm}%`).orWhereILike('last_name', `%${searchTerm}%`);
|
||||
// .orWhere('email', 'like', `%${searchTerm}%`);
|
||||
}
|
||||
|
||||
let persons = await authors;
|
||||
|
|
|
@ -4,20 +4,12 @@ import Dataset from 'App/Models/Dataset';
|
|||
|
||||
// node ace make:controller Author
|
||||
export default class DatasetController {
|
||||
public async index({}: HttpContextContract) {
|
||||
// select * from gba.persons
|
||||
// where exists (select * from gba.documents inner join gba.link_documents_persons on "documents"."id" = "link_documents_persons"."document_id"
|
||||
// where ("link_documents_persons"."role" = 'author') and ("persons"."id" = "link_documents_persons"."person_id"));
|
||||
const datasets = await Dataset.query().where('server_state', 'published').orWhere('server_state', 'deleted');
|
||||
|
||||
public async index({}: HttpContextContract) {
|
||||
// select * from gba.persons
|
||||
// where exists (select * from gba.documents inner join gba.link_documents_persons on "documents"."id" = "link_documents_persons"."document_id"
|
||||
// where ("link_documents_persons"."role" = 'author') and ("persons"."id" = "link_documents_persons"."person_id"));
|
||||
const datasets = await Dataset
|
||||
.query()
|
||||
.where('server_state', 'published')
|
||||
.orWhere('server_state', 'deleted');
|
||||
|
||||
|
||||
|
||||
|
||||
return datasets;
|
||||
}
|
||||
|
||||
return datasets;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -5,38 +5,36 @@ import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
|||
import AuthValidator from 'App/Validators/AuthValidator';
|
||||
|
||||
export default class AuthController {
|
||||
// login function
|
||||
public async login({ request, response, auth, session }: HttpContextContract) {
|
||||
// console.log({
|
||||
// registerBody: request.body(),
|
||||
// });
|
||||
// login function
|
||||
public async login({ request, response, auth, session }: HttpContextContract) {
|
||||
// console.log({
|
||||
// registerBody: request.body(),
|
||||
// });
|
||||
await request.validate(AuthValidator);
|
||||
|
||||
const plainPassword = await request.input('password');
|
||||
const email = await request.input('email');
|
||||
// grab uid and password values off request body
|
||||
// const { email, password } = request.only(['email', 'password'])
|
||||
|
||||
|
||||
|
||||
try {
|
||||
// attempt to login
|
||||
await auth.use("web").attempt(email, plainPassword);
|
||||
} catch (error) {
|
||||
// if login fails, return vague form message and redirect back
|
||||
session.flash('message', 'Your username, email, or password is incorrect')
|
||||
return response.redirect().back()
|
||||
}
|
||||
const plainPassword = await request.input('password');
|
||||
const email = await request.input('email');
|
||||
// grab uid and password values off request body
|
||||
// const { email, password } = request.only(['email', 'password'])
|
||||
|
||||
// otherwise, redirect todashboard
|
||||
response.redirect('/dashboard');
|
||||
}
|
||||
try {
|
||||
// attempt to login
|
||||
await auth.use('web').attempt(email, plainPassword);
|
||||
} catch (error) {
|
||||
// if login fails, return vague form message and redirect back
|
||||
session.flash('message', 'Your username, email, or password is incorrect');
|
||||
return response.redirect().back();
|
||||
}
|
||||
|
||||
// logout function
|
||||
public async logout({ auth, response }: HttpContextContract) {
|
||||
// await auth.logout();
|
||||
await auth.use('web').logout();
|
||||
response.redirect('/app/login');
|
||||
// return response.status(200);
|
||||
}
|
||||
// otherwise, redirect todashboard
|
||||
response.redirect('/dashboard');
|
||||
}
|
||||
|
||||
// logout function
|
||||
public async logout({ auth, response }: HttpContextContract) {
|
||||
// await auth.logout();
|
||||
await auth.use('web').logout();
|
||||
response.redirect('/app/login');
|
||||
// return response.status(200);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,33 +1,22 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
// import User from 'App/Models/User';
|
||||
import User from 'App/Models/User';
|
||||
import Dataset from 'App/Models/Dataset';
|
||||
// import Role from 'App/Models/Role';
|
||||
// import Database from '@ioc:Adonis/Lucid/Database';
|
||||
import License from 'App/Models/License';
|
||||
import Project from 'App/Models/Project';
|
||||
// import type { ModelQueryBuilderContract } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Title from 'App/Models/Title';
|
||||
import Description from 'App/Models/Description';
|
||||
// import CreateUserValidator from 'App/Validators/CreateUserValidator';
|
||||
// import UpdateUserValidator from 'App/Validators/UpdateUserValidator';
|
||||
// import { RenderResponse } from '@ioc:EidelLev/Inertia';
|
||||
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import dayjs from 'dayjs';
|
||||
// import Application from '@ioc:Adonis/Core/Application';
|
||||
|
||||
enum TitleTypes {
|
||||
Main = 'Main',
|
||||
Sub = 'Sub',
|
||||
Alternative = 'Alternative',
|
||||
Translated = 'Translated',
|
||||
Other = 'Other',
|
||||
}
|
||||
|
||||
enum DescriptionTypes {
|
||||
Abstract = 'Abstract',
|
||||
Methods = 'Methods',
|
||||
Series_information = 'Series_information',
|
||||
Technical_info = 'Technical_info',
|
||||
Translated = 'Translated',
|
||||
Other = 'Other',
|
||||
}
|
||||
import Person from 'App/Models/Person';
|
||||
import Database from '@ioc:Adonis/Lucid/Database';
|
||||
import { TransactionClientContract } from '@ioc:Adonis/Lucid/Database';
|
||||
import Subject from 'App/Models/Subject';
|
||||
import CreateDatasetValidator from 'App/Validators/CreateDatasetValidator';
|
||||
import { TitleTypes, DescriptionTypes } from 'Contracts/enums';
|
||||
|
||||
export default class DatasetController {
|
||||
public async create({ inertia }: HttpContextContract) {
|
||||
|
@ -190,7 +179,7 @@ export default class DatasetController {
|
|||
depth_min: schema.number.optional([rules.requiredIfExists('depth_max')]),
|
||||
depth_max: schema.number.optional([rules.requiredIfExists('depth_min')]),
|
||||
}),
|
||||
subjects: schema.array([rules.minLength(3)]).members(
|
||||
subjects: schema.array([rules.minLength(3), rules.uniqueArray('value')]).members(
|
||||
schema.object().members({
|
||||
value: schema.string({ trim: true }, [
|
||||
rules.minLength(3),
|
||||
|
@ -214,98 +203,161 @@ export default class DatasetController {
|
|||
}
|
||||
return response.redirect().back();
|
||||
}
|
||||
public async store({ request, response, session }: HttpContextContract) {
|
||||
const newDatasetSchema = schema.create({
|
||||
// first step
|
||||
language: schema.string({ trim: true }, [
|
||||
rules.regex(/^[a-zA-Z0-9-_]+$/), //Must be alphanumeric with hyphens or underscores
|
||||
]),
|
||||
licenses: schema.array([rules.minLength(1)]).members(schema.number()), // define at least one license for the new dataset
|
||||
rights: schema.string([rules.equalTo('true')]),
|
||||
// second step
|
||||
type: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(255)]),
|
||||
creating_corporation: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(255)]),
|
||||
titles: schema.array([rules.minLength(1)]).members(
|
||||
schema.object().members({
|
||||
value: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(255)]),
|
||||
type: schema.enum(Object.values(TitleTypes)),
|
||||
language: schema.string({ trim: true }, [
|
||||
rules.minLength(2),
|
||||
rules.maxLength(255),
|
||||
rules.translatedLanguage('/language', 'type'),
|
||||
]),
|
||||
}),
|
||||
),
|
||||
descriptions: schema.array([rules.minLength(1)]).members(
|
||||
schema.object().members({
|
||||
value: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(255)]),
|
||||
type: schema.enum(Object.values(DescriptionTypes)),
|
||||
language: schema.string({ trim: true }, [
|
||||
rules.minLength(2),
|
||||
rules.maxLength(255),
|
||||
rules.translatedLanguage('/language', 'type'),
|
||||
]),
|
||||
}),
|
||||
),
|
||||
authors: schema.array([rules.minLength(1)]).members(schema.object().members({ email: schema.string({ trim: true }) })),
|
||||
// third step
|
||||
project_id: schema.number.optional(),
|
||||
embargo_date: schema.date.optional({ format: 'yyyy-MM-dd' }, [rules.after(10, 'days')]),
|
||||
coverage: schema.object().members({
|
||||
x_min: schema.number(),
|
||||
x_max: schema.number(),
|
||||
y_min: schema.number(),
|
||||
y_max: schema.number(),
|
||||
elevation_absolut: schema.number.optional(),
|
||||
elevation_min: schema.number.optional([rules.requiredIfExists('elevation_max')]),
|
||||
elevation_max: schema.number.optional([rules.requiredIfExists('elevation_min')]),
|
||||
depth_absolut: schema.number.optional(),
|
||||
depth_min: schema.number.optional([rules.requiredIfExists('depth_max')]),
|
||||
depth_max: schema.number.optional([rules.requiredIfExists('depth_min')]),
|
||||
}),
|
||||
subjects: schema.array([rules.minLength(3)]).members(
|
||||
schema.object().members({
|
||||
value: schema.string({ trim: true }, [
|
||||
rules.minLength(3),
|
||||
rules.maxLength(255),
|
||||
// rules.unique({ table: 'dataset_subjects', column: 'value' }),
|
||||
]),
|
||||
// type: schema.enum(Object.values(TitleTypes)),
|
||||
language: schema.string({ trim: true }, [rules.minLength(2), rules.maxLength(255)]),
|
||||
}),
|
||||
),
|
||||
// file: schema.file({
|
||||
// size: '100mb',
|
||||
// extnames: ['jpg', 'gif', 'png'],
|
||||
// }),
|
||||
files: schema.array([rules.minLength(1)]).members(
|
||||
schema.file({
|
||||
size: '100mb',
|
||||
extnames: ['jpg', 'gif', 'png'],
|
||||
}),
|
||||
),
|
||||
// upload: schema.object().members({
|
||||
// label: schema.string({ trim: true }, [rules.maxLength(255)]),
|
||||
|
||||
// // label: schema.string({ trim: true }, [
|
||||
// // // rules.minLength(3),
|
||||
// // // rules.maxLength(255),
|
||||
// // ]),
|
||||
// }),
|
||||
});
|
||||
|
||||
// const coverImages = request.file('files');
|
||||
// node ace make:validator CreateUser
|
||||
public async store({ auth, request, response, session }: HttpContextContract) {
|
||||
// node ace make:validator CreateDataset
|
||||
try {
|
||||
// Step 2 - Validate request body against the schema
|
||||
// await request.validate(CreateUserValidator);
|
||||
await request.validate({ schema: newDatasetSchema, messages: this.messages });
|
||||
// await request.validate({ schema: newDatasetSchema, messages: this.messages });
|
||||
await request.validate(CreateDatasetValidator);
|
||||
// console.log({ payload });
|
||||
} catch (error) {
|
||||
// Step 3 - Handle errors
|
||||
// return response.badRequest(error.messages);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// const user = new User();
|
||||
// user.email = 'example@example.com';
|
||||
// user.password = 'password';
|
||||
// await user.useTransaction(trx).save();
|
||||
|
||||
let trx: TransactionClientContract | null = null;
|
||||
try {
|
||||
trx = await Database.transaction();
|
||||
const user = (await User.find(auth.user?.id)) as User;
|
||||
|
||||
// const dataset = await user.related('datasets').create({
|
||||
// type: request.input('type'),
|
||||
// creatingCorporation: request.input('creating_corporation'),
|
||||
// language: request.input('language'),
|
||||
// });
|
||||
|
||||
// Create a new instance of the Dataset model:
|
||||
const dataset = new Dataset();
|
||||
dataset.type = request.input('type');
|
||||
dataset.creatingCorporation = request.input('creating_corporation');
|
||||
dataset.language = request.input('language');
|
||||
dataset.embargoDate = request.input('embargo_date');
|
||||
//await dataset.related('user').associate(user); // speichert schon ab
|
||||
// Dataset.$getRelation('user').boot();
|
||||
// Dataset.$getRelation('user').setRelated(dataset, user);
|
||||
// dataset.$setRelated('user', user);
|
||||
await user.useTransaction(trx).related('datasets').save(dataset);
|
||||
|
||||
//store licenses:
|
||||
const licenses: number[] = request.input('licenses', []);
|
||||
dataset.useTransaction(trx).related('licenses').sync(licenses);
|
||||
|
||||
const authors = request.input('authors', []);
|
||||
for (const [key, person] of authors.entries()) {
|
||||
const pivotData = { role: 'author', sort_order: key + 1 };
|
||||
|
||||
if (person.id !== undefined) {
|
||||
await dataset
|
||||
.useTransaction(trx)
|
||||
.related('persons')
|
||||
.attach({
|
||||
[person.id]: {
|
||||
role: pivotData.role,
|
||||
sort_order: pivotData.sort_order,
|
||||
allow_email_contact: false,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const dataPerson = new Person();
|
||||
// use overwritten fill method
|
||||
dataPerson.fill(person);
|
||||
await dataset.useTransaction(trx).related('persons').save(dataPerson, false, {
|
||||
role: pivotData.role,
|
||||
sort_order: pivotData.sort_order,
|
||||
allow_email_contact: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const contributors = request.input('contributors', []);
|
||||
for (const [key, person] of contributors.entries()) {
|
||||
const pivotData = { role: 'contributor', sort_order: key + 1 };
|
||||
|
||||
if (person.id !== undefined) {
|
||||
await dataset
|
||||
.useTransaction(trx)
|
||||
.related('persons')
|
||||
.attach({
|
||||
[person.id]: {
|
||||
role: pivotData.role,
|
||||
sort_order: pivotData.sort_order,
|
||||
allow_email_contact: false,
|
||||
},
|
||||
});
|
||||
} else {
|
||||
const dataPerson = new Person();
|
||||
// use overwritten fill method
|
||||
dataPerson.fill(person);
|
||||
await dataset.useTransaction(trx).related('persons').save(dataPerson, false, {
|
||||
role: pivotData.role,
|
||||
sort_order: pivotData.sort_order,
|
||||
allow_email_contact: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
//save main and additional titles
|
||||
const titles = request.input('titles', []);
|
||||
for (const titleData of titles) {
|
||||
const title = new Title();
|
||||
title.value = titleData.value;
|
||||
title.language = titleData.language;
|
||||
title.type = titleData.type;
|
||||
await dataset.useTransaction(trx).related('titles').save(title);
|
||||
}
|
||||
|
||||
//save abstract and additional descriptions
|
||||
const descriptions = request.input('descriptions', []);
|
||||
for (const descriptionData of descriptions) {
|
||||
// $descriptionReference = new Description($description);
|
||||
// $dataset->abstracts()->save($descriptionReference);
|
||||
const description = new Description();
|
||||
description.value = descriptionData.value;
|
||||
description.language = descriptionData.language;
|
||||
description.type = descriptionData.type;
|
||||
await dataset.useTransaction(trx).related('descriptions').save(description);
|
||||
}
|
||||
|
||||
//save keywords
|
||||
const keywords = request.input('subjects', []);
|
||||
for (const keywordData of keywords) {
|
||||
// $dataKeyword = new Subject($keyword);
|
||||
// $dataset->subjects()->save($dataKeyword);
|
||||
const keyword = await Subject.firstOrNew({ value: keywordData.value, type: keywordData.type }, keywordData);
|
||||
if (keyword.$isNew == true) {
|
||||
await dataset.useTransaction(trx).related('subjects').save(keyword);
|
||||
} else {
|
||||
await dataset.useTransaction(trx).related('subjects').attach([keyword.id]);
|
||||
}
|
||||
}
|
||||
|
||||
// Dataset.$getRelation('persons').boot();
|
||||
// Dataset.$getRelation('persons').pushRelated(dataset, person)
|
||||
// dataset.$pushRelated('persons', person);
|
||||
|
||||
await trx.commit();
|
||||
|
||||
console.log('Users and posts created successfully');
|
||||
} catch (error) {
|
||||
if (trx !== null) {
|
||||
await trx.rollback();
|
||||
}
|
||||
console.error('Failed to create dataset and related models:', error);
|
||||
|
||||
// Handle the error and exit the controller code accordingly
|
||||
// session.flash('message', 'Failed to create dataset and relaed models');
|
||||
// return response.redirect().back();
|
||||
throw error;
|
||||
}
|
||||
|
||||
// save data files:
|
||||
const coverImage = request.files('files')[0];
|
||||
if (coverImage) {
|
||||
// clientName: 'Gehaltsschema.png'
|
||||
|
@ -326,11 +378,6 @@ export default class DatasetController {
|
|||
);
|
||||
// let path = coverImage.filePath;
|
||||
}
|
||||
// const user = await User.create(input);
|
||||
// if (request.input('roles')) {
|
||||
// const roles: Array<number> = request.input('roles');
|
||||
// await user.related('roles').attach(roles);
|
||||
// }
|
||||
|
||||
session.flash('message', 'Dataset has been created successfully');
|
||||
// return response.redirect().toRoute('user.index');
|
||||
|
@ -367,6 +414,7 @@ export default class DatasetController {
|
|||
'after': `{{ field }} must be older than ${dayjs().add(10, 'day')}`,
|
||||
|
||||
'subjects.minLength': 'at least {{ options.minLength }} keywords must be defined',
|
||||
'subjects.uniqueArray': 'The {{ options.array }} array must have unique values based on the {{ options.field }} attribute.',
|
||||
'subjects.*.value.required': 'keyword value is required',
|
||||
'subjects.*.value.minLength': 'keyword value must be at least {{ options.minLength }} characters long',
|
||||
'subjects.*.type.required': 'keyword type is required',
|
||||
|
|
|
@ -18,44 +18,44 @@ import Logger from '@ioc:Adonis/Core/Logger';
|
|||
import HttpExceptionHandler from '@ioc:Adonis/Core/HttpExceptionHandler';
|
||||
|
||||
export default class ExceptionHandler extends HttpExceptionHandler {
|
||||
protected statusPages = {
|
||||
'401,403': 'errors/unauthorized',
|
||||
'404': 'errors/not-found',
|
||||
'500..599': 'errors/server-error',
|
||||
};
|
||||
protected statusPages = {
|
||||
'401,403': 'errors/unauthorized',
|
||||
'404': 'errors/not-found',
|
||||
'500..599': 'errors/server-error',
|
||||
};
|
||||
|
||||
constructor() {
|
||||
super(Logger);
|
||||
}
|
||||
constructor() {
|
||||
super(Logger);
|
||||
}
|
||||
|
||||
public async handle(error: any, ctx: HttpContextContract) {
|
||||
const { response, request, inertia } = ctx;
|
||||
public async handle(error: any, ctx: HttpContextContract) {
|
||||
const { response, request, inertia } = ctx;
|
||||
|
||||
/**
|
||||
* Handle failed authentication attempt
|
||||
*/
|
||||
// if (['E_INVALID_AUTH_PASSWORD', 'E_INVALID_AUTH_UID'].includes(error.code)) {
|
||||
// session.flash('errors', { login: error.message });
|
||||
// return response.redirect('/login');
|
||||
// }
|
||||
// if ([401].includes(error.status)) {
|
||||
// session.flash('errors', { login: error.message });
|
||||
// return response.redirect('/dashboard');
|
||||
// }
|
||||
/**
|
||||
* Handle failed authentication attempt
|
||||
*/
|
||||
// if (['E_INVALID_AUTH_PASSWORD', 'E_INVALID_AUTH_UID'].includes(error.code)) {
|
||||
// session.flash('errors', { login: error.message });
|
||||
// return response.redirect('/login');
|
||||
// }
|
||||
// if ([401].includes(error.status)) {
|
||||
// session.flash('errors', { login: error.message });
|
||||
// return response.redirect('/dashboard');
|
||||
// }
|
||||
|
||||
// https://github.com/inertiajs/inertia-laravel/issues/56
|
||||
if (request.header('X-Inertia') && [500, 503, 404, 403, 401].includes(response.getStatus())) {
|
||||
return inertia.render('Error', {
|
||||
status: response.getStatus(),
|
||||
message: error.message
|
||||
});
|
||||
// ->toResponse($request)
|
||||
// ->setStatusCode($response->status());
|
||||
}
|
||||
// https://github.com/inertiajs/inertia-laravel/issues/56
|
||||
if (request.header('X-Inertia') && [500, 503, 404, 403, 401].includes(response.getStatus())) {
|
||||
return inertia.render('Error', {
|
||||
status: response.getStatus(),
|
||||
message: error.message,
|
||||
});
|
||||
// ->toResponse($request)
|
||||
// ->setStatusCode($response->status());
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward rest of the exceptions to the parent class
|
||||
*/
|
||||
return super.handle(error, ctx);
|
||||
}
|
||||
/**
|
||||
* Forward rest of the exceptions to the parent class
|
||||
*/
|
||||
return super.handle(error, ctx);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import { Exception } from "@adonisjs/core/build/standalone";
|
||||
import { Exception } from '@adonisjs/core/build/standalone';
|
||||
|
||||
/*
|
||||
|--------------------------------------------------------------------------
|
||||
|
@ -23,14 +23,14 @@ export default class InvalidCredentialException extends Exception {
|
|||
* Unable to find user
|
||||
*/
|
||||
static invalidUid() {
|
||||
const error = new this("User not found", 400, "E_INVALID_AUTH_UID");
|
||||
const error = new this('User not found', 400, 'E_INVALID_AUTH_UID');
|
||||
return error;
|
||||
}
|
||||
/**
|
||||
* Invalid user password
|
||||
*/
|
||||
static invalidPassword() {
|
||||
const error = new this("Password mis-match", 400, "E_INVALID_AUTH_PASSWORD");
|
||||
const error = new this('Password mis-match', 400, 'E_INVALID_AUTH_PASSWORD');
|
||||
return error;
|
||||
}
|
||||
|
||||
|
@ -41,18 +41,18 @@ export default class InvalidCredentialException extends Exception {
|
|||
// if (!ctx.session) {
|
||||
// return ctx.response.status(this.status).send(this.responseText);
|
||||
// }
|
||||
ctx.session.flashExcept(["_csrf"]);
|
||||
ctx.session.flash("auth", {
|
||||
ctx.session.flashExcept(['_csrf']);
|
||||
ctx.session.flash('auth', {
|
||||
error: error,
|
||||
/**
|
||||
* Will be removed in the future
|
||||
*/
|
||||
errors: {
|
||||
uid: this.code === "E_INVALID_AUTH_UID" ? ["Invalid login id"] : null,
|
||||
password: this.code === "E_INVALID_AUTH_PASSWORD" ? ["Invalid password"] : null,
|
||||
uid: this.code === 'E_INVALID_AUTH_UID' ? ['Invalid login id'] : null,
|
||||
password: this.code === 'E_INVALID_AUTH_PASSWORD' ? ['Invalid password'] : null,
|
||||
},
|
||||
});
|
||||
ctx.response.redirect("back", true);
|
||||
ctx.response.redirect('back', true);
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
import { AuthenticationException } from '@adonisjs/auth/build/standalone'
|
||||
import type { GuardsList } from '@ioc:Adonis/Addons/Auth'
|
||||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
|
||||
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
|
||||
|
@ -10,67 +10,58 @@ import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
|
|||
* 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
|
||||
* The URL to redirect to when request is Unauthorized
|
||||
*/
|
||||
let guardLastAttempted: string | undefined
|
||||
protected redirectTo = '/app/login';
|
||||
|
||||
for (let guard of guards) {
|
||||
guardLastAttempted = guard
|
||||
|
||||
if (await auth.use(guard).check()) {
|
||||
/**
|
||||
* 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)[]) {
|
||||
/**
|
||||
* Instruct auth to use the given guard as the default guard for
|
||||
* the rest of the request, since the user authenticated
|
||||
* succeeded here
|
||||
* 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
|
||||
*/
|
||||
auth.defaultGuard = guard
|
||||
return true
|
||||
}
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unable to authenticate using any guard
|
||||
* Handle request
|
||||
*/
|
||||
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()
|
||||
}
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
|
|
@ -15,71 +15,74 @@ const userRoleTable = Config.get('rolePermission.user_role_table', 'link_account
|
|||
* Should be called after auth middleware
|
||||
*/
|
||||
export default class Can {
|
||||
/**
|
||||
* Handle request
|
||||
*/
|
||||
public async handle(
|
||||
{ auth, response }: HttpContextContract,
|
||||
next: () => Promise<void>,
|
||||
permissionNames: string[]
|
||||
) {
|
||||
/**
|
||||
* Check if user is logged-in
|
||||
*/
|
||||
let user = await auth.user;
|
||||
if (!user) {
|
||||
return response.unauthorized({ error: 'Must be logged in' });
|
||||
}
|
||||
let hasPermission = await this.checkHasPermissions(user, permissionNames);
|
||||
if (!hasPermission) {
|
||||
// return response.unauthorized({
|
||||
// error: `Doesn't have required role(s): ${permissionNames.join(',')}`,
|
||||
// });
|
||||
throw new Exception(`Doesn't have required permission(s): ${permissionNames.join(',')}`, 401);
|
||||
}
|
||||
await next();
|
||||
}
|
||||
/**
|
||||
* Handle request
|
||||
*/
|
||||
public async handle({ auth, response }: HttpContextContract, next: () => Promise<void>, permissionNames: string[]) {
|
||||
/**
|
||||
* Check if user is logged-in
|
||||
*/
|
||||
let user = await auth.user;
|
||||
if (!user) {
|
||||
return response.unauthorized({ error: 'Must be logged in' });
|
||||
}
|
||||
let hasPermission = await this.checkHasPermissions(user, permissionNames);
|
||||
if (!hasPermission) {
|
||||
// return response.unauthorized({
|
||||
// error: `Doesn't have required role(s): ${permissionNames.join(',')}`,
|
||||
// });
|
||||
throw new Exception(`Doesn't have required permission(s): ${permissionNames.join(',')}`, 401);
|
||||
}
|
||||
await next();
|
||||
}
|
||||
|
||||
private async checkHasPermissions(user: User, permissionNames: Array<string>): Promise<boolean> {
|
||||
let rolePlaceHolder = '(';
|
||||
let placeholders = new Array(permissionNames.length).fill('?');
|
||||
rolePlaceHolder += placeholders.join(',');
|
||||
rolePlaceHolder += ')';
|
||||
private async checkHasPermissions(user: User, permissionNames: Array<string>): Promise<boolean> {
|
||||
let rolePlaceHolder = '(';
|
||||
let placeholders = new Array(permissionNames.length).fill('?');
|
||||
rolePlaceHolder += placeholders.join(',');
|
||||
rolePlaceHolder += ')';
|
||||
|
||||
// let test = user
|
||||
// .related('roles')
|
||||
// .query()
|
||||
// .count('permissions.name')
|
||||
// .innerJoin('gba.role_has_permissions', function () {
|
||||
// this.on('gba.role_has_permissions.role_id', 'roles.id');
|
||||
// })
|
||||
// .innerJoin('gba.permissions', function () {
|
||||
// this.on('role_has_permissions.permission_id', 'permissions.id');
|
||||
// })
|
||||
// .andWhereIn('permissions.name', permissionNames);
|
||||
|
||||
// let test = user
|
||||
// .related('roles')
|
||||
// .query()
|
||||
// .count('permissions.name')
|
||||
// .innerJoin('gba.role_has_permissions', function () {
|
||||
// this.on('gba.role_has_permissions.role_id', 'roles.id');
|
||||
// })
|
||||
// .innerJoin('gba.permissions', function () {
|
||||
// this.on('role_has_permissions.permission_id', 'permissions.id');
|
||||
// })
|
||||
// .andWhereIn('permissions.name', permissionNames);
|
||||
|
||||
// select "permissions"."name"
|
||||
// from "gba"."roles"
|
||||
// inner join "gba"."link_accounts_roles" on "roles"."id" = "link_accounts_roles"."role_id"
|
||||
// inner join "gba"."role_has_permissions" on "gba"."role_has_permissions"."role_id" = "roles"."id"
|
||||
// inner join "gba"."permissions" on "role_has_permissions"."permission_id" = "permissions"."id"
|
||||
// where ("permissions"."name" in ('dataset-list', 'dataset-publish'))
|
||||
// from "gba"."roles"
|
||||
// inner join "gba"."link_accounts_roles" on "roles"."id" = "link_accounts_roles"."role_id"
|
||||
// inner join "gba"."role_has_permissions" on "gba"."role_has_permissions"."role_id" = "roles"."id"
|
||||
// inner join "gba"."permissions" on "role_has_permissions"."permission_id" = "permissions"."id"
|
||||
// where ("permissions"."name" in ('dataset-list', 'dataset-publish'))
|
||||
// and ("link_accounts_roles"."account_id" = 1)
|
||||
|
||||
let {
|
||||
rows: {
|
||||
0: { permissioncount },
|
||||
},
|
||||
} = await Database.rawQuery(
|
||||
'SELECT count("p"."name") as permissionCount FROM ' + roleTable +
|
||||
' r INNER JOIN ' + userRoleTable + ' ur ON ur.role_id=r.id AND "ur"."account_id"=? ' +
|
||||
' INNER JOIN ' + rolePermissionTable + ' rp ON rp.role_id=r.id ' +
|
||||
' INNER JOIN ' + permissionTable + ' p ON rp.permission_id=p.id AND "p"."name" in ' +
|
||||
rolePlaceHolder +
|
||||
' LIMIT 1',
|
||||
[user.id, ...permissionNames]
|
||||
);
|
||||
let {
|
||||
rows: {
|
||||
0: { permissioncount },
|
||||
},
|
||||
} = await Database.rawQuery(
|
||||
'SELECT count("p"."name") as permissionCount FROM ' +
|
||||
roleTable +
|
||||
' r INNER JOIN ' +
|
||||
userRoleTable +
|
||||
' ur ON ur.role_id=r.id AND "ur"."account_id"=? ' +
|
||||
' INNER JOIN ' +
|
||||
rolePermissionTable +
|
||||
' rp ON rp.role_id=r.id ' +
|
||||
' INNER JOIN ' +
|
||||
permissionTable +
|
||||
' p ON rp.permission_id=p.id AND "p"."name" in ' +
|
||||
rolePlaceHolder +
|
||||
' LIMIT 1',
|
||||
[user.id, ...permissionNames],
|
||||
);
|
||||
|
||||
return permissioncount > 0;
|
||||
}
|
||||
return permissioncount > 0;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,11 +1,11 @@
|
|||
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
|
||||
import Config from '@ioc:Adonis/Core/Config'
|
||||
import Database from '@ioc:Adonis/Lucid/Database'
|
||||
import User from 'App/Models/User'
|
||||
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import Config from '@ioc:Adonis/Core/Config';
|
||||
import Database from '@ioc:Adonis/Lucid/Database';
|
||||
import User from 'App/Models/User';
|
||||
// import { Exception } from '@adonisjs/core/build/standalone'
|
||||
|
||||
const roleTable = Config.get('rolePermission.role_table', 'roles')
|
||||
const userRoleTable = Config.get('rolePermission.user_role_table', 'user_roles')
|
||||
const roleTable = Config.get('rolePermission.role_table', 'roles');
|
||||
const userRoleTable = Config.get('rolePermission.user_role_table', 'user_roles');
|
||||
|
||||
/**
|
||||
* Role authentication to check if user has any of the specified roles
|
||||
|
@ -13,54 +13,50 @@ const userRoleTable = Config.get('rolePermission.user_role_table', 'user_roles')
|
|||
* Should be called after auth middleware
|
||||
*/
|
||||
export default class Is {
|
||||
/**
|
||||
* Handle request
|
||||
*/
|
||||
public async handle(
|
||||
{ auth, response }: HttpContextContract,
|
||||
next: () => Promise<void>,
|
||||
roleNames: string[]
|
||||
) {
|
||||
/**
|
||||
* Check if user is logged-in or not.
|
||||
* Handle request
|
||||
*/
|
||||
let user = await auth.user
|
||||
if (!user) {
|
||||
return response.unauthorized({ error: 'Must be logged in' })
|
||||
public async handle({ auth, response }: HttpContextContract, next: () => Promise<void>, roleNames: string[]) {
|
||||
/**
|
||||
* Check if user is logged-in or not.
|
||||
*/
|
||||
let user = await auth.user;
|
||||
if (!user) {
|
||||
return response.unauthorized({ error: 'Must be logged in' });
|
||||
}
|
||||
let hasRole = await this.checkHasRoles(user, roleNames);
|
||||
if (!hasRole) {
|
||||
return response.unauthorized({
|
||||
error: `Doesn't have required role(s): ${roleNames.join(',')}`,
|
||||
});
|
||||
// return new Exception(`Doesn't have required role(s): ${roleNames.join(',')}`,
|
||||
// 401,
|
||||
// "E_INVALID_AUTH_UID");
|
||||
}
|
||||
await next();
|
||||
}
|
||||
let hasRole = await this.checkHasRoles(user, roleNames)
|
||||
if (!hasRole) {
|
||||
return response.unauthorized({
|
||||
error: `Doesn't have required role(s): ${roleNames.join(',')}`,
|
||||
})
|
||||
// return new Exception(`Doesn't have required role(s): ${roleNames.join(',')}`,
|
||||
// 401,
|
||||
// "E_INVALID_AUTH_UID");
|
||||
|
||||
private async checkHasRoles(user: User, roleNames: Array<string>): Promise<boolean> {
|
||||
let rolePlaceHolder = '(';
|
||||
let placeholders = new Array(roleNames.length).fill('?');
|
||||
rolePlaceHolder += placeholders.join(',');
|
||||
rolePlaceHolder += ')';
|
||||
|
||||
let {
|
||||
0: {
|
||||
0: { roleCount },
|
||||
},
|
||||
} = await Database.rawQuery(
|
||||
'SELECT count(`ur`.`id`) as roleCount FROM ' +
|
||||
userRoleTable +
|
||||
' ur INNER JOIN ' +
|
||||
roleTable +
|
||||
' r ON ur.role_id=r.id WHERE `ur`.`user_id`=? AND `r`.`name` in ' +
|
||||
rolePlaceHolder +
|
||||
' LIMIT 1',
|
||||
[user.id, ...roleNames],
|
||||
);
|
||||
|
||||
return roleCount > 0;
|
||||
}
|
||||
await next()
|
||||
}
|
||||
|
||||
private async checkHasRoles(user: User, roleNames: Array<string>): Promise<boolean> {
|
||||
let rolePlaceHolder = '('
|
||||
let placeholders = new Array(roleNames.length).fill('?')
|
||||
rolePlaceHolder += placeholders.join(',')
|
||||
rolePlaceHolder += ')'
|
||||
|
||||
let {
|
||||
0: {
|
||||
0: { roleCount },
|
||||
},
|
||||
} = await Database.rawQuery(
|
||||
'SELECT count(`ur`.`id`) as roleCount FROM ' +
|
||||
userRoleTable +
|
||||
' ur INNER JOIN ' +
|
||||
roleTable +
|
||||
' r ON ur.role_id=r.id WHERE `ur`.`user_id`=? AND `r`.`name` in ' +
|
||||
rolePlaceHolder +
|
||||
' LIMIT 1',
|
||||
[user.id, ...roleNames]
|
||||
)
|
||||
|
||||
return roleCount > 0
|
||||
}
|
||||
}
|
||||
|
|
|
@ -7,77 +7,72 @@ import { Exception } from '@adonisjs/core/build/standalone';
|
|||
const roleTable = Config.get('rolePermission.role_table', 'roles');
|
||||
const userRoleTable = Config.get('rolePermission.user_role_table', 'link_accounts_roles');
|
||||
|
||||
|
||||
// node ace make:middleware role
|
||||
export default class Role {
|
||||
// .middleware(['auth', 'role:admin,moderator'])
|
||||
public async handle(
|
||||
{ auth, response }: HttpContextContract,
|
||||
next: () => Promise<void>,
|
||||
userRoles: string[]
|
||||
) {
|
||||
// Check if user is logged-in or not.
|
||||
// let expression = "";
|
||||
// if (Array.isArray(args)) {
|
||||
// expression = args.join(" || ");
|
||||
// }
|
||||
// .middleware(['auth', 'role:admin,moderator'])
|
||||
public async handle({ auth, response }: HttpContextContract, next: () => Promise<void>, userRoles: string[]) {
|
||||
// Check if user is logged-in or not.
|
||||
// let expression = "";
|
||||
// if (Array.isArray(args)) {
|
||||
// expression = args.join(" || ");
|
||||
// }
|
||||
|
||||
let user = await auth.user;
|
||||
if (!user) {
|
||||
return response.unauthorized({ error: 'Must be logged in' });
|
||||
}
|
||||
let user = await auth.user;
|
||||
if (!user) {
|
||||
return response.unauthorized({ error: 'Must be logged in' });
|
||||
}
|
||||
|
||||
let hasRole = await this.checkHasRoles(user, userRoles);
|
||||
if (!hasRole) {
|
||||
// return response.unauthorized({
|
||||
// error: `Doesn't have required role(s): ${userRoles.join(',')}`,
|
||||
// // error: `Doesn't have required role(s)`,
|
||||
// });
|
||||
throw new Exception(`Doesn't have required role(s): ${userRoles.join(',')}`, 401);
|
||||
}
|
||||
let hasRole = await this.checkHasRoles(user, userRoles);
|
||||
if (!hasRole) {
|
||||
// return response.unauthorized({
|
||||
// error: `Doesn't have required role(s): ${userRoles.join(',')}`,
|
||||
// // error: `Doesn't have required role(s)`,
|
||||
// });
|
||||
throw new Exception(`Doesn't have required role(s): ${userRoles.join(',')}`, 401);
|
||||
}
|
||||
|
||||
// code for middleware goes here. ABOVE THE NEXT CALL
|
||||
await next();
|
||||
}
|
||||
// code for middleware goes here. ABOVE THE NEXT CALL
|
||||
await next();
|
||||
}
|
||||
|
||||
private async checkHasRoles(user: User, userRoles: string[]): Promise<boolean> {
|
||||
// await user.load("roles");
|
||||
// const ok = user.roles.map((role) => role.name);
|
||||
// const roles = await user.getRoles();
|
||||
private async checkHasRoles(user: User, userRoles: string[]): Promise<boolean> {
|
||||
// await user.load("roles");
|
||||
// const ok = user.roles.map((role) => role.name);
|
||||
// const roles = await user.getRoles();
|
||||
|
||||
let rolePlaceHolder = '(';
|
||||
let placeholders = new Array(userRoles.length).fill('?');
|
||||
rolePlaceHolder += placeholders.join(',');
|
||||
rolePlaceHolder += ')';
|
||||
let rolePlaceHolder = '(';
|
||||
let placeholders = new Array(userRoles.length).fill('?');
|
||||
rolePlaceHolder += placeholders.join(',');
|
||||
rolePlaceHolder += ')';
|
||||
|
||||
// const roles = await user
|
||||
// .related('roles')
|
||||
// .query()
|
||||
// .count('*') // .select('name')
|
||||
// .whereIn('name', userRoles);
|
||||
// // .groupBy('name');
|
||||
// const roles = await user
|
||||
// .related('roles')
|
||||
// .query()
|
||||
// .count('*') // .select('name')
|
||||
// .whereIn('name', userRoles);
|
||||
// // .groupBy('name');
|
||||
|
||||
// select count(*) as roleCount
|
||||
// from gba.roles
|
||||
// inner join gba.link_accounts_roles
|
||||
// on "roles"."id" = "link_accounts_roles"."role_id"
|
||||
// where ("name" in ('administrator', 'editor')) and ("link_accounts_roles"."account_id" = 1)
|
||||
// select count(*) as roleCount
|
||||
// from gba.roles
|
||||
// inner join gba.link_accounts_roles
|
||||
// on "roles"."id" = "link_accounts_roles"."role_id"
|
||||
// where ("name" in ('administrator', 'editor')) and ("link_accounts_roles"."account_id" = 1)
|
||||
|
||||
let {
|
||||
rows: {
|
||||
0: { rolecount },
|
||||
},
|
||||
} = await Database.rawQuery(
|
||||
'SELECT count("r"."id") as roleCount FROM ' +
|
||||
roleTable +
|
||||
' r INNER JOIN ' +
|
||||
userRoleTable +
|
||||
' ur ON r.id=ur.role_id WHERE "ur"."account_id"=? AND "r"."name" in ' +
|
||||
rolePlaceHolder +
|
||||
' LIMIT 1',
|
||||
[user.id, ...userRoles]
|
||||
);
|
||||
let {
|
||||
rows: {
|
||||
0: { rolecount },
|
||||
},
|
||||
} = await Database.rawQuery(
|
||||
'SELECT count("r"."id") as roleCount FROM ' +
|
||||
roleTable +
|
||||
' r INNER JOIN ' +
|
||||
userRoleTable +
|
||||
' ur ON r.id=ur.role_id WHERE "ur"."account_id"=? AND "r"."name" in ' +
|
||||
rolePlaceHolder +
|
||||
' LIMIT 1',
|
||||
[user.id, ...userRoles],
|
||||
);
|
||||
|
||||
return rolecount > 0;
|
||||
}
|
||||
return rolecount > 0;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
|
||||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
|
||||
/**
|
||||
* Silent auth middleware can be used as a global middleware to silent check
|
||||
|
@ -7,15 +7,15 @@ import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
|
|||
* The request continues as usual, even when the user is not logged-in.
|
||||
*/
|
||||
export default class SilentAuthMiddleware {
|
||||
/**
|
||||
* Handle request
|
||||
*/
|
||||
public async handle({ auth }: HttpContextContract, next: () => Promise<void>) {
|
||||
/**
|
||||
* Check if user is logged-in or not. If yes, then `ctx.auth.user` will be
|
||||
* set to the instance of the currently logged in user.
|
||||
* Handle request
|
||||
*/
|
||||
await auth.check()
|
||||
await next()
|
||||
}
|
||||
public async handle({ auth }: HttpContextContract, next: () => Promise<void>) {
|
||||
/**
|
||||
* Check if user is logged-in or not. If yes, then `ctx.auth.user` will be
|
||||
* set to the instance of the currently logged in user.
|
||||
*/
|
||||
await auth.check();
|
||||
await next();
|
||||
}
|
||||
}
|
||||
|
|
119
app/Models/BaseModel.ts
Normal file
119
app/Models/BaseModel.ts
Normal file
|
@ -0,0 +1,119 @@
|
|||
import { BaseModel as LucidBaseModel } from '@ioc:Adonis/Lucid/Orm';
|
||||
// import { ManyToManyQueryClient } from '@ioc:Adonis/Lucid/Orm';
|
||||
|
||||
// export class CustomManyToManyQueryClient extends ManyToManyQueryClient {
|
||||
// public attach(
|
||||
// relatedIds: any | any[],
|
||||
// pivotAttributes: any = {},
|
||||
// trx?: ReturnType<typeof this.model.transaction>
|
||||
// ) {
|
||||
// return super.attach(relatedIds, (row) => {
|
||||
// row.pivot.fill(pivotAttributes);
|
||||
// }, trx);
|
||||
// }
|
||||
// }
|
||||
|
||||
/**
|
||||
* Helper to find if value is a valid Object or
|
||||
* not
|
||||
*/
|
||||
export function isObject(value: any): boolean {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export default class BaseModel extends LucidBaseModel {
|
||||
/**
|
||||
* When `fill` method is called, then we may have a situation where it
|
||||
* removed the values which exists in `original` and hence the dirty
|
||||
* diff has to do a negative diff as well
|
||||
*/
|
||||
// private fillInvoked: boolean = false;
|
||||
|
||||
public static fillable: string[] = [];
|
||||
|
||||
public fill(attributes: any, allowExtraProperties: boolean = false): this {
|
||||
this.$attributes = {};
|
||||
// const Model = this.constructor as typeof BaseModel;
|
||||
|
||||
// for (const key in attributes) {
|
||||
// if (Model.fillable.includes(key)) {
|
||||
// const value = attributes[key];
|
||||
// if (Model.$hasColumn(key)) {
|
||||
// this[key] = value;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
this.mergeFillableAttributes(attributes, allowExtraProperties);
|
||||
// this.fillInvoked = true;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge bulk attributes with existing attributes.
|
||||
*
|
||||
* 1. If key is unknown, it will be added to the `extras` object.
|
||||
* 2. If key is defined as a relationship, it will be ignored and one must call `$setRelated`.
|
||||
*/
|
||||
public mergeFillableAttributes(values: any, allowExtraProperties: boolean = false): this {
|
||||
const Model = this.constructor as typeof BaseModel;
|
||||
|
||||
/**
|
||||
* Merge values with the attributes
|
||||
*/
|
||||
if (isObject(values)) {
|
||||
// Object.keys(values).forEach((key) => {
|
||||
for (const key in values) {
|
||||
if (Model.fillable.includes(key)) {
|
||||
const value = values[key];
|
||||
|
||||
/**
|
||||
* Set as column
|
||||
*/
|
||||
if (Model.$hasColumn(key)) {
|
||||
this[key] = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the attribute name from the column names. Since people
|
||||
* usaully define the column names directly as well by
|
||||
* accepting them directly from the API.
|
||||
*/
|
||||
const attributeName = Model.$keys.columnsToAttributes.get(key);
|
||||
if (attributeName) {
|
||||
this[attributeName] = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
/**
|
||||
* If key is defined as a relation, then ignore it, since one
|
||||
* must pass a qualified model to `this.$setRelated()`
|
||||
*/
|
||||
if (Model.$relationsDefinitions.has(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
/**
|
||||
* If the property already exists on the model, then set it
|
||||
* as it is vs defining it as an extra property
|
||||
*/
|
||||
if (this.hasOwnProperty(key)) {
|
||||
this[key] = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Raise error when not instructed to ignore non-existing properties.
|
||||
*/
|
||||
if (!allowExtraProperties) {
|
||||
throw new Error(`Cannot define "${key}" on "${Model.name}" model, since it is not defined as a model property`);
|
||||
}
|
||||
|
||||
this.$extras[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
}
|
|
@ -1,52 +1,108 @@
|
|||
import {
|
||||
column,
|
||||
BaseModel,
|
||||
SnakeCaseNamingStrategy,
|
||||
// computed,
|
||||
manyToMany,
|
||||
ManyToMany,
|
||||
column,
|
||||
BaseModel,
|
||||
SnakeCaseNamingStrategy,
|
||||
manyToMany,
|
||||
ManyToMany,
|
||||
belongsTo,
|
||||
BelongsTo,
|
||||
hasMany,
|
||||
HasMany,
|
||||
} from '@ioc:Adonis/Lucid/Orm';
|
||||
import { DateTime } from 'luxon';
|
||||
import Person from './Person';
|
||||
|
||||
import User from './User';
|
||||
import Title from './Title';
|
||||
import Description from './Description';
|
||||
import License from './License';
|
||||
import Subject from './Subject';
|
||||
|
||||
export default class Dataset extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
public static primaryKey = 'id';
|
||||
public static table = 'documents';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
public static primaryKey = 'id';
|
||||
public static table = 'documents';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
|
||||
@column({ isPrimary: true })
|
||||
public id: number;
|
||||
@column({ isPrimary: true })
|
||||
public id: number;
|
||||
|
||||
@column({})
|
||||
public server_state: boolean;
|
||||
public server_state: boolean;
|
||||
|
||||
@column({})
|
||||
public publisherName: string;
|
||||
public publisherName: string;
|
||||
|
||||
@column({ columnName: 'creating_corporation' })
|
||||
public creatingCorporation: string;
|
||||
|
||||
@column.dateTime({ columnName: 'embargo_date' })
|
||||
public embargoDate: DateTime;
|
||||
public embargoDate: DateTime;
|
||||
|
||||
@column({})
|
||||
public type: string;
|
||||
public type: string;
|
||||
|
||||
@column({})
|
||||
public language: string;
|
||||
|
||||
@column.dateTime({ columnName: 'server_date_published' })
|
||||
public serverDatePublished: DateTime;
|
||||
@column({})
|
||||
public account_id: number | null = null;
|
||||
|
||||
@column.dateTime({ autoCreate: true, columnName: 'created_at' })
|
||||
public createdAt: DateTime;
|
||||
@column.dateTime({ columnName: 'server_date_published' })
|
||||
public serverDatePublished: DateTime;
|
||||
|
||||
@column.dateTime({ autoCreate: true, autoUpdate: true })
|
||||
public updatedAt: DateTime;
|
||||
@column.dateTime({ autoCreate: true, columnName: 'created_at' })
|
||||
public createdAt: DateTime;
|
||||
|
||||
@column.dateTime({ autoCreate: true, autoUpdate: true, columnName: 'server_date_modified' })
|
||||
public updatedAt: DateTime;
|
||||
|
||||
@manyToMany(() => Person, {
|
||||
pivotForeignKey: 'document_id',
|
||||
pivotRelatedForeignKey: 'person_id',
|
||||
pivotTable: 'link_documents_persons',
|
||||
pivotColumns: ['role', 'sort_order', 'allow_email_contact']
|
||||
})
|
||||
public persons: ManyToMany<typeof Person>;
|
||||
pivotForeignKey: 'document_id',
|
||||
pivotRelatedForeignKey: 'person_id',
|
||||
pivotTable: 'link_documents_persons',
|
||||
pivotColumns: ['role', 'sort_order', 'allow_email_contact'],
|
||||
})
|
||||
public persons: ManyToMany<typeof Person>;
|
||||
|
||||
/**
|
||||
* Get the account that the dataset belongs to
|
||||
*/
|
||||
@belongsTo(() => User, {
|
||||
foreignKey: 'account_id',
|
||||
})
|
||||
public user: BelongsTo<typeof User>;
|
||||
|
||||
@hasMany(() => Title, {
|
||||
foreignKey: 'document_id',
|
||||
})
|
||||
public titles: HasMany<typeof Title>;
|
||||
|
||||
@hasMany(() => Description, {
|
||||
foreignKey: 'document_id',
|
||||
})
|
||||
public descriptions: HasMany<typeof Description>;
|
||||
|
||||
@manyToMany(() => License, {
|
||||
pivotForeignKey: 'document_id',
|
||||
pivotRelatedForeignKey: 'licence_id',
|
||||
pivotTable: 'link_documents_licences',
|
||||
})
|
||||
public licenses: ManyToMany<typeof License>;
|
||||
|
||||
// public function subjects()
|
||||
// {
|
||||
// return $this->belongsToMany(\App\Models\Subject::class, 'link_dataset_subjects', 'document_id', 'subject_id');
|
||||
// }
|
||||
@manyToMany(() => Subject, {
|
||||
pivotForeignKey: 'document_id',
|
||||
pivotRelatedForeignKey: 'subject_id',
|
||||
pivotTable: 'link_dataset_subjects',
|
||||
})
|
||||
public subjects: ManyToMany<typeof Subject>;
|
||||
|
||||
// async save(): Promise<this> {
|
||||
// // Call the parent save method to persist changes to the database
|
||||
// await super.save();
|
||||
// return this;
|
||||
// }
|
||||
}
|
||||
|
|
28
app/Models/Description.ts
Normal file
28
app/Models/Description.ts
Normal file
|
@ -0,0 +1,28 @@
|
|||
import { column, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Dataset from './Dataset';
|
||||
import BaseModel from './BaseModel';
|
||||
|
||||
export default class Description extends BaseModel {
|
||||
public static primaryKey = 'id';
|
||||
public static table = 'dataset_abstracts';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
public static timestamps = false;
|
||||
public static fillable: string[] = ['value', 'type', 'language'];
|
||||
|
||||
@column({})
|
||||
public document_id: number;
|
||||
|
||||
@column()
|
||||
public type: string;
|
||||
|
||||
@column()
|
||||
public value: string;
|
||||
|
||||
@column()
|
||||
public language: string;
|
||||
|
||||
@belongsTo(() => Dataset, {
|
||||
foreignKey: 'document_id',
|
||||
})
|
||||
public dataset: BelongsTo<typeof Dataset>;
|
||||
}
|
|
@ -1,54 +1,55 @@
|
|||
import { DateTime } from 'luxon';
|
||||
import {
|
||||
column,
|
||||
BaseModel,
|
||||
hasMany, HasMany,
|
||||
// manyToMany,
|
||||
// ManyToMany,
|
||||
SnakeCaseNamingStrategy,
|
||||
column,
|
||||
BaseModel,
|
||||
hasMany,
|
||||
HasMany,
|
||||
// manyToMany,
|
||||
// ManyToMany,
|
||||
SnakeCaseNamingStrategy,
|
||||
} from '@ioc:Adonis/Lucid/Orm';
|
||||
import HashValue from './HashValue';
|
||||
|
||||
export default class File extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
public static primaryKey = 'id';
|
||||
public static table = 'document_files';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
public static primaryKey = 'id';
|
||||
public static table = 'document_files';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
|
||||
@column({
|
||||
isPrimary: true,
|
||||
})
|
||||
public id: number;
|
||||
@column({
|
||||
isPrimary: true,
|
||||
})
|
||||
public id: number;
|
||||
|
||||
@column({})
|
||||
public pathName: string;
|
||||
|
||||
@column()
|
||||
public label: string;
|
||||
@column({})
|
||||
public pathName: string;
|
||||
|
||||
@column()
|
||||
public comment: string;
|
||||
public label: string;
|
||||
|
||||
@column()
|
||||
public mimetype: string;
|
||||
public comment: string;
|
||||
|
||||
@column()
|
||||
public language: string;
|
||||
public mimetype: string;
|
||||
|
||||
@column()
|
||||
public fileSize: bigint;
|
||||
public language: string;
|
||||
|
||||
@column()
|
||||
public visibleInOai: boolean;
|
||||
public fileSize: bigint;
|
||||
|
||||
@column()
|
||||
public sortOrder: number;
|
||||
public visibleInOai: boolean;
|
||||
|
||||
@column()
|
||||
public sortOrder: number;
|
||||
|
||||
@column.dateTime({ autoCreate: true })
|
||||
public createdAt: DateTime;
|
||||
public createdAt: DateTime;
|
||||
|
||||
@column.dateTime({ autoCreate: true, autoUpdate: true })
|
||||
public updatedAt: DateTime;
|
||||
@column.dateTime({ autoCreate: true, autoUpdate: true })
|
||||
public updatedAt: DateTime;
|
||||
|
||||
// public function hashvalues()
|
||||
// {
|
||||
|
@ -58,5 +59,5 @@ export default class File extends BaseModel {
|
|||
@hasMany(() => HashValue, {
|
||||
foreignKey: 'file_id',
|
||||
})
|
||||
public hashvalues: HasMany<typeof HashValue>;
|
||||
}
|
||||
public hashvalues: HasMany<typeof HashValue>;
|
||||
}
|
||||
|
|
|
@ -1,41 +1,34 @@
|
|||
import {
|
||||
column,
|
||||
BaseModel,
|
||||
belongsTo,
|
||||
BelongsTo,
|
||||
SnakeCaseNamingStrategy,
|
||||
} from '@ioc:Adonis/Lucid/Orm';
|
||||
import { column, BaseModel, belongsTo, BelongsTo, SnakeCaseNamingStrategy } from '@ioc:Adonis/Lucid/Orm';
|
||||
import File from './File';
|
||||
|
||||
export default class HashValue extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
public static primaryKey = 'file_id, type';
|
||||
public static table = 'file_hashvalues';
|
||||
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
public static primaryKey = 'file_id, type';
|
||||
public static table = 'file_hashvalues';
|
||||
|
||||
// static get primaryKey () {
|
||||
// return 'type, value'
|
||||
// }
|
||||
|
||||
static get incrementing () {
|
||||
return false
|
||||
}
|
||||
static get incrementing() {
|
||||
return false;
|
||||
}
|
||||
|
||||
// @column({
|
||||
// isPrimary: true,
|
||||
// })
|
||||
// public id: number;
|
||||
|
||||
// Foreign key is still on the same model
|
||||
// @column({
|
||||
// isPrimary: true,
|
||||
// })
|
||||
// public id: number;
|
||||
|
||||
// Foreign key is still on the same model
|
||||
@column({})
|
||||
public file_id: number;
|
||||
public file_id: number;
|
||||
|
||||
@column({})
|
||||
public type: string;
|
||||
public type: string;
|
||||
|
||||
@column()
|
||||
public value: string;
|
||||
@column()
|
||||
public value: string;
|
||||
|
||||
@belongsTo(() => File)
|
||||
public file: BelongsTo<typeof File>
|
||||
|
||||
}
|
||||
public file: BelongsTo<typeof File>;
|
||||
}
|
||||
|
|
|
@ -5,6 +5,22 @@ export default class License extends BaseModel {
|
|||
public static primaryKey = 'id';
|
||||
public static table = 'document_licences';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
public static timestamps = false;
|
||||
public static fillable: string[] = [
|
||||
'name_long',
|
||||
'name',
|
||||
'language',
|
||||
'link_licence',
|
||||
'link_logo',
|
||||
'desc_text',
|
||||
'desc_markup',
|
||||
'comment_internal',
|
||||
'mime_type',
|
||||
'sort_order',
|
||||
'language',
|
||||
'active',
|
||||
'pod_allowed',
|
||||
];
|
||||
|
||||
@column({
|
||||
isPrimary: true,
|
||||
|
|
|
@ -1,100 +1,92 @@
|
|||
import {
|
||||
column,
|
||||
BaseModel,
|
||||
manyToMany,
|
||||
ManyToMany,
|
||||
SnakeCaseNamingStrategy,
|
||||
beforeUpdate,
|
||||
beforeCreate,
|
||||
} from '@ioc:Adonis/Lucid/Orm';
|
||||
import { column, BaseModel, manyToMany, ManyToMany, SnakeCaseNamingStrategy, beforeUpdate, beforeCreate } from '@ioc:Adonis/Lucid/Orm';
|
||||
import { DateTime } from 'luxon';
|
||||
import dayjs from 'dayjs';
|
||||
import Role from 'App/Models/Role';
|
||||
|
||||
export default class Permission extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
public static primaryKey = 'id';
|
||||
public static table = 'permissions';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
public static primaryKey = 'id';
|
||||
public static table = 'permissions';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
|
||||
@column({
|
||||
isPrimary: true,
|
||||
})
|
||||
public id: number;
|
||||
@column({
|
||||
isPrimary: true,
|
||||
})
|
||||
public id: number;
|
||||
|
||||
@column({})
|
||||
public role_id: number;
|
||||
@column({})
|
||||
public role_id: number;
|
||||
|
||||
@column({})
|
||||
public display_name: string;
|
||||
@column({})
|
||||
public display_name: string;
|
||||
|
||||
@column({})
|
||||
public name: string;
|
||||
@column({})
|
||||
public name: string;
|
||||
|
||||
@column({})
|
||||
public description: string;
|
||||
@column({})
|
||||
public description: string;
|
||||
|
||||
@column.dateTime({
|
||||
serialize: (value: Date | null) => {
|
||||
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
|
||||
},
|
||||
autoCreate: true,
|
||||
})
|
||||
public created_at: DateTime;
|
||||
@column.dateTime({
|
||||
serialize: (value: Date | null) => {
|
||||
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
|
||||
},
|
||||
autoCreate: true,
|
||||
})
|
||||
public created_at: DateTime;
|
||||
|
||||
@column.dateTime({
|
||||
serialize: (value: Date | null) => {
|
||||
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
|
||||
},
|
||||
autoCreate: true,
|
||||
autoUpdate: true,
|
||||
})
|
||||
public updated_at: DateTime;
|
||||
@column.dateTime({
|
||||
serialize: (value: Date | null) => {
|
||||
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
|
||||
},
|
||||
autoCreate: true,
|
||||
autoUpdate: true,
|
||||
})
|
||||
public updated_at: DateTime;
|
||||
|
||||
@beforeCreate()
|
||||
@beforeUpdate()
|
||||
public static async resetDate(role) {
|
||||
role.created_at = this.formatDateTime(role.created_at);
|
||||
role.updated_at = this.formatDateTime(role.updated_at);
|
||||
}
|
||||
@beforeCreate()
|
||||
@beforeUpdate()
|
||||
public static async resetDate(role) {
|
||||
role.created_at = this.formatDateTime(role.created_at);
|
||||
role.updated_at = this.formatDateTime(role.updated_at);
|
||||
}
|
||||
|
||||
// public static boot() {
|
||||
// super.boot()
|
||||
// public static boot() {
|
||||
// super.boot()
|
||||
|
||||
// this.before('create', async (_modelInstance) => {
|
||||
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at)
|
||||
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at)
|
||||
// })
|
||||
// this.before('update', async (_modelInstance) => {
|
||||
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at)
|
||||
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at)
|
||||
// })
|
||||
// }
|
||||
// this.before('create', async (_modelInstance) => {
|
||||
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at)
|
||||
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at)
|
||||
// })
|
||||
// this.before('update', async (_modelInstance) => {
|
||||
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at)
|
||||
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at)
|
||||
// })
|
||||
// }
|
||||
|
||||
private static formatDateTime(datetime) {
|
||||
let value = new Date(datetime);
|
||||
return datetime
|
||||
? value.getFullYear() +
|
||||
'-' +
|
||||
(value.getMonth() + 1) +
|
||||
'-' +
|
||||
value.getDate() +
|
||||
' ' +
|
||||
value.getHours() +
|
||||
':' +
|
||||
value.getMinutes() +
|
||||
':' +
|
||||
value.getSeconds()
|
||||
: datetime;
|
||||
}
|
||||
private static formatDateTime(datetime) {
|
||||
let value = new Date(datetime);
|
||||
return datetime
|
||||
? value.getFullYear() +
|
||||
'-' +
|
||||
(value.getMonth() + 1) +
|
||||
'-' +
|
||||
value.getDate() +
|
||||
' ' +
|
||||
value.getHours() +
|
||||
':' +
|
||||
value.getMinutes() +
|
||||
':' +
|
||||
value.getSeconds()
|
||||
: datetime;
|
||||
}
|
||||
|
||||
// @belongsTo(() => Role)
|
||||
// public role: BelongsTo<typeof Role>;
|
||||
// @belongsTo(() => Role)
|
||||
// public role: BelongsTo<typeof Role>;
|
||||
|
||||
@manyToMany(() => Role, {
|
||||
pivotForeignKey: 'permission_id',
|
||||
pivotRelatedForeignKey: 'role_id',
|
||||
pivotTable: 'role_has_permissions',
|
||||
})
|
||||
public roles: ManyToMany<typeof Role>;
|
||||
@manyToMany(() => Role, {
|
||||
pivotForeignKey: 'permission_id',
|
||||
pivotRelatedForeignKey: 'role_id',
|
||||
pivotTable: 'role_has_permissions',
|
||||
})
|
||||
public roles: ManyToMany<typeof Role>;
|
||||
}
|
||||
|
|
|
@ -1,83 +1,79 @@
|
|||
import {
|
||||
column,
|
||||
BaseModel,
|
||||
SnakeCaseNamingStrategy,
|
||||
computed,
|
||||
manyToMany,
|
||||
ManyToMany,
|
||||
} from '@ioc:Adonis/Lucid/Orm';
|
||||
import { column, SnakeCaseNamingStrategy, computed, manyToMany, ManyToMany } from '@ioc:Adonis/Lucid/Orm';
|
||||
import { DateTime } from 'luxon';
|
||||
import dayjs from 'dayjs';
|
||||
import Dataset from './Dataset';
|
||||
import BaseModel from './BaseModel';
|
||||
|
||||
export default class Person extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
public static primaryKey = 'id';
|
||||
public static table = 'persons';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
public static primaryKey = 'id';
|
||||
public static table = 'persons';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
// only the academic_title, email, first_name, identifier_orcid, last_name and name_type attributes are allowed to be mass assigned.
|
||||
public static fillable: string[] = ['academic_title', 'email', 'first_name', 'identifier_orcid', 'last_name', 'name_type'];
|
||||
|
||||
@column({
|
||||
isPrimary: true,
|
||||
})
|
||||
public id: number;
|
||||
|
||||
@column({})
|
||||
public academicTitle: string;
|
||||
|
||||
@column()
|
||||
public email: string;
|
||||
|
||||
@column({})
|
||||
public firstName: string;
|
||||
|
||||
@column({})
|
||||
public lastName: string;
|
||||
|
||||
@column({})
|
||||
public identifierOrcid: string;
|
||||
|
||||
@column({})
|
||||
public status: boolean;
|
||||
|
||||
@column({})
|
||||
public nameType: string;
|
||||
|
||||
@column.dateTime({
|
||||
serialize: (value: Date | null) => {
|
||||
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
|
||||
},
|
||||
autoCreate: true,
|
||||
})
|
||||
public createdAt: DateTime;
|
||||
|
||||
@computed({
|
||||
serializeAs: 'name'
|
||||
@column({
|
||||
isPrimary: true,
|
||||
})
|
||||
public get fullName() {
|
||||
return `${this.firstName} ${this.lastName}`;
|
||||
}
|
||||
public id: number;
|
||||
|
||||
@column({ columnName: 'academic_title' })
|
||||
public academicTitle: string;
|
||||
|
||||
@column()
|
||||
public email: string;
|
||||
|
||||
@column({})
|
||||
public firstName: string;
|
||||
|
||||
@column({})
|
||||
public lastName: string;
|
||||
|
||||
@column({})
|
||||
public identifierOrcid: string;
|
||||
|
||||
@column({})
|
||||
public status: boolean;
|
||||
|
||||
@column({})
|
||||
public nameType: string;
|
||||
|
||||
@column.dateTime({
|
||||
serialize: (value: Date | null) => {
|
||||
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
|
||||
},
|
||||
autoCreate: true,
|
||||
})
|
||||
public createdAt: DateTime;
|
||||
|
||||
@computed({
|
||||
serializeAs: 'name',
|
||||
})
|
||||
public get fullName() {
|
||||
return `${this.firstName} ${this.lastName}`;
|
||||
}
|
||||
|
||||
// @computed()
|
||||
// public get progress(): number {
|
||||
// return 50;
|
||||
// }
|
||||
// public get progress(): number {
|
||||
// return 50;
|
||||
// }
|
||||
|
||||
// @computed()
|
||||
// public get created_at() {
|
||||
// return '2023-03-21 08:45:00';
|
||||
// }
|
||||
// public get created_at() {
|
||||
// return '2023-03-21 08:45:00';
|
||||
// }
|
||||
|
||||
@computed()
|
||||
public get datasetCount() {
|
||||
const stock = this.$extras.datasets_count //my pivot column name was "stock"
|
||||
return stock
|
||||
}
|
||||
const stock = this.$extras.datasets_count; //my pivot column name was "stock"
|
||||
return stock;
|
||||
}
|
||||
|
||||
@manyToMany(() => Dataset, {
|
||||
pivotForeignKey: 'person_id',
|
||||
pivotRelatedForeignKey: 'document_id',
|
||||
pivotTable: 'link_documents_persons',
|
||||
pivotColumns: ['role', 'sort_order', 'allow_email_contact']
|
||||
})
|
||||
public datasets: ManyToMany<typeof Dataset>;
|
||||
@manyToMany(() => Dataset, {
|
||||
pivotForeignKey: 'person_id',
|
||||
pivotRelatedForeignKey: 'document_id',
|
||||
pivotTable: 'link_documents_persons',
|
||||
pivotColumns: ['role', 'sort_order', 'allow_email_contact'],
|
||||
})
|
||||
public datasets: ManyToMany<typeof Dataset>;
|
||||
}
|
||||
|
|
|
@ -12,7 +12,6 @@ export default class Project extends BaseModel {
|
|||
})
|
||||
public id: number;
|
||||
|
||||
|
||||
@column({})
|
||||
public label: string;
|
||||
|
||||
|
@ -24,14 +23,12 @@ export default class Project extends BaseModel {
|
|||
|
||||
@column.dateTime({
|
||||
autoCreate: true,
|
||||
})
|
||||
public created_at: DateTime;
|
||||
})
|
||||
public created_at: DateTime;
|
||||
|
||||
@column.dateTime({
|
||||
@column.dateTime({
|
||||
autoCreate: true,
|
||||
autoUpdate: true
|
||||
})
|
||||
public updated_at: DateTime;
|
||||
|
||||
|
||||
autoUpdate: true,
|
||||
})
|
||||
public updated_at: DateTime;
|
||||
}
|
||||
|
|
|
@ -1,12 +1,4 @@
|
|||
import {
|
||||
column,
|
||||
BaseModel,
|
||||
SnakeCaseNamingStrategy,
|
||||
manyToMany,
|
||||
ManyToMany,
|
||||
beforeCreate,
|
||||
beforeUpdate,
|
||||
} from '@ioc:Adonis/Lucid/Orm';
|
||||
import { column, BaseModel, SnakeCaseNamingStrategy, manyToMany, ManyToMany, beforeCreate, beforeUpdate } from '@ioc:Adonis/Lucid/Orm';
|
||||
|
||||
import { DateTime } from 'luxon';
|
||||
// import moment from 'moment';
|
||||
|
@ -15,91 +7,91 @@ import User from './User';
|
|||
import Permission from 'App/Models/Permission';
|
||||
|
||||
export default class Role extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
public static primaryKey = 'id';
|
||||
public static table = 'roles';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
public static primaryKey = 'id';
|
||||
public static table = 'roles';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
|
||||
@column({
|
||||
isPrimary: true,
|
||||
})
|
||||
public id: number;
|
||||
@column({
|
||||
isPrimary: true,
|
||||
})
|
||||
public id: number;
|
||||
|
||||
@column({})
|
||||
public display_name: string;
|
||||
@column({})
|
||||
public display_name: string;
|
||||
|
||||
@column({})
|
||||
public name: string;
|
||||
@column({})
|
||||
public name: string;
|
||||
|
||||
@column({})
|
||||
public description: string;
|
||||
@column({})
|
||||
public description: string;
|
||||
|
||||
@column.dateTime({
|
||||
serialize: (value: Date | null) => {
|
||||
// return value ? moment(value).format('MMMM Do YYYY, HH:mm:ss') : value;
|
||||
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
|
||||
},
|
||||
@column.dateTime({
|
||||
serialize: (value: Date | null) => {
|
||||
// return value ? moment(value).format('MMMM Do YYYY, HH:mm:ss') : value;
|
||||
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
|
||||
},
|
||||
autoCreate: true,
|
||||
})
|
||||
public created_at: DateTime;
|
||||
})
|
||||
public created_at: DateTime;
|
||||
|
||||
@column.dateTime({
|
||||
serialize: (value: Date | null) => {
|
||||
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
|
||||
},
|
||||
@column.dateTime({
|
||||
serialize: (value: Date | null) => {
|
||||
return value ? dayjs(value).format('MMMM D YYYY HH:mm a') : value;
|
||||
},
|
||||
autoCreate: true,
|
||||
autoUpdate: true
|
||||
})
|
||||
public updated_at: DateTime;
|
||||
autoUpdate: true,
|
||||
})
|
||||
public updated_at: DateTime;
|
||||
|
||||
@beforeCreate()
|
||||
@beforeCreate()
|
||||
@beforeUpdate()
|
||||
public static async resetDate(role) {
|
||||
role.created_at = this.formatDateTime(role.created_at);
|
||||
role.updated_at = this.formatDateTime(role.updated_at);
|
||||
}
|
||||
public static async resetDate(role) {
|
||||
role.created_at = this.formatDateTime(role.created_at);
|
||||
role.updated_at = this.formatDateTime(role.updated_at);
|
||||
}
|
||||
|
||||
// public static boot() {
|
||||
// super.boot();
|
||||
// public static boot() {
|
||||
// super.boot();
|
||||
|
||||
// this.before('create', async (_modelInstance) => {
|
||||
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at);
|
||||
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at);
|
||||
// });
|
||||
// this.before('update', async (_modelInstance) => {
|
||||
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at);
|
||||
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at);
|
||||
// });
|
||||
// }
|
||||
// this.before('create', async (_modelInstance) => {
|
||||
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at);
|
||||
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at);
|
||||
// });
|
||||
// this.before('update', async (_modelInstance) => {
|
||||
// _modelInstance.created_at = this.formatDateTime(_modelInstance.created_at);
|
||||
// _modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at);
|
||||
// });
|
||||
// }
|
||||
|
||||
private static formatDateTime(datetime) {
|
||||
let value = new Date(datetime);
|
||||
return datetime
|
||||
? value.getFullYear() +
|
||||
'-' +
|
||||
(value.getMonth() + 1) +
|
||||
'-' +
|
||||
value.getDate() +
|
||||
' ' +
|
||||
value.getHours() +
|
||||
':' +
|
||||
value.getMinutes() +
|
||||
':' +
|
||||
value.getSeconds()
|
||||
: datetime;
|
||||
}
|
||||
private static formatDateTime(datetime) {
|
||||
let value = new Date(datetime);
|
||||
return datetime
|
||||
? value.getFullYear() +
|
||||
'-' +
|
||||
(value.getMonth() + 1) +
|
||||
'-' +
|
||||
value.getDate() +
|
||||
' ' +
|
||||
value.getHours() +
|
||||
':' +
|
||||
value.getMinutes() +
|
||||
':' +
|
||||
value.getSeconds()
|
||||
: datetime;
|
||||
}
|
||||
|
||||
@manyToMany(() => User, {
|
||||
pivotForeignKey: 'role_id',
|
||||
pivotRelatedForeignKey: 'account_id',
|
||||
pivotTable: 'link_accounts_roles',
|
||||
})
|
||||
public users: ManyToMany<typeof User>;
|
||||
@manyToMany(() => User, {
|
||||
pivotForeignKey: 'role_id',
|
||||
pivotRelatedForeignKey: 'account_id',
|
||||
pivotTable: 'link_accounts_roles',
|
||||
})
|
||||
public users: ManyToMany<typeof User>;
|
||||
|
||||
@manyToMany(() => Permission, {
|
||||
pivotForeignKey: 'role_id',
|
||||
pivotRelatedForeignKey: 'permission_id',
|
||||
pivotTable: 'role_has_permissions',
|
||||
})
|
||||
public permissions: ManyToMany<typeof Permission>;
|
||||
@manyToMany(() => Permission, {
|
||||
pivotForeignKey: 'role_id',
|
||||
pivotRelatedForeignKey: 'permission_id',
|
||||
pivotTable: 'role_has_permissions',
|
||||
})
|
||||
public permissions: ManyToMany<typeof Permission>;
|
||||
}
|
||||
|
|
28
app/Models/Title.ts
Normal file
28
app/Models/Title.ts
Normal file
|
@ -0,0 +1,28 @@
|
|||
import { column, belongsTo, BelongsTo } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Dataset from './Dataset';
|
||||
import BaseModel from './BaseModel';
|
||||
|
||||
export default class Title extends BaseModel {
|
||||
public static primaryKey = 'id';
|
||||
public static table = 'dataset_titles';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
public static timestamps = false;
|
||||
public static fillable: string[] = ['value', 'type', 'language'];
|
||||
|
||||
@column({})
|
||||
public document_id: number;
|
||||
|
||||
@column()
|
||||
public type: string;
|
||||
|
||||
@column()
|
||||
public value: string;
|
||||
|
||||
@column()
|
||||
public language: string;
|
||||
|
||||
@belongsTo(() => Dataset, {
|
||||
foreignKey: 'document_id',
|
||||
})
|
||||
public dataset: BelongsTo<typeof Dataset>;
|
||||
}
|
|
@ -1,9 +1,10 @@
|
|||
import { DateTime } from 'luxon';
|
||||
import { BaseModel, column, beforeSave, manyToMany, ManyToMany } from '@ioc:Adonis/Lucid/Orm';
|
||||
import { BaseModel, column, beforeSave, manyToMany, ManyToMany, hasMany, HasMany } from '@ioc:Adonis/Lucid/Orm';
|
||||
import Hash from '@ioc:Adonis/Core/Hash';
|
||||
import Role from './Role';
|
||||
import Database from '@ioc:Adonis/Lucid/Database';
|
||||
import Config from '@ioc:Adonis/Core/Config';
|
||||
import Dataset from './Dataset';
|
||||
|
||||
// export default interface IUser {
|
||||
// id: number;
|
||||
|
@ -22,82 +23,87 @@ const roleTable = Config.get('rolePermission.role_table', 'roles');
|
|||
const userRoleTable = Config.get('rolePermission.user_role_table', 'link_accounts_roles');
|
||||
|
||||
export default class User extends BaseModel {
|
||||
public static table = 'accounts';
|
||||
public static table = 'accounts';
|
||||
|
||||
@column({ isPrimary: true })
|
||||
public id: number;
|
||||
@column({ isPrimary: true })
|
||||
public id: number;
|
||||
|
||||
@column()
|
||||
public login: string;
|
||||
@column()
|
||||
public login: string;
|
||||
|
||||
@column()
|
||||
public email: string;
|
||||
@column()
|
||||
public email: string;
|
||||
|
||||
@column({ serializeAs: null })
|
||||
public password: string;
|
||||
@column({ serializeAs: null })
|
||||
public password: string;
|
||||
|
||||
@column.dateTime({ autoCreate: true })
|
||||
public createdAt: DateTime;
|
||||
@column.dateTime({ autoCreate: true })
|
||||
public createdAt: DateTime;
|
||||
|
||||
@column.dateTime({ autoCreate: true, autoUpdate: true })
|
||||
public updatedAt: DateTime;
|
||||
@column.dateTime({ autoCreate: true, autoUpdate: true })
|
||||
public updatedAt: DateTime;
|
||||
|
||||
@beforeSave()
|
||||
public static async hashPassword(user) {
|
||||
if (user.$dirty.password) {
|
||||
user.password = await Hash.make(user.password);
|
||||
}
|
||||
}
|
||||
@beforeSave()
|
||||
public static async hashPassword(user) {
|
||||
if (user.$dirty.password) {
|
||||
user.password = await Hash.make(user.password);
|
||||
}
|
||||
}
|
||||
|
||||
@manyToMany(() => Role, {
|
||||
pivotForeignKey: 'account_id',
|
||||
pivotRelatedForeignKey: 'role_id',
|
||||
pivotTable: 'link_accounts_roles',
|
||||
})
|
||||
public roles: ManyToMany<typeof Role>;
|
||||
@manyToMany(() => Role, {
|
||||
pivotForeignKey: 'account_id',
|
||||
pivotRelatedForeignKey: 'role_id',
|
||||
pivotTable: 'link_accounts_roles',
|
||||
})
|
||||
public roles: ManyToMany<typeof Role>;
|
||||
|
||||
// https://github.com/adonisjs/core/discussions/1872#discussioncomment-132289
|
||||
public async getRoles(this: User): Promise<string[]> {
|
||||
const test = await this.related('roles').query();
|
||||
return test.map((role) => role.name);
|
||||
}
|
||||
@hasMany(() => Dataset, {
|
||||
foreignKey: 'account_id',
|
||||
})
|
||||
public datasets: HasMany<typeof Dataset>;
|
||||
|
||||
public async can(permissionNames: Array<string>): Promise<boolean> {
|
||||
// const permissions = await this.getPermissions()
|
||||
// return Acl.check(expression, operand => _.includes(permissions, operand))
|
||||
const hasPermission = await this.checkHasPermissions(this, permissionNames);
|
||||
return hasPermission;
|
||||
}
|
||||
// https://github.com/adonisjs/core/discussions/1872#discussioncomment-132289
|
||||
public async getRoles(this: User): Promise<string[]> {
|
||||
const test = await this.related('roles').query();
|
||||
return test.map((role) => role.name);
|
||||
}
|
||||
|
||||
private async checkHasPermissions(user: User, permissionNames: Array<string>): Promise<boolean> {
|
||||
let permissionPlaceHolder = '(';
|
||||
let placeholders = new Array(permissionNames.length).fill('?');
|
||||
permissionPlaceHolder += placeholders.join(',');
|
||||
permissionPlaceHolder += ')';
|
||||
public async can(permissionNames: Array<string>): Promise<boolean> {
|
||||
// const permissions = await this.getPermissions()
|
||||
// return Acl.check(expression, operand => _.includes(permissions, operand))
|
||||
const hasPermission = await this.checkHasPermissions(this, permissionNames);
|
||||
return hasPermission;
|
||||
}
|
||||
|
||||
let {
|
||||
rows: {
|
||||
0: { permissioncount },
|
||||
},
|
||||
} = await Database.rawQuery(
|
||||
'SELECT count("p"."name") as permissionCount FROM ' +
|
||||
roleTable +
|
||||
' r INNER JOIN ' +
|
||||
userRoleTable +
|
||||
' ur ON ur.role_id=r.id AND "ur"."account_id"=? ' +
|
||||
' INNER JOIN ' +
|
||||
rolePermissionTable +
|
||||
' rp ON rp.role_id=r.id ' +
|
||||
' INNER JOIN ' +
|
||||
permissionTable +
|
||||
' p ON rp.permission_id=p.id AND "p"."name" in ' +
|
||||
permissionPlaceHolder +
|
||||
' LIMIT 1',
|
||||
[user.id, ...permissionNames]
|
||||
);
|
||||
private async checkHasPermissions(user: User, permissionNames: Array<string>): Promise<boolean> {
|
||||
let permissionPlaceHolder = '(';
|
||||
let placeholders = new Array(permissionNames.length).fill('?');
|
||||
permissionPlaceHolder += placeholders.join(',');
|
||||
permissionPlaceHolder += ')';
|
||||
|
||||
return permissioncount > 0;
|
||||
}
|
||||
let {
|
||||
rows: {
|
||||
0: { permissioncount },
|
||||
},
|
||||
} = await Database.rawQuery(
|
||||
'SELECT count("p"."name") as permissionCount FROM ' +
|
||||
roleTable +
|
||||
' r INNER JOIN ' +
|
||||
userRoleTable +
|
||||
' ur ON ur.role_id=r.id AND "ur"."account_id"=? ' +
|
||||
' INNER JOIN ' +
|
||||
rolePermissionTable +
|
||||
' rp ON rp.role_id=r.id ' +
|
||||
' INNER JOIN ' +
|
||||
permissionTable +
|
||||
' p ON rp.permission_id=p.id AND "p"."name" in ' +
|
||||
permissionPlaceHolder +
|
||||
' LIMIT 1',
|
||||
[user.id, ...permissionNames],
|
||||
);
|
||||
|
||||
return permissioncount > 0;
|
||||
}
|
||||
}
|
||||
|
||||
// export default User;
|
||||
|
|
|
@ -1,74 +1,74 @@
|
|||
import {column, BaseModel, belongsTo, BelongsTo, SnakeCaseNamingStrategy} from '@ioc:Adonis/Lucid/Orm'
|
||||
import { column, BaseModel, belongsTo, BelongsTo, SnakeCaseNamingStrategy } from '@ioc:Adonis/Lucid/Orm';
|
||||
|
||||
import User from 'App/Models/User'
|
||||
import Role from 'App/Models/Role'
|
||||
import { DateTime } from 'luxon'
|
||||
import User from 'App/Models/User';
|
||||
import Role from 'App/Models/Role';
|
||||
import { DateTime } from 'luxon';
|
||||
// import moment from 'moment'
|
||||
|
||||
export default class UserRole extends BaseModel {
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy()
|
||||
public static primaryKey = 'id'
|
||||
public static table = 'user_roles'
|
||||
public static selfAssignPrimaryKey = false
|
||||
public static namingStrategy = new SnakeCaseNamingStrategy();
|
||||
public static primaryKey = 'id';
|
||||
public static table = 'user_roles';
|
||||
public static selfAssignPrimaryKey = false;
|
||||
|
||||
@column({
|
||||
isPrimary: true,
|
||||
})
|
||||
public id: number
|
||||
|
||||
@column({})
|
||||
public user_id: number
|
||||
|
||||
@column({})
|
||||
public role_id: number
|
||||
|
||||
@column({
|
||||
// serialize: (value: DateTime | null) => {
|
||||
// return value ? moment(value).format('lll') : value
|
||||
// },
|
||||
})
|
||||
public created_at: DateTime
|
||||
|
||||
@column({
|
||||
// serialize: (value: DateTime | null) => {
|
||||
// return value ? moment(value).format('lll') : value
|
||||
// },
|
||||
})
|
||||
public updated_at: DateTime
|
||||
|
||||
public static boot() {
|
||||
super.boot()
|
||||
|
||||
this.before('create', async (_modelInstance) => {
|
||||
_modelInstance.created_at = this.formatDateTime(_modelInstance.created_at)
|
||||
_modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at)
|
||||
@column({
|
||||
isPrimary: true,
|
||||
})
|
||||
this.before('update', async (_modelInstance) => {
|
||||
_modelInstance.created_at = this.formatDateTime(_modelInstance.created_at)
|
||||
_modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at)
|
||||
public id: number;
|
||||
|
||||
@column({})
|
||||
public user_id: number;
|
||||
|
||||
@column({})
|
||||
public role_id: number;
|
||||
|
||||
@column({
|
||||
// serialize: (value: DateTime | null) => {
|
||||
// return value ? moment(value).format('lll') : value
|
||||
// },
|
||||
})
|
||||
}
|
||||
public created_at: DateTime;
|
||||
|
||||
private static formatDateTime(datetime) {
|
||||
let value = new Date(datetime)
|
||||
return datetime
|
||||
? value.getFullYear() +
|
||||
'-' +
|
||||
(value.getMonth() + 1) +
|
||||
'-' +
|
||||
value.getDate() +
|
||||
' ' +
|
||||
value.getHours() +
|
||||
':' +
|
||||
value.getMinutes() +
|
||||
':' +
|
||||
value.getSeconds()
|
||||
: datetime
|
||||
}
|
||||
@column({
|
||||
// serialize: (value: DateTime | null) => {
|
||||
// return value ? moment(value).format('lll') : value
|
||||
// },
|
||||
})
|
||||
public updated_at: DateTime;
|
||||
|
||||
@belongsTo(() => User)
|
||||
public user: BelongsTo<typeof User>
|
||||
public static boot() {
|
||||
super.boot();
|
||||
|
||||
@belongsTo(() => Role)
|
||||
public role: BelongsTo<typeof Role>
|
||||
this.before('create', async (_modelInstance) => {
|
||||
_modelInstance.created_at = this.formatDateTime(_modelInstance.created_at);
|
||||
_modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at);
|
||||
});
|
||||
this.before('update', async (_modelInstance) => {
|
||||
_modelInstance.created_at = this.formatDateTime(_modelInstance.created_at);
|
||||
_modelInstance.updated_at = this.formatDateTime(_modelInstance.updated_at);
|
||||
});
|
||||
}
|
||||
|
||||
private static formatDateTime(datetime) {
|
||||
let value = new Date(datetime);
|
||||
return datetime
|
||||
? value.getFullYear() +
|
||||
'-' +
|
||||
(value.getMonth() + 1) +
|
||||
'-' +
|
||||
value.getDate() +
|
||||
' ' +
|
||||
value.getHours() +
|
||||
':' +
|
||||
value.getMinutes() +
|
||||
':' +
|
||||
value.getSeconds()
|
||||
: datetime;
|
||||
}
|
||||
|
||||
@belongsTo(() => User)
|
||||
public user: BelongsTo<typeof User>;
|
||||
|
||||
@belongsTo(() => Role)
|
||||
public role: BelongsTo<typeof Role>;
|
||||
}
|
||||
|
|
|
@ -2,45 +2,45 @@ import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
|
||||
export default class AuthValidator {
|
||||
constructor(protected ctx: HttpContextContract) {}
|
||||
constructor(protected ctx: HttpContextContract) {}
|
||||
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
*
|
||||
* For example:
|
||||
* 1. The username must be of data type string. But then also, it should
|
||||
* not contain special characters or numbers.
|
||||
* ```
|
||||
* schema.string({}, [ rules.alpha() ])
|
||||
* ```
|
||||
*
|
||||
* 2. The email must be of data type string, formatted as a valid
|
||||
* email. But also, not used by any other user.
|
||||
* ```
|
||||
* schema.string({}, [
|
||||
* rules.email(),
|
||||
* rules.unique({ table: 'users', column: 'email' }),
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
public schema = schema.create({
|
||||
email: schema.string({ trim: true }, [
|
||||
rules.email(),
|
||||
// rules.unique({ table: 'accounts', column: 'email' })
|
||||
]),
|
||||
password: schema.string({}, [rules.minLength(6)]),
|
||||
});
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
*
|
||||
* For example:
|
||||
* 1. The username must be of data type string. But then also, it should
|
||||
* not contain special characters or numbers.
|
||||
* ```
|
||||
* schema.string({}, [ rules.alpha() ])
|
||||
* ```
|
||||
*
|
||||
* 2. The email must be of data type string, formatted as a valid
|
||||
* email. But also, not used by any other user.
|
||||
* ```
|
||||
* schema.string({}, [
|
||||
* rules.email(),
|
||||
* rules.unique({ table: 'users', column: 'email' }),
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
public schema = schema.create({
|
||||
email: schema.string({ trim: true }, [
|
||||
rules.email(),
|
||||
// rules.unique({ table: 'accounts', column: 'email' })
|
||||
]),
|
||||
password: schema.string({}, [rules.minLength(6)]),
|
||||
});
|
||||
|
||||
/**
|
||||
* Custom messages for validation failures. You can make use of dot notation `(.)`
|
||||
* for targeting nested fields and array expressions `(*)` for targeting all
|
||||
* children of an array. For example:
|
||||
*
|
||||
* {
|
||||
* 'profile.username.required': 'Username is required',
|
||||
* 'scores.*.number': 'Define scores as valid numbers'
|
||||
* }
|
||||
*
|
||||
*/
|
||||
public messages: CustomMessages = {};
|
||||
/**
|
||||
* Custom messages for validation failures. You can make use of dot notation `(.)`
|
||||
* for targeting nested fields and array expressions `(*)` for targeting all
|
||||
* children of an array. For example:
|
||||
*
|
||||
* {
|
||||
* 'profile.username.required': 'Username is required',
|
||||
* 'scores.*.number': 'Define scores as valid numbers'
|
||||
* }
|
||||
*
|
||||
*/
|
||||
public messages: CustomMessages = {};
|
||||
}
|
||||
|
|
157
app/Validators/CreateDatasetValidator.ts
Normal file
157
app/Validators/CreateDatasetValidator.ts
Normal file
|
@ -0,0 +1,157 @@
|
|||
import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
||||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
import dayjs from 'dayjs';
|
||||
import { TitleTypes, DescriptionTypes } from 'Contracts/enums';
|
||||
|
||||
export default class CreateDatasetValidator {
|
||||
constructor(protected ctx: HttpContextContract) {}
|
||||
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
*
|
||||
* For example:
|
||||
* 1. The username must be of data type string. But then also, it should
|
||||
* not contain special characters or numbers.
|
||||
* ```
|
||||
* schema.string({}, [ rules.alpha() ])
|
||||
* ```
|
||||
*
|
||||
* 2. The email must be of data type string, formatted as a valid
|
||||
* email. But also, not used by any other user.
|
||||
* ```
|
||||
* schema.string({}, [
|
||||
* rules.email(),
|
||||
* rules.unique({ table: 'users', column: 'email' }),
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
public schema = schema.create({
|
||||
// first step
|
||||
language: schema.string({ trim: true }, [
|
||||
rules.regex(/^[a-zA-Z0-9-_]+$/), //Must be alphanumeric with hyphens or underscores
|
||||
]),
|
||||
licenses: schema.array([rules.minLength(1)]).members(schema.number()), // define at least one license for the new dataset
|
||||
rights: schema.string([rules.equalTo('true')]),
|
||||
// second step
|
||||
type: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(255)]),
|
||||
creating_corporation: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(255)]),
|
||||
titles: schema.array([rules.minLength(1)]).members(
|
||||
schema.object().members({
|
||||
value: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(255)]),
|
||||
type: schema.enum(Object.values(TitleTypes)),
|
||||
language: schema.string({ trim: true }, [
|
||||
rules.minLength(2),
|
||||
rules.maxLength(255),
|
||||
rules.translatedLanguage('/language', 'type'),
|
||||
]),
|
||||
}),
|
||||
),
|
||||
descriptions: schema.array([rules.minLength(1)]).members(
|
||||
schema.object().members({
|
||||
value: schema.string({ trim: true }, [rules.minLength(3), rules.maxLength(255)]),
|
||||
type: schema.enum(Object.values(DescriptionTypes)),
|
||||
language: schema.string({ trim: true }, [
|
||||
rules.minLength(2),
|
||||
rules.maxLength(255),
|
||||
rules.translatedLanguage('/language', 'type'),
|
||||
]),
|
||||
}),
|
||||
),
|
||||
authors: schema.array([rules.minLength(1)]).members(schema.object().members({ email: schema.string({ trim: true }) })),
|
||||
// third step
|
||||
project_id: schema.number.optional(),
|
||||
embargo_date: schema.date.optional({ format: 'yyyy-MM-dd' }, [rules.after(10, 'days')]),
|
||||
coverage: schema.object().members({
|
||||
x_min: schema.number(),
|
||||
x_max: schema.number(),
|
||||
y_min: schema.number(),
|
||||
y_max: schema.number(),
|
||||
elevation_absolut: schema.number.optional(),
|
||||
elevation_min: schema.number.optional([rules.requiredIfExists('elevation_max')]),
|
||||
elevation_max: schema.number.optional([rules.requiredIfExists('elevation_min')]),
|
||||
depth_absolut: schema.number.optional(),
|
||||
depth_min: schema.number.optional([rules.requiredIfExists('depth_max')]),
|
||||
depth_max: schema.number.optional([rules.requiredIfExists('depth_min')]),
|
||||
}),
|
||||
subjects: schema.array([rules.minLength(3), rules.uniqueArray('value')]).members(
|
||||
schema.object().members({
|
||||
value: schema.string({ trim: true }, [
|
||||
rules.minLength(3),
|
||||
rules.maxLength(255),
|
||||
// rules.unique({ table: 'dataset_subjects', column: 'value' }),
|
||||
]),
|
||||
// type: schema.enum(Object.values(TitleTypes)),
|
||||
language: schema.string({ trim: true }, [rules.minLength(2), rules.maxLength(255)]),
|
||||
}),
|
||||
),
|
||||
// file: schema.file({
|
||||
// size: '100mb',
|
||||
// extnames: ['jpg', 'gif', 'png'],
|
||||
// }),
|
||||
files: schema.array([rules.minLength(1)]).members(
|
||||
schema.file({
|
||||
size: '100mb',
|
||||
extnames: ['jpg', 'gif', 'png'],
|
||||
}),
|
||||
),
|
||||
// upload: schema.object().members({
|
||||
// label: schema.string({ trim: true }, [rules.maxLength(255)]),
|
||||
|
||||
// // label: schema.string({ trim: true }, [
|
||||
// // // rules.minLength(3),
|
||||
// // // rules.maxLength(255),
|
||||
// // ]),
|
||||
// }),
|
||||
});
|
||||
|
||||
/**
|
||||
* Custom messages for validation failures. You can make use of dot notation `(.)`
|
||||
* for targeting nested fields and array expressions `(*)` for targeting all
|
||||
* children of an array. For example:
|
||||
*
|
||||
* {
|
||||
* 'profile.username.required': 'Username is required',
|
||||
* 'scores.*.number': 'Define scores as valid numbers'
|
||||
* }
|
||||
*
|
||||
*/
|
||||
public messages: CustomMessages = {
|
||||
'minLength': '{{ field }} must be at least {{ options.minLength }} characters long',
|
||||
'maxLength': '{{ field }} must be less then {{ options.maxLength }} characters long',
|
||||
'required': '{{ field }} is required',
|
||||
'unique': '{{ field }} must be unique, and this value is already taken',
|
||||
// 'confirmed': '{{ field }} is not correct',
|
||||
'licences.minLength': 'at least {{ options.minLength }} permission must be defined',
|
||||
'licences.*.number': 'Define roles as valid numbers',
|
||||
'rights.equalTo': 'you must agree to continue',
|
||||
|
||||
'titles.0.value.minLength': 'Main Title must be at least {{ options.minLength }} characters long',
|
||||
'titles.0.value.required': 'Main Title is required',
|
||||
'titles.*.value.required': 'Additional title is required, if defined',
|
||||
'titles.*.type.required': 'Additional title type is required',
|
||||
'titles.*.language.required': 'Additional title language is required',
|
||||
'titles.*.language.translatedLanguage': 'The language of the translated title must be different from the language of the dataset',
|
||||
|
||||
'descriptions.0.value.minLength': 'Main Abstract must be at least {{ options.minLength }} characters long',
|
||||
'descriptions.0.value.required': 'Main Abstract is required',
|
||||
'descriptions.*.value.required': 'Additional description is required, if defined',
|
||||
'descriptions.*.type.required': 'Additional description type is required',
|
||||
'descriptions.*.language.required': 'Additional description language is required',
|
||||
'descriptions.*.language.translatedLanguage':
|
||||
'The language of the translated description must be different from the language of the dataset',
|
||||
|
||||
'authors.minLength': 'at least {{ options.minLength }} author must be defined',
|
||||
|
||||
'after': `{{ field }} must be older than ${dayjs().add(10, 'day')}`,
|
||||
|
||||
'subjects.minLength': 'at least {{ options.minLength }} keywords must be defined',
|
||||
'subjects.uniqueArray': 'The {{ options.array }} array must have unique values based on the {{ options.field }} attribute.',
|
||||
'subjects.*.value.required': 'keyword value is required',
|
||||
'subjects.*.value.minLength': 'keyword value must be at least {{ options.minLength }} characters long',
|
||||
'subjects.*.type.required': 'keyword type is required',
|
||||
'subjects.*.language.required': 'language of keyword is required',
|
||||
|
||||
'files.*.size': 'file size is to big',
|
||||
'files.extnames': 'file extension is not supported',
|
||||
};
|
||||
}
|
|
@ -2,68 +2,68 @@ import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
|
||||
export default class CreateRoleValidator {
|
||||
constructor(protected ctx: HttpContextContract) {}
|
||||
constructor(protected ctx: HttpContextContract) {}
|
||||
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
*
|
||||
* For example:
|
||||
* 1. The username must be of data type string. But then also, it should
|
||||
* not contain special characters or numbers.
|
||||
* ```
|
||||
* schema.string({}, [ rules.alpha() ])
|
||||
* ```
|
||||
*
|
||||
* 2. The email must be of data type string, formatted as a valid
|
||||
* email. But also, not used by any other user.
|
||||
* ```
|
||||
* schema.string({}, [
|
||||
* rules.email(),
|
||||
* rules.unique({ table: 'users', column: 'email' }),
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
public schema = schema.create({
|
||||
name: schema.string({ trim: true }, [
|
||||
rules.minLength(3),
|
||||
rules.maxLength(255),
|
||||
rules.unique({ table: 'roles', column: 'name' }),
|
||||
rules.regex(/^[a-zA-Z0-9-_]+$/), //Must be alphanumeric with hyphens or underscores
|
||||
]),
|
||||
display_name: schema.string.optional({ trim: true }, [
|
||||
rules.minLength(3),
|
||||
rules.maxLength(255),
|
||||
rules.unique({ table: 'roles', column: 'name' }),
|
||||
rules.regex(/^[a-zA-Z0-9-_]+$/), //Must be alphanumeric with hyphens or underscores
|
||||
]),
|
||||
description: schema.string.optional({}, [rules.minLength(3), rules.maxLength(255)]),
|
||||
permissions: schema.array([rules.minLength(1)]).members(schema.number()), // define at least one role for the new role
|
||||
});
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
*
|
||||
* For example:
|
||||
* 1. The username must be of data type string. But then also, it should
|
||||
* not contain special characters or numbers.
|
||||
* ```
|
||||
* schema.string({}, [ rules.alpha() ])
|
||||
* ```
|
||||
*
|
||||
* 2. The email must be of data type string, formatted as a valid
|
||||
* email. But also, not used by any other user.
|
||||
* ```
|
||||
* schema.string({}, [
|
||||
* rules.email(),
|
||||
* rules.unique({ table: 'users', column: 'email' }),
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
public schema = schema.create({
|
||||
name: schema.string({ trim: true }, [
|
||||
rules.minLength(3),
|
||||
rules.maxLength(255),
|
||||
rules.unique({ table: 'roles', column: 'name' }),
|
||||
rules.regex(/^[a-zA-Z0-9-_]+$/), //Must be alphanumeric with hyphens or underscores
|
||||
]),
|
||||
display_name: schema.string.optional({ trim: true }, [
|
||||
rules.minLength(3),
|
||||
rules.maxLength(255),
|
||||
rules.unique({ table: 'roles', column: 'name' }),
|
||||
rules.regex(/^[a-zA-Z0-9-_]+$/), //Must be alphanumeric with hyphens or underscores
|
||||
]),
|
||||
description: schema.string.optional({}, [rules.minLength(3), rules.maxLength(255)]),
|
||||
permissions: schema.array([rules.minLength(1)]).members(schema.number()), // define at least one role for the new role
|
||||
});
|
||||
|
||||
// emails: schema
|
||||
// .array([rules.minLength(1)])
|
||||
// .members(
|
||||
// schema.object().members({ email: schema.string({}, [rules.email()]) })
|
||||
// ),
|
||||
// emails: schema
|
||||
// .array([rules.minLength(1)])
|
||||
// .members(
|
||||
// schema.object().members({ email: schema.string({}, [rules.email()]) })
|
||||
// ),
|
||||
|
||||
/**
|
||||
* Custom messages for validation failures. You can make use of dot notation `(.)`
|
||||
* for targeting nested fields and array expressions `(*)` for targeting all
|
||||
* children of an array. For example:
|
||||
*
|
||||
* {
|
||||
* 'profile.username.required': 'Username is required',
|
||||
* 'scores.*.number': 'Define scores as valid numbers'
|
||||
* }
|
||||
*
|
||||
*/
|
||||
public messages: CustomMessages = {
|
||||
'minLength': '{{ field }} must be at least {{ options.minLength }} characters long',
|
||||
'maxLength': '{{ field }} must be less then {{ options.maxLength }} characters long',
|
||||
'required': '{{ field }} is required',
|
||||
'unique': '{{ field }} must be unique, and this value is already taken',
|
||||
'confirmed': '{{ field }} is not correct',
|
||||
'permissions.minLength': 'at least {{ options.minLength }} permission must be defined',
|
||||
'permissions.*.number': 'Define roles as valid numbers',
|
||||
};
|
||||
/**
|
||||
* Custom messages for validation failures. You can make use of dot notation `(.)`
|
||||
* for targeting nested fields and array expressions `(*)` for targeting all
|
||||
* children of an array. For example:
|
||||
*
|
||||
* {
|
||||
* 'profile.username.required': 'Username is required',
|
||||
* 'scores.*.number': 'Define scores as valid numbers'
|
||||
* }
|
||||
*
|
||||
*/
|
||||
public messages: CustomMessages = {
|
||||
'minLength': '{{ field }} must be at least {{ options.minLength }} characters long',
|
||||
'maxLength': '{{ field }} must be less then {{ options.maxLength }} characters long',
|
||||
'required': '{{ field }} is required',
|
||||
'unique': '{{ field }} must be unique, and this value is already taken',
|
||||
'confirmed': '{{ field }} is not correct',
|
||||
'permissions.minLength': 'at least {{ options.minLength }} permission must be defined',
|
||||
'permissions.*.number': 'Define roles as valid numbers',
|
||||
};
|
||||
}
|
||||
|
|
|
@ -2,63 +2,63 @@ import { schema, CustomMessages, rules } from '@ioc:Adonis/Core/Validator';
|
|||
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
||||
|
||||
export default class CreateUserValidator {
|
||||
constructor(protected ctx: HttpContextContract) {}
|
||||
constructor(protected ctx: HttpContextContract) {}
|
||||
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
*
|
||||
* For example:
|
||||
* 1. The username must be of data type string. But then also, it should
|
||||
* not contain special characters or numbers.
|
||||
* ```
|
||||
* schema.string({}, [ rules.alpha() ])
|
||||
* ```
|
||||
*
|
||||
* 2. The email must be of data type string, formatted as a valid
|
||||
* email. But also, not used by any other user.
|
||||
* ```
|
||||
* schema.string({}, [
|
||||
* rules.email(),
|
||||
* rules.unique({ table: 'users', column: 'email' }),
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
public schema = schema.create({
|
||||
login: schema.string({ trim: true }, [
|
||||
rules.minLength(3),
|
||||
rules.maxLength(50),
|
||||
rules.unique({ table: 'accounts', column: 'login' }),
|
||||
rules.regex(/^[a-zA-Z0-9-_]+$/), //Must be alphanumeric with hyphens or underscores
|
||||
]),
|
||||
email: schema.string({}, [rules.email(), rules.unique({ table: 'accounts', column: 'email' })]),
|
||||
password: schema.string([rules.confirmed(), rules.minLength(6)]),
|
||||
roles: schema.array([rules.minLength(1)]).members(schema.number()), // define at least one role for the new user
|
||||
});
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
*
|
||||
* For example:
|
||||
* 1. The username must be of data type string. But then also, it should
|
||||
* not contain special characters or numbers.
|
||||
* ```
|
||||
* schema.string({}, [ rules.alpha() ])
|
||||
* ```
|
||||
*
|
||||
* 2. The email must be of data type string, formatted as a valid
|
||||
* email. But also, not used by any other user.
|
||||
* ```
|
||||
* schema.string({}, [
|
||||
* rules.email(),
|
||||
* rules.unique({ table: 'users', column: 'email' }),
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
public schema = schema.create({
|
||||
login: schema.string({ trim: true }, [
|
||||
rules.minLength(3),
|
||||
rules.maxLength(50),
|
||||
rules.unique({ table: 'accounts', column: 'login' }),
|
||||
rules.regex(/^[a-zA-Z0-9-_]+$/), //Must be alphanumeric with hyphens or underscores
|
||||
]),
|
||||
email: schema.string({}, [rules.email(), rules.unique({ table: 'accounts', column: 'email' })]),
|
||||
password: schema.string([rules.confirmed(), rules.minLength(6)]),
|
||||
roles: schema.array([rules.minLength(1)]).members(schema.number()), // define at least one role for the new user
|
||||
});
|
||||
|
||||
// emails: schema
|
||||
// .array([rules.minLength(1)])
|
||||
// .members(
|
||||
// schema.object().members({ email: schema.string({}, [rules.email()]) })
|
||||
// ),
|
||||
// emails: schema
|
||||
// .array([rules.minLength(1)])
|
||||
// .members(
|
||||
// schema.object().members({ email: schema.string({}, [rules.email()]) })
|
||||
// ),
|
||||
|
||||
/**
|
||||
* Custom messages for validation failures. You can make use of dot notation `(.)`
|
||||
* for targeting nested fields and array expressions `(*)` for targeting all
|
||||
* children of an array. For example:
|
||||
*
|
||||
* {
|
||||
* 'profile.username.required': 'Username is required',
|
||||
* 'scores.*.number': 'Define scores as valid numbers'
|
||||
* }
|
||||
*
|
||||
*/
|
||||
public messages: CustomMessages = {
|
||||
'minLength': '{{ field }} must be at least {{ options.minLength }} characters long',
|
||||
'maxLength': '{{ field }} must be less then {{ options.maxLength }} characters long',
|
||||
'required': '{{ field }} is required',
|
||||
'unique': '{{ field }} must be unique, and this value is already taken',
|
||||
'confirmed': '{{ field }} is not correct',
|
||||
'roles.minLength': 'at least {{ options.minLength }} role must be defined',
|
||||
'roles.*.number': 'Define roles as valid numbers'
|
||||
};
|
||||
/**
|
||||
* Custom messages for validation failures. You can make use of dot notation `(.)`
|
||||
* for targeting nested fields and array expressions `(*)` for targeting all
|
||||
* children of an array. For example:
|
||||
*
|
||||
* {
|
||||
* 'profile.username.required': 'Username is required',
|
||||
* 'scores.*.number': 'Define scores as valid numbers'
|
||||
* }
|
||||
*
|
||||
*/
|
||||
public messages: CustomMessages = {
|
||||
'minLength': '{{ field }} must be at least {{ options.minLength }} characters long',
|
||||
'maxLength': '{{ field }} must be less then {{ options.maxLength }} characters long',
|
||||
'required': '{{ field }} is required',
|
||||
'unique': '{{ field }} must be unique, and this value is already taken',
|
||||
'confirmed': '{{ field }} is not correct',
|
||||
'roles.minLength': 'at least {{ options.minLength }} role must be defined',
|
||||
'roles.*.number': 'Define roles as valid numbers',
|
||||
};
|
||||
}
|
||||
|
|
|
@ -3,95 +3,95 @@ import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext';
|
|||
// import { Request } from '@adonisjs/core/build/standalone';
|
||||
|
||||
export default class UpdateRoleValidator {
|
||||
protected ctx: HttpContextContract;
|
||||
public schema;
|
||||
protected ctx: HttpContextContract;
|
||||
public schema;
|
||||
|
||||
constructor(ctx: HttpContextContract) {
|
||||
this.ctx = ctx;
|
||||
this.schema = this.createSchema();
|
||||
}
|
||||
constructor(ctx: HttpContextContract) {
|
||||
this.ctx = ctx;
|
||||
this.schema = this.createSchema();
|
||||
}
|
||||
|
||||
// public get schema() {
|
||||
// return this._schema;
|
||||
// }
|
||||
// public get schema() {
|
||||
// return this._schema;
|
||||
// }
|
||||
|
||||
private createSchema() {
|
||||
return schema.create({
|
||||
name: schema.string({ trim: true }, [
|
||||
rules.minLength(3),
|
||||
rules.maxLength(50),
|
||||
rules.unique({
|
||||
table: 'roles',
|
||||
column: 'name',
|
||||
whereNot: { id: this.ctx?.params.id },
|
||||
}),
|
||||
rules.regex(/^[a-zA-Z0-9-_]+$/),
|
||||
//Must be alphanumeric with hyphens or underscores
|
||||
]),
|
||||
description: schema.string.optional({}, [rules.minLength(3), rules.maxLength(255)]),
|
||||
permissions: schema.array([rules.minLength(1)]).members(schema.number()), // define at least one permission for the new role
|
||||
});
|
||||
}
|
||||
private createSchema() {
|
||||
return schema.create({
|
||||
name: schema.string({ trim: true }, [
|
||||
rules.minLength(3),
|
||||
rules.maxLength(50),
|
||||
rules.unique({
|
||||
table: 'roles',
|
||||
column: 'name',
|
||||
whereNot: { id: this.ctx?.params.id },
|
||||
}),
|
||||
rules.regex(/^[a-zA-Z0-9-_]+$/),
|
||||
//Must be alphanumeric with hyphens or underscores
|
||||
]),
|
||||
description: schema.string.optional({}, [rules.minLength(3), rules.maxLength(255)]),
|
||||
permissions: schema.array([rules.minLength(1)]).members(schema.number()), // define at least one permission for the new role
|
||||
});
|
||||
}
|
||||
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
*
|
||||
* For example:
|
||||
* 1. The username must be of data type string. But then also, it should
|
||||
* not contain special characters or numbers.
|
||||
* ```
|
||||
* schema.string({}, [ rules.alpha() ])
|
||||
* ```
|
||||
*
|
||||
* 2. The email must be of data type string, formatted as a valid
|
||||
* email. But also, not used by any other user.
|
||||
* ```
|
||||
* schema.string({}, [
|
||||
* rules.email(),
|
||||
* rules.unique({ table: 'users', column: 'email' }),
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
/*
|
||||
* Define schema to validate the "shape", "type", "formatting" and "integrity" of data.
|
||||
*
|
||||
* For example:
|
||||
* 1. The username must be of data type string. But then also, it should
|
||||
* not contain special characters or numbers.
|
||||
* ```
|
||||
* schema.string({}, [ rules.alpha() ])
|
||||
* ```
|
||||
*
|
||||
* 2. The email must be of data type string, formatted as a valid
|
||||
* email. But also, not used by any other user.
|
||||
* ```
|
||||
* schema.string({}, [
|
||||
* rules.email(),
|
||||
* rules.unique({ table: 'users', column: 'email' }),
|
||||
* ])
|
||||
* ```
|
||||
*/
|
||||
|
||||
// public refs = schema.refs({
|
||||
// id: this.ctx.params.id
|
||||
// })
|
||||
// public refs = schema.refs({
|
||||
// id: this.ctx.params.id
|
||||
// })
|
||||
|
||||
// public schema = schema.create({
|
||||
// login: schema.string({ trim: true }, [
|
||||
// rules.minLength(3),
|
||||
// rules.maxLength(50),
|
||||
// rules.unique({
|
||||
// table: 'accounts',
|
||||
// column: 'login',
|
||||
// // whereNot: { id: this.refs.id }
|
||||
// whereNot: { id: this.ctx?.params.id },
|
||||
// }),
|
||||
// // rules.regex(/^[a-zA-Z0-9-_]+$/),
|
||||
// //Must be alphanumeric with hyphens or underscores
|
||||
// ]),
|
||||
// email: schema.string({}, [rules.email(), rules.unique({ table: 'accounts', column: 'email' })]),
|
||||
// password: schema.string.optional([rules.confirmed(), rules.minLength(6)]),
|
||||
// roles: schema.array([rules.minLength(1)]).members(schema.number()), // define at least one role for the new user
|
||||
// });
|
||||
// public schema = schema.create({
|
||||
// login: schema.string({ trim: true }, [
|
||||
// rules.minLength(3),
|
||||
// rules.maxLength(50),
|
||||
// rules.unique({
|
||||
// table: 'accounts',
|
||||
// column: 'login',
|
||||
// // whereNot: { id: this.refs.id }
|
||||
// whereNot: { id: this.ctx?.params.id },
|
||||
// }),
|
||||
// // rules.regex(/^[a-zA-Z0-9-_]+$/),
|
||||
// //Must be alphanumeric with hyphens or underscores
|
||||
// ]),
|
||||
// email: schema.string({}, [rules.email(), rules.unique({ table: 'accounts', column: 'email' })]),
|
||||
// password: schema.string.optional([rules.confirmed(), rules.minLength(6)]),
|
||||
// roles: schema.array([rules.minLength(1)]).members(schema.number()), // define at least one role for the new user
|
||||
// });
|
||||
|
||||
/**
|
||||
* Custom messages for validation failures. You can make use of dot notation `(.)`
|
||||
* for targeting nested fields and array expressions `(*)` for targeting all
|
||||
* children of an array. For example:
|
||||
*
|
||||
* {
|
||||
* 'profile.username.required': 'Username is required',
|
||||
* 'scores.*.number': 'Define scores as valid numbers'
|
||||
* }
|
||||
*
|
||||
*/
|
||||
public messages: CustomMessages = {
|
||||
'minLength': '{{ field }} must be at least {{ options.minLength }} characters long',
|
||||
'maxLength': '{{ field }} must be less then {{ options.maxLength }} characters long',
|
||||
'required': '{{ field }} is required',
|
||||
'unique': '{{ field }} must be unique, and this value is already taken',
|
||||
'permissions.minLength': 'at least {{ options.minLength }} permission must be defined',
|
||||
'permissions.*.number': 'Define permissions as valid numbers',
|
||||
};
|
||||
/**
|
||||
* Custom messages for validation failures. You can make use of dot notation `(.)`
|
||||
* for targeting nested fields and array expressions `(*)` for targeting all
|
||||
* children of an array. For example:
|
||||
*
|
||||
* {
|
||||
* 'profile.username.required': 'Username is required',
|
||||
* 'scores.*.number': 'Define scores as valid numbers'
|
||||
* }
|
||||
*
|
||||
*/
|
||||
public messages: CustomMessages = {
|
||||
'minLength': '{{ field }} must be at least {{ options.minLength }} characters long',
|
||||
'maxLength': '{{ field }} must be less then {{ options.maxLength }} characters long',
|
||||
'required': '{{ field }} is required',
|
||||
'unique': '{{ field }} must be unique, and this value is already taken',
|
||||
'permissions.minLength': 'at least {{ options.minLength }} permission must be defined',
|
||||
'permissions.*.number': 'Define permissions as valid numbers',
|
||||
};
|
||||
}
|
||||
|
|
Loading…
Add table
editor.link_modal.header
Reference in a new issue