Browse Source

Moved from Adonis to Django,

Because Adonis' author is apparently a moron that doesn't care about
accessibility or civil debate.
main
Artemis 2 weeks ago
parent
commit
c3e37b8b6c
  1. 41
      .adonisrc.json
  2. 8
      .env.example
  3. 1
      .eslintignore
  4. 14
      .eslintrc.json
  5. 6
      .gitignore
  6. 1
      .prettierignore
  7. 10
      .prettierrc
  8. 2
      MANIFEST.in
  9. 10
      README.md
  10. 16
      ace
  11. 269
      ace-manifest.json
  12. 32
      app/Controllers/Http/BookmarksController.ts
  13. 37
      app/Controllers/Http/SearchController.ts
  14. 15
      app/Controllers/Http/TagsController.ts
  15. 29
      app/Exceptions/Handler.ts
  16. 27
      app/Models/Bookmark.ts
  17. 20
      app/Models/Tag.ts
  18. 0
      bookmarks/__init__.py
  19. 7
      bookmarks/admin.py
  20. 5
      bookmarks/apps.py
  21. 11
      bookmarks/forms.py
  22. 41
      bookmarks/migrations/0001_initial.py
  23. 0
      bookmarks/migrations/__init__.py
  24. 23
      bookmarks/models.py
  25. 0
      bookmarks/static/bookmarks.css
  26. 44
      bookmarks/templates/index.html
  27. 1
      bookmarks/tests.py
  28. 10
      bookmarks/urls.py
  29. 46
      bookmarks/views.py
  30. 19
      commands/index.ts
  31. 276
      config/app.ts
  32. 205
      config/bodyparser.ts
  33. 134
      config/cors.ts
  34. 52
      config/database.ts
  35. 148
      config/drive.ts
  36. 75
      config/hash.ts
  37. 118
      config/session.ts
  38. 237
      config/shield.ts
  39. 89
      config/static.ts
  40. 23
      contracts/drive.ts
  41. 25
      contracts/env.ts
  42. 30
      contracts/events.ts
  43. 19
      contracts/hash.ts
  44. 1
      database/factories/index.ts
  45. 19
      database/migrations/1637353626982_tags.ts
  46. 21
      database/migrations/1637354762904_bookmarks.ts
  47. 21
      database/migrations/1637354768649_bookmark_tags.ts
  48. 27
      env.ts
  49. 0
      linkstream/__init__.py
  50. 16
      linkstream/asgi.py
  51. 115
      linkstream/settings.example.py
  52. 7
      linkstream/urls.py
  53. 16
      linkstream/wsgi.py
  54. 22
      manage.py
  55. 41
      package.json
  56. 22
      providers/AppProvider.ts
  57. 12
      public/assets/entrypoints.json
  58. 4
      public/assets/manifest.json
  59. BIN
      public/favicon.ico
  60. 1
      resources/js/app.js
  61. 1
      resources/views/errors/not-found.edge
  62. 1
      resources/views/errors/server-error.edge
  63. 1
      resources/views/errors/unauthorized.edge
  64. 19
      server.ts
  65. 30
      setup.py
  66. 41
      start/kernel.ts
  67. 34
      start/routes.ts
  68. 37
      tsconfig.json
  69. 214
      webpack.config.js
  70. 8116
      yarn.lock

41
.adonisrc.json

@ -1,41 +0,0 @@
{
"typescript": true,
"commands": [
"./commands",
"@adonisjs/core/build/commands/index.js",
"@adonisjs/repl/build/commands",
"@adonisjs/lucid/build/commands"
],
"exceptionHandlerNamespace": "App/Exceptions/Handler",
"aliases": {
"App": "app",
"Config": "config",
"Database": "database",
"Contracts": "contracts"
},
"preloads": [
"./start/routes",
"./start/kernel"
],
"providers": [
"./providers/AppProvider",
"@adonisjs/core",
"@adonisjs/session",
"@adonisjs/view",
"@adonisjs/shield",
"@adonisjs/lucid"
],
"metaFiles": [
{
"pattern": "public/**",
"reloadServer": false
},
{
"pattern": "resources/views/**/*.edge",
"reloadServer": false
}
],
"aceProviders": [
"@adonisjs/repl"
]
}

8
.env.example

@ -1,8 +0,0 @@
PORT=3333
HOST=0.0.0.0
NODE_ENV=development
APP_KEY=as_A5GRv9cxxzMT0_WAMk3btdJWWfc70
DRIVE_DISK=local
SESSION_DRIVER=cookie
CACHE_VIEWS=false
DB_CONNECTION=sqlite

1
.eslintignore

@ -1 +0,0 @@
build

14
.eslintrc.json

@ -1,14 +0,0 @@
{
"extends": [
"plugin:adonis/typescriptApp",
"prettier"
],
"plugins": [
"prettier"
],
"rules": {
"prettier/prettier": [
"error"
]
}
}

6
.gitignore

@ -1,4 +1,4 @@
.idea/
build/
node_modules
.env
linkstream/settings.py
__pycache__/
db.sqlite3

1
.prettierignore

@ -1 +0,0 @@
build

10
.prettierrc

@ -1,10 +0,0 @@
{
"trailingComma": "es5",
"semi": false,
"singleQuote": true,
"useTabs": true,
"quoteProps": "consistent",
"bracketSpacing": true,
"arrowParens": "always",
"printWidth": 100
}

2
MANIFEST.in

@ -0,0 +1,2 @@
include bookmarks/static/*
include bookmarks/templates/*

10
README.md

@ -2,4 +2,12 @@
![trans rights!](https://awoo.systems/trans_rights_badge.svg)
Small bookmark manager, browser, sharer, and more
Small bookmark manager, browser, sharer, and more.
## Project structure
This project is a Django project, trying to follow Django standards.
The entrypoint is the `linkstream` package. Its logic is split in several packages.
- `bookmarks`: handles everything related to the bookmarking management

16
ace

@ -1,16 +0,0 @@
/*
|--------------------------------------------------------------------------
| Ace Commands
|--------------------------------------------------------------------------
|
| This file is the entry point for running ace commands.
|
*/
require('reflect-metadata')
require('source-map-support').install({ handleUncaughtExceptions: false })
const { Ignitor } = require('@adonisjs/core/build/standalone')
new Ignitor(__dirname)
.ace()
.handle(process.argv.slice(2))

269
ace-manifest.json

@ -1,269 +0,0 @@
{
"commands": {
"dump:rcfile": {
"settings": {},
"commandPath": "@adonisjs/core/build/commands/DumpRc",
"commandName": "dump:rcfile",
"description": "Dump contents of .adonisrc.json file along with defaults",
"args": [],
"aliases": [],
"flags": []
},
"list:routes": {
"settings": {
"loadApp": true
},
"commandPath": "@adonisjs/core/build/commands/ListRoutes",
"commandName": "list:routes",
"description": "List application routes",
"args": [],
"aliases": [],
"flags": [
{
"name": "json",
"propertyName": "json",
"type": "boolean",
"description": "Output as JSON"
}
]
},
"generate:key": {
"settings": {},
"commandPath": "@adonisjs/core/build/commands/GenerateKey",
"commandName": "generate:key",
"description": "Generate a new APP_KEY secret",
"args": [],
"aliases": [],
"flags": []
},
"repl": {
"settings": {
"loadApp": true,
"environment": "repl",
"stayAlive": true
},
"commandPath": "@adonisjs/repl/build/commands/AdonisRepl",
"commandName": "repl",
"description": "Start a new REPL session",
"args": [],
"aliases": [],
"flags": []
},
"db:seed": {
"settings": {
"loadApp": true
},
"commandPath": "@adonisjs/lucid/build/commands/DbSeed",
"commandName": "db:seed",
"description": "Execute database seeder files",
"args": [],
"aliases": [],
"flags": [
{
"name": "connection",
"propertyName": "connection",
"type": "string",
"description": "Define a custom database connection for the seeders",
"alias": "c"
},
{
"name": "interactive",
"propertyName": "interactive",
"type": "boolean",
"description": "Run seeders in interactive mode",
"alias": "i"
},
{
"name": "files",
"propertyName": "files",
"type": "array",
"description": "Define a custom set of seeders files names to run",
"alias": "f"
}
]
},
"make:model": {
"settings": {
"loadApp": true
},
"commandPath": "@adonisjs/lucid/build/commands/MakeModel",
"commandName": "make:model",
"description": "Make a new Lucid model",
"args": [
{
"type": "string",
"propertyName": "name",
"name": "name",
"required": true,
"description": "Name of the model class"
}
],
"aliases": [],
"flags": [
{
"name": "migration",
"propertyName": "migration",
"type": "boolean",
"alias": "m",
"description": "Generate the migration for the model"
},
{
"name": "controller",
"propertyName": "controller",
"type": "boolean",
"alias": "c",
"description": "Generate the controller for the model"
}
]
},
"make:migration": {
"settings": {
"loadApp": true
},
"commandPath": "@adonisjs/lucid/build/commands/MakeMigration",
"commandName": "make:migration",
"description": "Make a new migration file",
"args": [
{
"type": "string",
"propertyName": "name",
"name": "name",
"required": true,
"description": "Name of the migration file"
}
],
"aliases": [],
"flags": [
{
"name": "connection",
"propertyName": "connection",
"type": "string",
"description": "The connection flag is used to lookup the directory for the migration file"
},
{
"name": "folder",
"propertyName": "folder",
"type": "string",
"description": "Pre-select a migration directory"
},
{
"name": "create",
"propertyName": "create",
"type": "string",
"description": "Define the table name for creating a new table"
},
{
"name": "table",
"propertyName": "table",
"type": "string",
"description": "Define the table name for altering an existing table"
}
]
},
"make:seeder": {
"settings": {},
"commandPath": "@adonisjs/lucid/build/commands/MakeSeeder",
"commandName": "make:seeder",
"description": "Make a new Seeder file",
"args": [
{
"type": "string",
"propertyName": "name",
"name": "name",
"required": true,
"description": "Name of the seeder class"
}
],
"aliases": [],
"flags": []
},
"migration:run": {
"settings": {
"loadApp": true
},
"commandPath": "@adonisjs/lucid/build/commands/Migration/Run",
"commandName": "migration:run",
"description": "Run pending migrations",
"args": [],
"aliases": [],
"flags": [
{
"name": "connection",
"propertyName": "connection",
"type": "string",
"description": "Define a custom database connection",
"alias": "c"
},
{
"name": "force",
"propertyName": "force",
"type": "boolean",
"description": "Explicitly force to run migrations in production"
},
{
"name": "dry-run",
"propertyName": "dryRun",
"type": "boolean",
"description": "Print SQL queries, instead of running the migrations"
}
]
},
"migration:rollback": {
"settings": {
"loadApp": true
},
"commandPath": "@adonisjs/lucid/build/commands/Migration/Rollback",
"commandName": "migration:rollback",
"description": "Rollback migrations to a given batch number",
"args": [],
"aliases": [],
"flags": [
{
"name": "connection",
"propertyName": "connection",
"type": "string",
"description": "Define a custom database connection",
"alias": "c"
},
{
"name": "force",
"propertyName": "force",
"type": "boolean",
"description": "Explictly force to run migrations in production"
},
{
"name": "dry-run",
"propertyName": "dryRun",
"type": "boolean",
"description": "Print SQL queries, instead of running the migrations"
},
{
"name": "batch",
"propertyName": "batch",
"type": "number",
"description": "Define custom batch number for rollback. Use 0 to rollback to initial state"
}
]
},
"migration:status": {
"settings": {
"loadApp": true
},
"commandPath": "@adonisjs/lucid/build/commands/Migration/Status",
"commandName": "migration:status",
"description": "Check migrations current status.",
"args": [],
"aliases": [],
"flags": [
{
"name": "connection",
"propertyName": "connection",
"type": "string",
"description": "Define a custom database connection",
"alias": "c"
}
]
}
},
"aliases": {}
}

32
app/Controllers/Http/BookmarksController.ts

@ -1,32 +0,0 @@
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import Bookmark from 'App/Models/Bookmark'
import { schema, rules } from '@ioc:Adonis/Core/Validator'
import slug from 'slug'
import Tag from 'App/Models/Tag'
import {URL} from 'url'
export default class BookmarksController {
public async create({request}: HttpContextContract): Promise<Bookmark | null> {
const newBmSchema = schema.create({
title: schema.string({trim: true}),
link: schema.string({trim: true}, [rules.url()]),
tags: schema.string.optional({trim: true}),
})
const payload = await request.validate({ schema: newBmSchema })
const bm = await Bookmark.create({
slug: slug(payload.title),
title: payload.title,
link: new URL(payload.link),
})
if (payload.tags) {
const rawTags = payload.tags.split(' ').map(tag => tag.trim())
const tags = await Tag.fetchOrCreateMany('slug', rawTags.map(slug => ({slug})))
await bm.related('tags').saveMany(tags)
}
// TODO Is there a cleaner way to do this?
return Bookmark.query().where('id', bm.id).preload('tags').first()
}
}

37
app/Controllers/Http/SearchController.ts

@ -1,37 +0,0 @@
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { schema } from '@ioc:Adonis/Core/Validator'
import Bookmark from 'App/Models/Bookmark';
export type Results = unknown;
export default class SearchController {
async search({request}: HttpContextContract): Promise<Results> {
const newSearchSchema = schema.create({
query: schema.string({trim: true})
})
const payload = await request.validate({ schema: newSearchSchema })
const tokens = payload.query.split(' ').map(token => token.trim())
const {tags, excludedTags, natQuery} = tokens.reduce(
(acc, v) => {
if (v.startsWith('#')) {
acc.tags.push(v.replace(/#/, ''))
} else if (v.startsWith('-#')) {
acc.excludedTags.push(v.replace(/-#/, ''))
} else {
acc.natQuery += ` ${v}`
}
return acc
},
{tags: [], excludedTags: [], natQuery: ''} as {
tags: string[],
excludedTags: string[],
natQuery: string,
}
)
// TODO: Add inclusion and exclusion and all that bullshit
const query = Bookmark.query()
.preload('tags')
}
}

15
app/Controllers/Http/TagsController.ts

@ -1,15 +0,0 @@
import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
import { schema } from '@ioc:Adonis/Core/Validator'
import Tag from 'App/Models/Tag'
import slug from 'slug'
export default class TagsController {
public async create({request}: HttpContextContract): Promise<Tag | null> {
const newTagSchema = schema.create({
label: schema.string({trim: true}),
})
const payload = await request.validate({ schema: newTagSchema })
return await Tag.create({slug: slug(payload.label)})
}
}

29
app/Exceptions/Handler.ts

@ -1,29 +0,0 @@
/*
|--------------------------------------------------------------------------
| Http Exception Handler
|--------------------------------------------------------------------------
|
| AdonisJs will forward all exceptions occurred during an HTTP request to
| the following class. You can learn more about exception handling by
| reading docs.
|
| The exception handler extends a base `HttpExceptionHandler` which is not
| mandatory, however it can do lot of heavy lifting to handle the errors
| properly.
|
*/
import Logger from '@ioc:Adonis/Core/Logger'
import HttpExceptionHandler from '@ioc:Adonis/Core/HttpExceptionHandler'
export default class ExceptionHandler extends HttpExceptionHandler {
protected statusPages = {
'403': 'errors/unauthorized',
'404': 'errors/not-found',
'500..599': 'errors/server-error',
}
constructor() {
super(Logger)
}
}

27
app/Models/Bookmark.ts

@ -1,27 +0,0 @@
import { DateTime } from 'luxon'
import { BaseModel, column, ManyToMany, manyToMany } from '@ioc:Adonis/Lucid/Orm'
import { URL } from 'url'
import Tag from 'App/Models/Tag'
export default class Bookmark extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public slug: string
@column()
public title: string
@column()
public link: URL
@column.dateTime({ autoCreate: true })
public createdAt: DateTime
@column.dateTime({ autoCreate: true, autoUpdate: true })
public updatedAt: DateTime
@manyToMany(() => Tag)
public tags: ManyToMany<typeof Tag>
}

20
app/Models/Tag.ts

@ -1,20 +0,0 @@
import { DateTime } from 'luxon'
import { BaseModel, column, ManyToMany, manyToMany } from '@ioc:Adonis/Lucid/Orm'
import Bookmark from 'App/Models/Bookmark'
export default class Tag extends BaseModel {
@column({ isPrimary: true })
public id: number
@column()
public slug: string
@column.dateTime({ autoCreate: true })
public createdAt: DateTime
@column.dateTime({ autoCreate: true, autoUpdate: true })
public updatedAt: DateTime
@manyToMany(() => Bookmark)
public bookmarks: ManyToMany<typeof Bookmark>
}

0
bookmarks/__init__.py

7
bookmarks/admin.py

@ -0,0 +1,7 @@
# Register your models here.
from django.contrib import admin
from .models import Bookmark, Tag
admin.site.register(Bookmark)
admin.site.register(Tag)

5
bookmarks/apps.py

@ -0,0 +1,5 @@
from django.apps import AppConfig
class BookmarksConfig(AppConfig):
name = 'bookmarks'

11
bookmarks/forms.py

@ -0,0 +1,11 @@
from django import forms
class CreateBookmarkForm(forms.Form):
title = forms.CharField(label='Title', max_length=255, strip=True)
tags = forms.CharField(label='Tags', max_length=255, strip=True, required=False)
link = forms.URLField(label='Link')
class CreateTagForm(forms.Form):
slug = forms.SlugField(label='Label', max_length=255, strip=True)

41
bookmarks/migrations/0001_initial.py

@ -0,0 +1,41 @@
# Generated by Django 3.1.4 on 2021-11-20 15:08
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Bookmark',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('public_id', models.UUIDField(db_index=True, default=uuid.uuid4, unique=True)),
('title', models.CharField(max_length=255)),
('link', models.URLField()),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
],
),
migrations.CreateModel(
name='Tag',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('slug', models.SlugField(max_length=255, unique=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('bookmarks', models.ManyToManyField(to='bookmarks.Bookmark')),
],
),
migrations.AddField(
model_name='bookmark',
name='tags',
field=models.ManyToManyField(to='bookmarks.Tag'),
),
]

0
bookmarks/migrations/__init__.py

23
bookmarks/models.py

@ -0,0 +1,23 @@
from django.db import models
from uuid import uuid4
# Create your models here.
class Tag(models.Model):
slug = models.SlugField(max_length=255, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
bookmarks = models.ManyToManyField('Bookmark')
class Bookmark(models.Model):
public_id = models.UUIDField(default=uuid4, db_index=True, unique=True)
title = models.CharField(max_length=255)
link = models.URLField()
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
tags = models.ManyToManyField(Tag)

0
resources/css/app.css → bookmarks/static/bookmarks.css

44
resources/views/welcome.edge → bookmarks/templates/index.html

@ -1,18 +1,18 @@
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Bookmarks</title>
@entryPointStyles('app')
{{-- @entryPointScripts('app') --}}
<link rel="stylesheet" href="{% static 'bookmarks.css' %}">
</head>
<body>
<main>
<section>
<h2>Search</h2>
<form action="/search">
<form action="{% url 'search' %}">
<input name="query" placeholder="This random link #queer" required>
<input type="submit" value="Search">
</form>
@ -24,37 +24,25 @@
<details>
<summary>Add a bookmark</summary>
<form action="/bookmarks" method="post">
<label>
Title:
<input name="title" required>
</label>
<label>
Link:
<input type="url" name="link" required>
</label>
<label>
Tags (separated by space):
<input name="tags">
</label>
<form action="{% url 'create_bookmark' %}" method="post">
{% csrf_token %}
{{ bookmark_form }}
<input type="submit" value="Create">
</form>
</details>
<section>
@each(bm in bookmarks)
{% for bm in bookmarks %}
<article>
<h3>{{ bm.title }}</h3>
<p>
@each(tag in bm.tags)
{% for tag in bm.tags.all %}
<span>#{{ tag.slug }}</span>
@else
no tag
@end
{% endfor %}
</p>
</article>
@end
{% endfor %}
</section>
</section>
<section>
@ -63,20 +51,18 @@
<details>
<summary>Add a tag</summary>
<form action="/tags" method="post">
<label>
Label:
<input name="label" required>
</label>
<form action="{% url 'create_tag' %}" method="post">
{% csrf_token %}
{{ tag_form }}
<input type="submit" value="Create">
</form>
</details>
<ul>
@each(tag in tags)
{% for tag in tags %}
<li>{{ tag.slug }}</li>
@end
{% endfor %}
</ul>
</section>
</main>

1
bookmarks/tests.py

@ -0,0 +1 @@
# Create your tests here.

10
bookmarks/urls.py

@ -0,0 +1,10 @@
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('bookmarks', views.create_bookmark, name='create_bookmark'),
path('tags', views.create_tag, name='create_tag'),
path('search', views.search, name='search'),
]

46
bookmarks/views.py

@ -0,0 +1,46 @@
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, redirect
from .forms import CreateBookmarkForm, CreateTagForm
from .models import Bookmark, Tag
def index(req):
bookmarks = Bookmark.objects.order_by('-created_at')
tags = Tag.objects.order_by('-created_at')
return render(req, 'index.html', context={
'bookmarks': bookmarks,
'tags': tags,
'bookmark_form': CreateBookmarkForm(req.POST),
'tag_form': CreateTagForm(req.POST),
})
def create_bookmark(req):
form = CreateBookmarkForm(req.POST)
if form.is_valid():
tags = list(
map(
lambda x: Tag.objects.get_or_create(slug=x.strip())[0],
form.cleaned_data['tags'].split(' '),
),
)
b = Bookmark(title=form.cleaned_data['title'], link=form.cleaned_data['link'])
b.save()
b.tags.add(*tags)
return redirect('index')
def create_tag(req):
form = CreateTagForm(req.POST)
if form.is_valid():
Tag(slug=form.cleaned_data['slug']).save()
return redirect('index')
def search(req):
query = req.GET['query']
return HttpResponse(f'Query was "{query}"')

19
commands/index.ts

@ -1,19 +0,0 @@
import { listDirectoryFiles } from '@adonisjs/core/build/standalone'
import Application from '@ioc:Adonis/Core/Application'
/*
|--------------------------------------------------------------------------
| Exporting an array of commands
|--------------------------------------------------------------------------
|
| Instead of manually exporting each file from this directory, we use the
| helper `listDirectoryFiles` to recursively collect and export an array
| of filenames.
|
| Couple of things to note:
|
| 1. The file path must be relative from the project root and not this directory.
| 2. We must ignore this file to avoid getting into an infinite loop
|
*/
export default listDirectoryFiles(__dirname, Application.appRoot, ['./commands/index'])

276
config/app.ts

@ -1,276 +0,0 @@
/**
* Config source: https://git.io/JfefZ
*
* Feel free to let us know via PR, if you find something broken in this config
* file.
*/
import proxyAddr from 'proxy-addr'
import Env from '@ioc:Adonis/Core/Env'
import Application from '@ioc:Adonis/Core/Application'
import { ServerConfig } from '@ioc:Adonis/Core/Server'
import { LoggerConfig } from '@ioc:Adonis/Core/Logger'
import { ProfilerConfig } from '@ioc:Adonis/Core/Profiler'
import { ValidatorConfig } from '@ioc:Adonis/Core/Validator'
import { AssetsManagerConfig } from '@ioc:Adonis/Core/AssetsManager'
/*
|--------------------------------------------------------------------------
| Application secret key
|--------------------------------------------------------------------------
|
| The secret to encrypt and sign different values in your application.
| Make sure to keep the `APP_KEY` as an environment variable and secure.
|
| Note: Changing the application key for an existing app will make all
| the cookies invalid and also the existing encrypted data will not
| be decrypted.
|
*/
export const appKey: string = Env.get('APP_KEY')
/*
|--------------------------------------------------------------------------
| Http server configuration
|--------------------------------------------------------------------------
|
| The configuration for the HTTP(s) server. Make sure to go through all
| the config properties to make keep server secure.
|
*/
export const http: ServerConfig = {
/*
|--------------------------------------------------------------------------
| Allow method spoofing
|--------------------------------------------------------------------------
|
| Method spoofing enables defining custom HTTP methods using a query string
| `_method`. This is usually required when you are making traditional
| form requests and wants to use HTTP verbs like `PUT`, `DELETE` and
| so on.
|
*/
allowMethodSpoofing: false,
/*
|--------------------------------------------------------------------------
| Subdomain offset
|--------------------------------------------------------------------------
*/
subdomainOffset: 2,
/*
|--------------------------------------------------------------------------
| Request Ids
|--------------------------------------------------------------------------
|
| Setting this value to `true` will generate a unique request id for each
| HTTP request and set it as `x-request-id` header.
|
*/
generateRequestId: false,
/*
|--------------------------------------------------------------------------
| Trusting proxy servers
|--------------------------------------------------------------------------
|
| Define the proxy servers that AdonisJs must trust for reading `X-Forwarded`
| headers.
|
*/
trustProxy: proxyAddr.compile('loopback'),
/*
|--------------------------------------------------------------------------
| Generating Etag
|--------------------------------------------------------------------------
|
| Whether or not to generate an etag for every response.
|
*/
etag: false,
/*
|--------------------------------------------------------------------------
| JSONP Callback
|--------------------------------------------------------------------------
*/
jsonpCallbackName: 'callback',
/*
|--------------------------------------------------------------------------
| Cookie settings
|--------------------------------------------------------------------------
*/
cookie: {
domain: '',
path: '/',
maxAge: '2h',
httpOnly: true,
secure: false,
sameSite: false,
},
}
/*
|--------------------------------------------------------------------------
| Logger
|--------------------------------------------------------------------------
*/
export const logger: LoggerConfig = {
/*
|--------------------------------------------------------------------------
| Application name
|--------------------------------------------------------------------------
|
| The name of the application you want to add to the log. It is recommended
| to always have app name in every log line.
|
| The `APP_NAME` environment variable is automatically set by AdonisJS by
| reading the `name` property from the `package.json` file.
|
*/
name: Env.get('APP_NAME'),
/*
|--------------------------------------------------------------------------
| Toggle logger
|--------------------------------------------------------------------------
|
| Enable or disable logger application wide
|
*/
enabled: true,
/*
|--------------------------------------------------------------------------
| Logging level
|--------------------------------------------------------------------------
|
| The level from which you want the logger to flush logs. It is recommended
| to make use of the environment variable, so that you can define log levels
| at deployment level and not code level.
|
*/
level: Env.get('LOG_LEVEL', 'info'),
/*
|--------------------------------------------------------------------------
| Pretty print
|--------------------------------------------------------------------------
|
| It is highly advised NOT to use `prettyPrint` in production, since it
| can have huge impact on performance.
|
*/
prettyPrint: Env.get('NODE_ENV') === 'development',
}
/*
|--------------------------------------------------------------------------
| Profiler
|--------------------------------------------------------------------------
*/
export const profiler: ProfilerConfig = {
/*
|--------------------------------------------------------------------------
| Toggle profiler
|--------------------------------------------------------------------------
|
| Enable or disable profiler
|
*/
enabled: true,
/*
|--------------------------------------------------------------------------
| Blacklist actions/row labels
|--------------------------------------------------------------------------
|
| Define an array of actions or row labels that you want to disable from
| getting profiled.
|
*/
blacklist: [],
/*
|--------------------------------------------------------------------------
| Whitelist actions/row labels
|--------------------------------------------------------------------------
|
| Define an array of actions or row labels that you want to whitelist for
| the profiler. When whitelist is defined, then `blacklist` is ignored.
|
*/
whitelist: [],
}
/*
|--------------------------------------------------------------------------
| Validator
|--------------------------------------------------------------------------
|
| Configure the global configuration for the validator. Here's the reference
| to the default config https://git.io/JT0WE
|
*/
export const validator: ValidatorConfig = {}
/*
|--------------------------------------------------------------------------
| Assets
|--------------------------------------------------------------------------
|
| Configure the asset manager you are using to compile the frontend assets
|
*/
export const assets: AssetsManagerConfig = {
/*
|--------------------------------------------------------------------------
| Driver
|--------------------------------------------------------------------------
|
| Currently we only support webpack encore and may introduce more drivers
| in the future
|
*/
driver: 'encore',
/*
|--------------------------------------------------------------------------
| Public path
|--------------------------------------------------------------------------
|
| Directory to search for the "manifest.json" and the "entrypoints.json"
| files
|
*/
publicPath: Application.publicPath('assets'),
/*
|--------------------------------------------------------------------------
| Script tag
|--------------------------------------------------------------------------
|
| Define attributes for the entryPointScripts tags
|
*/
script: {
attributes: {
defer: true,
},
},
/*
|--------------------------------------------------------------------------
| Style tag
|--------------------------------------------------------------------------
|
| Define attributes for the entryPointStyles tags
|
*/
style: {
attributes: {},
},
}

205
config/bodyparser.ts

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

134
config/cors.ts

@ -1,134 +0,0 @@
/**
* Config source: https://git.io/JfefC
*
* Feel free to let us know via PR, if you find something broken in this config
* file.
*/
import { CorsConfig } from '@ioc:Adonis/Core/Cors'
const corsConfig: CorsConfig = {
/*
|--------------------------------------------------------------------------
| Enabled
|--------------------------------------------------------------------------
|
| A boolean to enable or disable CORS integration from your AdonisJs
| application.
|
| Setting the value to `true` will enable the CORS for all HTTP request. However,
| you can define a function to enable/disable it on per request basis as well.
|
*/
enabled: false,
// You can also use a function that return true or false.
// enabled: (request) => request.url().startsWith('/api')
/*
|--------------------------------------------------------------------------
| Origin
|--------------------------------------------------------------------------
|
| Set a list of origins to be allowed for `Access-Control-Allow-Origin`.
| The value can be one of the following:
|
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
|
| Boolean (true) - Allow current request origin.
| Boolean (false) - Disallow all.
| String - Comma separated list of allowed origins.
| Array - An array of allowed origins.
| String (*) - A wildcard (*) to allow all request origins.
| Function - Receives the current origin string and should return
| one of the above values.
|
*/
origin: true,
/*
|--------------------------------------------------------------------------
| Methods
|--------------------------------------------------------------------------
|
| An array of allowed HTTP methods for CORS. The `Access-Control-Request-Method`
| is checked against the following list.
|
| Following is the list of default methods. Feel free to add more.
*/
methods: ['GET', 'HEAD', 'POST', 'PUT', 'DELETE'],
/*
|--------------------------------------------------------------------------
| Headers
|--------------------------------------------------------------------------
|
| List of headers to be allowed for `Access-Control-Allow-Headers` header.
| The value can be one of the following:
|
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Request-Headers
|
| Boolean(true) - Allow all headers mentioned in `Access-Control-Request-Headers`.
| Boolean(false) - Disallow all headers.
| String - Comma separated list of allowed headers.
| Array - An array of allowed headers.
| Function - Receives the current header and should return one of the above values.
|
*/
headers: true,
/*
|--------------------------------------------------------------------------
| Expose Headers
|--------------------------------------------------------------------------
|
| A list of headers to be exposed by setting `Access-Control-Expose-Headers`.
| header. By default following 6 simple response headers are exposed.
|
| Cache-Control
| Content-Language
| Content-Type
| Expires
| Last-Modified
| Pragma
|
| In order to add more headers, simply define them inside the following array.
|
| https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
|
*/
exposeHeaders: [
'cache-control',
'content-language',
'content-type',
'expires',
'last-modified',
'pragma',
],