Compare commits

..

2 Commits

Author SHA1 Message Date
f401385ae6
spike: add some public files
Some checks failed
continuous-integration/drone/push Build is failing
2021-10-15 18:46:18 +02:00
e9bb1cbdc0
spike: try to install & migrate to lucky
Some checks failed
continuous-integration/drone/push Build is failing
2021-10-15 18:44:23 +02:00
235 changed files with 10170 additions and 3465 deletions

1
.crystal-version Normal file
View File

@ -0,0 +1 @@
1.1.1

9
.editorconfig Normal file
View File

@ -0,0 +1,9 @@
root = true
[*.cr]
charset = utf-8
end_of_line = lf
insert_final_newline = true
indent_style = space
indent_size = 2
trim_trailing_whitespace = true

116
.github/workflows/ci.yml vendored Normal file
View File

@ -0,0 +1,116 @@
name: kisswiki CI
on:
push:
branches: "*"
pull_request:
branches: "*"
jobs:
check-format:
strategy:
fail-fast: false
matrix:
crystal_version:
- 1.1.1
experimental:
- false
runs-on: ubuntu-latest
continue-on-error: ${{ matrix.experimental }}
steps:
- uses: actions/checkout@v2
- name: Install Crystal
uses: crystal-lang/install-crystal@v1
with:
crystal: ${{ matrix.crystal_version }}
- name: Format
run: crystal tool format --check
specs:
strategy:
fail-fast: false
matrix:
crystal_version:
- 1.1.1
experimental:
- false
runs-on: ubuntu-latest
env:
LUCKY_ENV: test
DB_HOST: postgres
continue-on-error: ${{ matrix.experimental }}
services:
postgres:
image: postgres:12-alpine
env:
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
# Set health checks to wait until postgres has started
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v2
- name: Install Crystal
uses: crystal-lang/install-crystal@v1
with:
crystal: ${{ matrix.crystal_version }}
- name: Get yarn cache directory path
id: yarn-cache-dir-path
run: echo "::set-output name=dir::$(yarn cache dir)"
- name: Set up Yarn cache
uses: actions/cache@v2
with:
path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-yarn-
- name: Set up Node cache
uses: actions/cache@v2
id: node-cache # use this to check for `cache-hit` (`steps.node-cache.outputs.cache-hit != 'true'`)
with:
path: '**/node_modules'
key: ${{ runner.os }}-node-${{ hashFiles('**/yarn.lock') }}
restore-keys: |
${{ runner.os }}-node-
- name: Set up Crystal cache
uses: actions/cache@v2
id: crystal-cache
with:
path: |
~/.cache/crystal
lib
lucky_tasks
key: ${{ runner.os }}-crystal-${{ hashFiles('**/shard.lock') }}
restore-keys: |
${{ runner.os }}-crystal-
- name: Install shards
if: steps.crystal-cache.outputs.cache-hit != 'true'
run: shards check || shards install
- name: Install yarn packages
if: steps.node-cache.outputs.cache-hit != 'true'
run: yarn install --frozen-lockfile --no-progress
- name: Compiling assets
run: yarn prod
- name: Build lucky_tasks
if: steps.crystal-cache.outputs.cache-hit != 'true'
run: crystal build tasks.cr -o ./lucky_tasks
- name: Prepare database
run: |
./lucky_tasks db.create
./lucky_tasks db.migrate
./lucky_tasks db.seed.required_data
- name: Run tests
run: crystal spec

17
.gitignore vendored
View File

@ -1,12 +1,15 @@
/doc/
/docs/
/lib/
/bin/
/.shards/
/.crystal/
*.dwarf
start_server
*.dwarf
*.local.cr
.env
/wikicr
/data/
/meta/
/tmp
#/public/js
#/public/css
#/public/mix-manifest.json
/node_modules
yarn-error.log

View File

@ -1 +1,22 @@
language: crystal
addons:
chrome: stable
services:
- postgresql
before_install:
# Setup chromedriver for LuckyFlow
- sudo apt-get install chromium-chromedriver
# Setup assets
- yarn install
- yarn prod
script:
- crystal spec
# Uncomment the next line if you'd like Travis to check code formatting
# - crystal tool format spec src --check
cache:
yarn: true
directories:
- bin/lucky
- lib
- .shards

674
LICENSE
View File

@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
{one line to give the program's name and a brief idea of what it does.}
Copyright (C) {year} {name of author}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
{project} Copyright (C) {year} {fullname}
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View File

@ -1,26 +0,0 @@
NAME=wikicr
all: deps_opt build
run:
crystal run src/$(NAME).cr --error-trace
build:
crystal build src/$(NAME).cr --stats --error-trace
release:
crystal build src/$(NAME).cr --stats --release
test:
crystal spec --error-trace
deps:
shards install
deps_update:
shards update
deps_opt:
@[ -d lib/ ] || make deps
doc:
crystal docs
clean:
rm $(NAME)
format:
crystal tool format
.PHONY: all run build release test deps deps_update clean doc format

2
Procfile Normal file
View File

@ -0,0 +1,2 @@
web: bin/kisswiki
release: lucky db.migrate

3
Procfile.dev Normal file
View File

@ -0,0 +1,3 @@
system_check: script/system_check && sleep 100000
web: lucky watch --reload-browser
assets: yarn watch

173
README.md
View File

@ -1,169 +1,14 @@
**Migrated to <https://git.sceptique.eu/Sceptique/wikicr>**
# kisswiki
# wikicr
This is a project written using [Lucky](https://luckyframework.org). Enjoy!
[![Build Status](https://drone.sceptique.eu/api/badges/Sceptique/wikicr/status.svg)](https://drone.sceptique.eu/Sceptique/wikicr)
### Setting up the project
Wiki in crystal and markdown
1. [Install required dependencies](https://luckyframework.org/guides/getting-started/installing#install-required-dependencies)
1. Update database settings in `config/database.cr`
1. Run `script/setup`
1. Run `lucky dev` to start the app
The pages of the wiki are written in markdown and committed on the git repository where it is started.
### Learning Lucky
## How to install
### Dependencies
Verify that you have crystal v1.0.0 or greater installed, as well as shards and git.
### Get the application
git clone https://github.com/Nephos/wikicr.git
cd wikicr
### Test the application
make test
### Build the binary
make
### Run the server
./wikicr --port 3000
INVERT_THEME=true ./wikicr --port 3000 # dark mode
### Verify your files
A directory `meta/` should be created into wikicr.
It must contains several files and directories (acl, index, users, ...).
You may want to save this directory because it contains meta-data about the pages.
Another `data/` should be a git repository (initialized at the first start).
Those files are the ALL the "displayed data" of the wiki.
## Security and ACLs
* Admin panel to manage the directories and pages
* Rules on directories are terminated with a \*
* If several rules conflict, take the more specific one
* Directories with the longer name prevails
* Files rules prevails over directory rules
## Administration and usage tutorial
### Edit / Create a page
<img width=240 src="https://i.imgur.com/5bfJstb.png" />
### Show a page
<img width=240 src="https://i.imgur.com/gllJ8Nr.png" />
### Remove a page
Simply edit the page to remove and delete all the content.
The page will be deleted completely.
### Administrate users and acls
<img width=240 src="https://i.imgur.com/1zWiAV3.png" />
### Custom Markdown
A special markdown (wikimd) is used in the pages. It provides several interesting features:
#### Internal links
An internal link will search through the index of pages to find a matching one and render a valid link to it.
```markdown
blabla [[my page]] blabla
```
##### Notes about the wikimd
- internal link algorithm have been benchmarked a bit
[benchmark link](https://gist.github.com/Nephos/ad292a3e2acc9201e6ea6342eb85dacb)
The algorithm has been improved since, but it gave me a first idea of what to do.
## Development and Roadmap
### You want to add or modify something ?
Don't hesitate to open an issue, I'm always happy to discuss about my projects
or include other developers than me.
## Contributing
1. Open an issue to see what you want to implement and how to do it.
2. Fork it ( https://github.com/Nephos/wikicr/fork )
3. Create your feature branch (git checkout -b my-new-feature)
4. Commit your changes (git commit -am 'Add some feature')
5. Push to the branch (git push origin my-new-feature)
6. Create a new Pull Request
### Operations
For now, there is no "important" core operation to add (they are all already implemented).
However, there are still lots of improvements to write on the current implementation,
documentation, security check, error management and consistency of the code.
- [x] (core) View wiki pages
- [x] (core) Write new wiki page, edit existing ones
- [x] (core) Chroot the files to data/: avoid writing / reading files outside of data/
- [x] (core) If page does not exists, form to create it: if a file does not exist, display the edit form
- [x] (core) Delete pages: remove the content of a page should remove the file
- [x] (core) Index of pages: each modification of a page should update and index with all these pages (with first h1 and url)
- [x] (core) Choose between sqlite3 and the file system for the index: sqlite = sql, fs = easier
- [x] (core) Move page (rename): box with "mv X Y" and git commit
- [x] (core) Lock system for acl/users/index: A thread safe method should be provided to avoid conflict when executing read+write or write operations
### Git
At the beginning, I tried to used libgit2. However, it seems to be a bad idea
because the lib was not documented (no tutorial or at least not up-to-date, API
not very well documented, etc.) so I want to write a little git-* wrapper to
handle some operations (add, commit, revert, etc.).
It is not something very likely to be done first (even if it's a lot of important
features) because it is boring and requires to take care of the security issues.
I must have to replace the "system" calls (in backquote) with `Proccess.new.run`.
- [x] (git) Commit when write on a file: every modification on data/ should be committed
- [ ] (git) List of revisions on a file (using git): list the revision of a file
- [ ] (git) Revert a revision (avoid vandalism): button to remove a revision (git revert)
### Web
There is some important features in order to have a good interface and a fluent
wiki experience. That's not the stuff I prefer because it requires some css/js
(front-end stuff).
There is also work around string matching to write a valid research engine.
This is the most important feature to add right now.
- [x] (web) Add content table: if titles are written, give a content table with them and links to anchors
- [x] (web) Sitemap: add a list of all the files available
- [x] (web) User login / registration: keep a file with login:group:bcryptpassords
- [x] (web) User ACL basic (read / write): the groups have rights on directories (globing)
- [x] (web) Groups ACL on EVERY wiki url
- [ ] (web) Search a page: an input that search a page (content, title) with auto-completion
- [ ] (web) Template loader (files in public/): load css, js etc. from public/
- [ ] (web) File upload and lists: page that add a file in uploads/
- [ ] (web) Tags for pages (index): extended markdown and index to keep a list of pages
### Advanced usage
The current implementation of Markdown in crystal is limited and may be fully rewritten with more standard features in some weeks or months.
For now, I choose to use Markd, another markdown parser, and wrote a wikimd wrapper (Wikicr::Page::Markdown).
It allows me to expand the default markdown by writting HTML inside the markdown to render.
The rest is boring stuff (code factorization, make everything configurable, document the code, add a lot of specs, ...).
- [x] (edit) Handle `[[tag]]`: markdown extended to search in the page index (url and title)
- [x] (edit) Handle `[[tag|title]]`: same than internal links but with a fixed title
- [ ] (core) Index the internal links of a page to update them if a page is move or the title changed.
- [ ] (web) Configuration page: title of the wiki, rights of the files, etc. should be configurable
- [ ] (conf) Handle environment variables in a .env file
- [ ] (core) Extensions loader (.so files + extended markdown ?): extend the wiki features with hooks
### Other
- [x] Improve the controller/routes architecture
## Contributors
- [Sceptique](https://git.sceptique.eu/Sceptique) Arthur Poulet - creator, maintainer
Lucky uses the [Crystal](https://crystal-lang.org) programming language. You can learn about Lucky from the [Lucky Guides](https://luckyframework.org/guides/getting-started/why-lucky).

26
bs-config.js Normal file
View File

@ -0,0 +1,26 @@
/*
| Browser-sync config file
|
| For up-to-date information about the options:
| http://www.browsersync.io/docs/options/
|
*/
module.exports = {
snippetOptions: {
rule: {
match: /<\/head>/i,
fn: function (snippet, match) {
return snippet + match;
}
}
},
files: ["public/css/**/*.css", "public/js/**/*.js"],
watchEvents: ["change"],
open: false,
browser: "default",
ghostMode: false,
ui: false,
online: false,
logConnections: false
};

View File

@ -1,9 +0,0 @@
require "./routes"
Kemal::Session.config do |config|
config.cookie_name = "session_id"
config.secret = ENV["WIKI_SECRET"]? || Random::Secure.base64(64)
config.gc_interval = 2.minutes # 2 minutes
end
Kemal.run

10
config/authentic.cr Normal file
View File

@ -0,0 +1,10 @@
require "./server"
Authentic.configure do |settings|
settings.secret_key = Lucky::Server.settings.secret_key_base
unless LuckyEnv.production?
fastest_encryption_possible = 4
settings.encryption_cost = fastest_encryption_possible
end
end

4
config/colors.cr Normal file
View File

@ -0,0 +1,4 @@
# This enables the color output when in development or test
# Check out the Colorize docs for more information
# https://crystal-lang.org/api/Colorize.html
Colorize.enabled = LuckyEnv.development? || LuckyEnv.test?

25
config/cookies.cr Normal file
View File

@ -0,0 +1,25 @@
require "./server"
Lucky::Session.configure do |settings|
settings.key = "_kisswiki_session"
end
Lucky::CookieJar.configure do |settings|
settings.on_set = ->(cookie : HTTP::Cookie) {
# If ForceSSLHandler is enabled, only send cookies over HTTPS
cookie.secure(Lucky::ForceSSLHandler.settings.enabled)
# By default, don't allow reading cookies with JavaScript
cookie.http_only(true)
# Restrict cookies to a first-party or same-site context
cookie.samesite(:lax)
# Set all cookies to the root path by default
cookie.path("/")
# You can set other defaults for cookies here. For example:
#
# cookie.expires(1.year.from_now).domain("mydomain.com")
}
end

29
config/database.cr Normal file
View File

@ -0,0 +1,29 @@
database_name = "kisswiki_#{LuckyEnv.environment}"
AppDatabase.configure do |settings|
if LuckyEnv.production?
settings.credentials = Avram::Credentials.parse(ENV["DATABASE_URL"])
else
settings.credentials = Avram::Credentials.parse?(ENV["DATABASE_URL"]?) || Avram::Credentials.new(
database: database_name,
hostname: ENV["DB_HOST"]? || "localhost",
port: ENV["DB_PORT"]?.try(&.to_i) || 5432,
# Some common usernames are "postgres", "root", or your system username (run 'whoami')
username: ENV["DB_USERNAME"]? || "postgres",
# Some Postgres installations require no password. Use "" if that is the case.
password: ENV["DB_PASSWORD"]? || "postgres"
)
end
end
Avram.configure do |settings|
settings.database_to_migrate = AppDatabase
# In production, allow lazy loading (N+1).
# In development and test, raise an error if you forget to preload associations
settings.lazy_load_enabled = LuckyEnv.production?
# Always parse `Time` values with these specific formats.
# Used for both database values, and datetime input fields.
# settings.time_formats << "%F"
end

View File

@ -1,7 +0,0 @@
FROM crystallang/crystal:lastest
WORKDIR /app/user
ADD . /app/user
RUN crystal deps

26
config/email.cr Normal file
View File

@ -0,0 +1,26 @@
require "carbon_sendgrid_adapter"
BaseEmail.configure do |settings|
if LuckyEnv.production?
# If you don't need to send emails, set the adapter to DevAdapter instead:
#
# settings.adapter = Carbon::DevAdapter.new
#
# If you do need emails, get a key from SendGrid and set an ENV variable
send_grid_key = send_grid_key_from_env
settings.adapter = Carbon::SendGridAdapter.new(api_key: send_grid_key)
elsif LuckyEnv.development?
settings.adapter = Carbon::DevAdapter.new(print_emails: true)
else
settings.adapter = Carbon::DevAdapter.new
end
end
private def send_grid_key_from_env
ENV["SEND_GRID_KEY"]? || raise_missing_key_message
end
private def raise_missing_key_message
puts "Missing SEND_GRID_KEY. Set the SEND_GRID_KEY env variable to 'unused' if not sending emails, or set the SEND_GRID_KEY ENV var.".colorize.red
exit(1)
end

33
config/env.cr Normal file
View File

@ -0,0 +1,33 @@
# Environments are managed using `LuckyEnv`. By default, development, production
# and test are supported. See
# https://luckyframework.org/guides/getting-started/configuration for details.
#
# The default environment is development unless the environment variable
# LUCKY_ENV is set.
#
# Example:
# ```
# LuckyEnv.environment # => "development"
# LuckyEnv.development? # => true
# LuckyEnv.production? # => false
# LuckyEnv.test? # => false
# ```
#
# New environments can be added using the `LuckyEnv.add_env` macro.
#
# Example:
# ```
# LuckyEnv.add_env :staging
# LuckyEnv.staging? # => false
# ```
#
# To determine whether or not a `LuckyTask` is currently running, you can use
# the `LuckyEnv.task?` predicate.
#
# Example:
# ```
# LuckyEnv.task? # => false
# ```
# Add a staging environment.
# LuckyEnv.add_env :staging

3
config/error_handler.cr Normal file
View File

@ -0,0 +1,3 @@
Lucky::ErrorHandler.configure do |settings|
settings.show_debug_output = !LuckyEnv.production?
end

3
config/html_page.cr Normal file
View File

@ -0,0 +1,3 @@
Lucky::HTMLPage.configure do |settings|
settings.render_component_comments = !LuckyEnv.production?
end

45
config/log.cr Normal file
View File

@ -0,0 +1,45 @@
require "file_utils"
if LuckyEnv.test?
# Logs to `tmp/test.log` so you can see what's happening without having
# a bunch of log output in your spec results.
FileUtils.mkdir_p("tmp")
backend = Log::IOBackend.new(File.new("tmp/test.log", mode: "w"))
backend.formatter = Lucky::PrettyLogFormatter.proc
Log.dexter.configure(:debug, backend)
elsif LuckyEnv.production?
# Lucky uses JSON in production so logs can be searched more easily
#
# If you want logs like in develpoment use 'Lucky::PrettyLogFormatter.proc'.
backend = Log::IOBackend.new
backend.formatter = Dexter::JSONLogFormatter.proc
Log.dexter.configure(:info, backend)
else
# Use a pretty formatter printing to STDOUT in development
backend = Log::IOBackend.new
backend.formatter = Lucky::PrettyLogFormatter.proc
Log.dexter.configure(:debug, backend)
DB::Log.level = :info
end
# Lucky only logs when before/after pipes halt by redirecting, or rendering a
# response. Pipes that run without halting are not logged.
#
# If you want to log every pipe that runs, set the log level to ':info'
Lucky::ContinuedPipeLog.dexter.configure(:none)
# Lucky only logs failed queries by default.
#
# Set the log to ':info' to log all queries
Avram::QueryLog.dexter.configure(:none)
# Skip logging static assets requests in development
Lucky::LogHandler.configure do |settings|
if LuckyEnv.development?
settings.skip_if = ->(context : HTTP::Server::Context) {
context.request.method.downcase == "get" &&
context.request.resource.starts_with?(/\/css\/|\/js\/|\/assets\/|\/favicon\.ico/)
}
end
end

10
config/route_helper.cr Normal file
View File

@ -0,0 +1,10 @@
# This is used when generating URLs for your application
Lucky::RouteHelper.configure do |settings|
if LuckyEnv.production?
# Example: https://my_app.com
settings.base_uri = ENV.fetch("APP_DOMAIN")
else
# Set domain to the default host/port in development/test
settings.base_uri = "http://localhost:#{Lucky::ServerSettings.port}"
end
end

View File

@ -1,39 +0,0 @@
class Router
{% for verb in {:get, :post, :delete, :patch, :put, :head} %}
macro {{verb.id}}(route, controller, method)
::{{verb.id}}(\{{route}}) do |env|
context = \{{controller}}.new(env)
# puts "Before init"
# pp env.request.cookies
# pp env.response.cookies
context.cookies.fill_from_client_headers(env.request.headers)
# puts "After init"
# pp env.request.cookies
# pp env.response.cookies
output = context.\{{method.id}}()
# puts "After controller"
# pp env.request.cookies
# pp env.response.cookies
#context.cookies.add_response_headers(env.response.headers)
output
end
end
{% end %}
end
Router.get "/", HomeController, :index
Router.get "/sitemap", PagesController, :sitemap
Router.get "/pages/search", PagesController, :search
Router.get "/pages/*path", PagesController, :show
Router.post "/pages/*path", PagesController, :update
Router.get "/users/login", UsersController, :login
Router.post "/users/login", UsersController, :login_validates
Router.get "/users/register", UsersController, :register
Router.post "/users/register", UsersController, :register_validates
Router.get "/admin/users", AdminController, :users_show
Router.post "/admin/users/create", AdminController, :user_create
Router.post "/admin/users/delete", AdminController, :user_delete
Router.get "/admin/acls", AdminController, :acls_show
Router.post "/admin/acls/update", AdminController, :acl_update
Router.post "/admin/acls/create", AdminController, :acl_create
Router.post "/admin/acls/delete", AdminController, :acl_delete

56
config/server.cr Normal file
View File

@ -0,0 +1,56 @@
# Here is where you configure the Lucky server
#
# Look at config/route_helper.cr if you want to change the domain used when
# generating links with `Action.url`.
Lucky::Server.configure do |settings|
if LuckyEnv.production?
settings.secret_key_base = secret_key_from_env
settings.host = "0.0.0.0"
settings.port = ENV["PORT"].to_i
settings.gzip_enabled = true
# By default certain content types will be gzipped.
# For a full list look in
# https://github.com/luckyframework/lucky/blob/master/src/lucky/server.cr
# To add additional extensions do something like this:
# settings.gzip_content_types << "content/type"
else
settings.secret_key_base = "2MZZcc/iAkP/JTs+8ZGcMq440IhuX1rpiA5XdooSR5Q="
# Change host/port in config/watch.yml
# Alternatively, you can set the DEV_PORT env to set the port for local development
settings.host = Lucky::ServerSettings.host
settings.port = Lucky::ServerSettings.port
end
# By default Lucky will serve static assets in development and production.
#
# However you could use a CDN when in production like this:
#
# Lucky::Server.configure do |settings|
# if LuckyEnv.production?
# settings.asset_host = "https://mycdnhost.com"
# else
# settings.asset_host = ""
# end
# end
settings.asset_host = "" # Lucky will serve assets
end
Lucky::ForceSSLHandler.configure do |settings|
# To force SSL in production, uncomment the lines below.
# This will cause http requests to be redirected to https:
#
# settings.enabled = LuckyEnv.production?
# settings.strict_transport_security = {max_age: 1.year, include_subdomains: true}
#
# Or, leave it disabled:
settings.enabled = false
end
private def secret_key_from_env
ENV["SECRET_KEY_BASE"]? || raise_missing_secret_key_in_production
end
private def raise_missing_secret_key_in_production
puts "Please set the SECRET_KEY_BASE environment variable. You can generate a secret key with 'lucky gen.secret_key'".colorize.red
exit(1)
end

2
config/watch.yml Normal file
View File

@ -0,0 +1,2 @@
host: 127.0.0.1
port: 5000

0
db/migrations/.keep Normal file
View File

View File

@ -0,0 +1,17 @@
class CreateUsers::V00000000000001 < Avram::Migrator::Migration::V1
def migrate
enable_extension "citext"
create table_for(User) do
primary_key id : Int64
add_timestamps
add email : String, unique: true, case_sensitive: false
add encrypted_password : String
end
end
def rollback
drop table_for(User)
disable_extension "citext"
end
end

View File

@ -0,0 +1,18 @@
class CreateUserAcls::V20211014212427 < Avram::Migrator::Migration::V1
def migrate
# Learn about migrations at: https://luckyframework.org/guides/database/migrations
create table_for(UserAcls) do
primary_key id : UUID
add_timestamps
add_belongs_to user : User, on_delete: :cascade, foreign_key_type: Int64
add path : String
add permission : String
end
create_index :user_acls, [:user_id, :path], unique: false
end
def rollback
drop table_for(UserAcls)
end
end

View File

@ -0,0 +1,25 @@
class CreatePages::V20211014213500 < Avram::Migrator::Migration::V1
def migrate
# Learn about migrations at: https://luckyframework.org/guides/database/migrations
create table_for(Page) do
primary_key id : UUID
add_timestamps
add file_path : String, unique: true
add web_path : String, unique: true
add title : String
add slug : String
add toc : Array(String)
add keywords : Array(String)
add last_touched_at : Time
add_belongs_to created_by : User, on_delete: :nullify, foreign_key_type: Int64
add_belongs_to last_edited_by : User, on_delete: :nullify, foreign_key_type: Int64
end
create_index :pages, [:last_touched_at]
create_index :pages, [:keywords]
end
def rollback
drop table_for(Page)
end
end

View File

@ -0,0 +1,17 @@
class CreatePageRevisions::V20211014221710 < Avram::Migrator::Migration::V1
def migrate
# Learn about migrations at: https://luckyframework.org/guides/database/migrations
create table_for(PageRevisions) do
primary_key id : Int64
add_timestamps
add_belongs_to page : Page, on_delete: :cascade, foreign_key_type: UUID
add_belongs_to user : User, on_delete: :cascade, foreign_key_type: Int64
add commit : String
add body : String
end
end
def rollback
drop table_for(PageRevisions)
end
end

View File

@ -1,17 +0,0 @@
version: '2'
services:
web:
build: .
image: wikicr
command: './wikicr'
working_dir: /app/user
environment:
ports:
- '3000:3000'
depends_on:
volumes:
- '.:/app/user'
volumes:
db:

25
package.json Normal file
View File

@ -0,0 +1,25 @@
{
"license": "UNLICENSED",
"private": true,
"dependencies": {
"@rails/ujs": "^6.0.0",
"modern-normalize": "^1.1.0",
"turbolinks": "^5.2.0"
},
"scripts": {
"heroku-postbuild": "yarn prod",
"dev": "mix",
"watch": "mix watch",
"prod": "mix --production"
},
"devDependencies": {
"@babel/compat-data": "^7.9.0",
"browser-sync": "^2.26.7",
"compression-webpack-plugin": "^7.0.0",
"laravel-mix": "^6.0.0",
"postcss": "^8.1.0",
"resolve-url-loader": "^3.1.1",
"sass": "^1.26.10",
"sass-loader": "^10.0.2"
}
}

View File

View File

@ -1,15 +0,0 @@
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<!-- Read this: www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->
<!-- Most restrictive policy: -->
<site-control permitted-cross-domain-policies="none"/>
<!-- Least restrictive policy: -->
<!--
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*" to-ports="*" secure="false"/>
<allow-http-request-headers-from domain="*" headers="*" secure="false"/>
-->
</cross-domain-policy>

345
public/css/app.css Normal file
View File

@ -0,0 +1,345 @@
/*! modern-normalize v1.1.0 | MIT License | https://github.com/sindresorhus/modern-normalize */
/*
Document
========
*/
/**
Use a better box model (opinionated).
*/
*,
::before,
::after {
box-sizing: border-box;
}
/**
Use a more readable tab size (opinionated).
*/
html {
-moz-tab-size: 4;
-o-tab-size: 4;
tab-size: 4;
}
/**
1. Correct the line height in all browsers.
2. Prevent adjustments of font size after orientation changes in iOS.
*/
html {
line-height: 1.15; /* 1 */
-webkit-text-size-adjust: 100%; /* 2 */
}
/*
Sections
========
*/
/**
Remove the margin in all browsers.
*/
body {
margin: 0;
}
/**
Improve consistency of default fonts in all browsers. (https://github.com/sindresorhus/modern-normalize/issues/3)
*/
body {
font-family:
system-ui,
-apple-system, /* Firefox supports this but not yet `system-ui` */
'Segoe UI',
Roboto,
Helvetica,
Arial,
sans-serif,
'Apple Color Emoji',
'Segoe UI Emoji';
}
/*
Grouping content
================
*/
/**
1. Add the correct height in Firefox.
2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655)
*/
hr {
height: 0; /* 1 */
color: inherit; /* 2 */
}
/*
Text-level semantics
====================
*/
/**
Add the correct text decoration in Chrome, Edge, and Safari.
*/
abbr[title] {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
}
/**
Add the correct font weight in Edge and Safari.
*/
b,
strong {
font-weight: bolder;
}
/**
1. Improve consistency of default fonts in all browsers. (https://github.com/sindresorhus/modern-normalize/issues/3)
2. Correct the odd 'em' font sizing in all browsers.
*/
code,
kbd,
samp,
pre {
font-family:
ui-monospace,
SFMono-Regular,
Consolas,
'Liberation Mono',
Menlo,
monospace; /* 1 */
font-size: 1em; /* 2 */
}
/**
Add the correct font size in all browsers.
*/
small {
font-size: 80%;
}
/**
Prevent 'sub' and 'sup' elements from affecting the line height in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
/*
Tabular data
============
*/
/**
1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297)
2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016)
*/
table {
text-indent: 0; /* 1 */
border-color: inherit; /* 2 */
}
/*
Forms
=====
*/
/**
1. Change the font styles in all browsers.
2. Remove the margin in Firefox and Safari.
*/
button,
input,
optgroup,
select,
textarea {
font-family: inherit; /* 1 */
font-size: 100%; /* 1 */
line-height: 1.15; /* 1 */
margin: 0; /* 2 */
}
/**
Remove the inheritance of text transform in Edge and Firefox.
1. Remove the inheritance of text transform in Firefox.
*/
button,
select { /* 1 */
text-transform: none;
}
/**
Correct the inability to style clickable types in iOS and Safari.
*/
button,
[type='button'],
[type='reset'],
[type='submit'] {
-webkit-appearance: button;
}
/**
Remove the inner border and padding in Firefox.
*/
::-moz-focus-inner {
border-style: none;
padding: 0;
}
/**
Restore the focus styles unset by the previous rule.
*/
:-moz-focusring {
outline: 1px dotted ButtonText;
}
/**
Remove the additional ':invalid' styles in Firefox.
See: https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737
*/
:-moz-ui-invalid {
box-shadow: none;
}
/**
Remove the padding so developers are not caught out when they zero out 'fieldset' elements in all browsers.
*/
legend {
padding: 0;
}
/**
Add the correct vertical alignment in Chrome and Firefox.
*/
progress {
vertical-align: baseline;
}
/**
Correct the cursor style of increment and decrement buttons in Safari.
*/
::-webkit-inner-spin-button,
::-webkit-outer-spin-button {
height: auto;
}
/**
1. Correct the odd appearance in Chrome and Safari.
2. Correct the outline style in Safari.
*/
[type='search'] {
-webkit-appearance: textfield; /* 1 */
outline-offset: -2px; /* 2 */
}
/**
Remove the inner padding in Chrome and Safari on macOS.
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
1. Correct the inability to style clickable types in iOS and Safari.
2. Change font properties to 'inherit' in Safari.
*/
::-webkit-file-upload-button {
-webkit-appearance: button; /* 1 */
font: inherit; /* 2 */
}
/*
Interactive
===========
*/
/*
Add the correct display in Chrome and Safari.
*/
summary {
display: list-item;
}
body {
font-family: system-ui, BlinkMacSystemFont, -apple-system, Segoe UI, Roboto, Oxygen, Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
margin: 0 auto;
max-width: 800px;
padding: 20px 40px;
}
label, input {
display: flex;
}
label {
font-weight: 500;
}
[type=color],
[type=date],
[type=datetime],
[type=datetime-local],
[type=email],
[type=month],
[type=number],
[type=password],
[type=search],
[type=tel],
[type=text],
[type=time],
[type=url],
[type=week],
input:not([type]),
textarea {
border-radius: 3px;
border: 1px solid #bbb;
margin: 7px 0 14px 0;
max-width: 400px;
padding: 8px 6px;
width: 100%;
}
[type=submit] {
font-weight: 900;
margin: 9px 0;
padding: 6px 9px;
}

0
public/favicon.ico Normal file
View File

View File

Before

Width:  |  Height:  |  Size: 434 KiB

After

Width:  |  Height:  |  Size: 434 KiB

View File

Before

Width:  |  Height:  |  Size: 106 KiB

After

Width:  |  Height:  |  Size: 106 KiB

938
public/js/app.js Normal file
View File

@ -0,0 +1,938 @@
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ "./node_modules/@rails/ujs/lib/assets/compiled/rails-ujs.js":
/*!******************************************************************!*\
!*** ./node_modules/@rails/ujs/lib/assets/compiled/rails-ujs.js ***!
\******************************************************************/
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;/*
Unobtrusive JavaScript
https://github.com/rails/rails/blob/main/actionview/app/assets/javascripts
Released under the MIT license
*/;
(function() {
var context = this;
(function() {
(function() {
this.Rails = {
linkClickSelector: 'a[data-confirm], a[data-method], a[data-remote]:not([disabled]), a[data-disable-with], a[data-disable]',
buttonClickSelector: {
selector: 'button[data-remote]:not([form]), button[data-confirm]:not([form])',
exclude: 'form button'
},
inputChangeSelector: 'select[data-remote], input[data-remote], textarea[data-remote]',
formSubmitSelector: 'form:not([data-turbo=true])',
formInputClickSelector: 'form:not([data-turbo=true]) input[type=submit], form:not([data-turbo=true]) input[type=image], form:not([data-turbo=true]) button[type=submit], form:not([data-turbo=true]) button:not([type]), input[type=submit][form], input[type=image][form], button[type=submit][form], button[form]:not([type])',
formDisableSelector: 'input[data-disable-with]:enabled, button[data-disable-with]:enabled, textarea[data-disable-with]:enabled, input[data-disable]:enabled, button[data-disable]:enabled, textarea[data-disable]:enabled',
formEnableSelector: 'input[data-disable-with]:disabled, button[data-disable-with]:disabled, textarea[data-disable-with]:disabled, input[data-disable]:disabled, button[data-disable]:disabled, textarea[data-disable]:disabled',
fileInputSelector: 'input[name][type=file]:not([disabled])',
linkDisableSelector: 'a[data-disable-with], a[data-disable]',
buttonDisableSelector: 'button[data-remote][data-disable-with], button[data-remote][data-disable]'
};
}).call(this);
}).call(context);
var Rails = context.Rails;
(function() {
(function() {
var nonce;
nonce = null;
Rails.loadCSPNonce = function() {
var ref;
return nonce = (ref = document.querySelector("meta[name=csp-nonce]")) != null ? ref.content : void 0;
};
Rails.cspNonce = function() {
return nonce != null ? nonce : Rails.loadCSPNonce();
};
}).call(this);
(function() {
var expando, m;
m = Element.prototype.matches || Element.prototype.matchesSelector || Element.prototype.mozMatchesSelector || Element.prototype.msMatchesSelector || Element.prototype.oMatchesSelector || Element.prototype.webkitMatchesSelector;
Rails.matches = function(element, selector) {
if (selector.exclude != null) {
return m.call(element, selector.selector) && !m.call(element, selector.exclude);
} else {
return m.call(element, selector);
}
};
expando = '_ujsData';
Rails.getData = function(element, key) {
var ref;
return (ref = element[expando]) != null ? ref[key] : void 0;
};
Rails.setData = function(element, key, value) {
if (element[expando] == null) {
element[expando] = {};
}
return element[expando][key] = value;
};
Rails.$ = function(selector) {
return Array.prototype.slice.call(document.querySelectorAll(selector));
};
}).call(this);
(function() {
var $, csrfParam, csrfToken;
$ = Rails.$;
csrfToken = Rails.csrfToken = function() {
var meta;
meta = document.querySelector('meta[name=csrf-token]');
return meta && meta.content;
};
csrfParam = Rails.csrfParam = function() {
var meta;
meta = document.querySelector('meta[name=csrf-param]');
return meta && meta.content;
};
Rails.CSRFProtection = function(xhr) {
var token;
token = csrfToken();
if (token != null) {
return xhr.setRequestHeader('X-CSRF-Token', token);
}
};
Rails.refreshCSRFTokens = function() {
var param, token;
token = csrfToken();
param = csrfParam();
if ((token != null) && (param != null)) {
return $('form input[name="' + param + '"]').forEach(function(input) {
return input.value = token;
});
}
};
}).call(this);
(function() {
var CustomEvent, fire, matches, preventDefault;
matches = Rails.matches;
CustomEvent = window.CustomEvent;
if (typeof CustomEvent !== 'function') {
CustomEvent = function(event, params) {
var evt;
evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
CustomEvent.prototype = window.Event.prototype;
preventDefault = CustomEvent.prototype.preventDefault;
CustomEvent.prototype.preventDefault = function() {
var result;
result = preventDefault.call(this);
if (this.cancelable && !this.defaultPrevented) {
Object.defineProperty(this, 'defaultPrevented', {
get: function() {
return true;
}
});
}
return result;
};
}
fire = Rails.fire = function(obj, name, data) {
var event;
event = new CustomEvent(name, {
bubbles: true,
cancelable: true,
detail: data
});
obj.dispatchEvent(event);
return !event.defaultPrevented;
};
Rails.stopEverything = function(e) {
fire(e.target, 'ujs:everythingStopped');
e.preventDefault();
e.stopPropagation();
return e.stopImmediatePropagation();
};
Rails.delegate = function(element, selector, eventType, handler) {
return element.addEventListener(eventType, function(e) {
var target;
target = e.target;
while (!(!(target instanceof Element) || matches(target, selector))) {
target = target.parentNode;
}
if (target instanceof Element && handler.call(target, e) === false) {
e.preventDefault();
return e.stopPropagation();
}
});
};
}).call(this);
(function() {
var AcceptHeaders, CSRFProtection, createXHR, cspNonce, fire, prepareOptions, processResponse;
cspNonce = Rails.cspNonce, CSRFProtection = Rails.CSRFProtection, fire = Rails.fire;
AcceptHeaders = {
'*': '*/*',
text: 'text/plain',
html: 'text/html',
xml: 'application/xml, text/xml',
json: 'application/json, text/javascript',
script: 'text/javascript, application/javascript, application/ecmascript, application/x-ecmascript'
};
Rails.ajax = function(options) {
var xhr;
options = prepareOptions(options);
xhr = createXHR(options, function() {
var ref, response;
response = processResponse((ref = xhr.response) != null ? ref : xhr.responseText, xhr.getResponseHeader('Content-Type'));
if (Math.floor(xhr.status / 100) === 2) {
if (typeof options.success === "function") {
options.success(response, xhr.statusText, xhr);
}
} else {
if (typeof options.error === "function") {
options.error(response, xhr.statusText, xhr);
}
}
return typeof options.complete === "function" ? options.complete(xhr, xhr.statusText) : void 0;
});
if ((options.beforeSend != null) && !options.beforeSend(xhr, options)) {
return false;
}
if (xhr.readyState === XMLHttpRequest.OPENED) {
return xhr.send(options.data);
}
};
prepareOptions = function(options) {
options.url = options.url || location.href;
options.type = options.type.toUpperCase();
if (options.type === 'GET' && options.data) {
if (options.url.indexOf('?') < 0) {
options.url += '?' + options.data;
} else {
options.url += '&' + options.data;
}
}
if (AcceptHeaders[options.dataType] == null) {
options.dataType = '*';
}
options.accept = AcceptHeaders[options.dataType];
if (options.dataType !== '*') {
options.accept += ', */*; q=0.01';
}
return options;
};
createXHR = function(options, done) {
var xhr;
xhr = new XMLHttpRequest();
xhr.open(options.type, options.url, true);
xhr.setRequestHeader('Accept', options.accept);
if (typeof options.data === 'string') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
}
if (!options.crossDomain) {
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
CSRFProtection(xhr);
}
xhr.withCredentials = !!options.withCredentials;
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
return done(xhr);
}
};
return xhr;
};
processResponse = function(response, type) {
var parser, script;
if (typeof response === 'string' && typeof type === 'string') {
if (type.match(/\bjson\b/)) {
try {
response = JSON.parse(response);
} catch (error) {}
} else if (type.match(/\b(?:java|ecma)script\b/)) {
script = document.createElement('script');
script.setAttribute('nonce', cspNonce());
script.text = response;
document.head.appendChild(script).parentNode.removeChild(script);
} else if (type.match(/\b(xml|html|svg)\b/)) {
parser = new DOMParser();
type = type.replace(/;.+/, '');
try {
response = parser.parseFromString(response, type);
} catch (error) {}
}
}
return response;
};
Rails.href = function(element) {
return element.href;
};
Rails.isCrossDomain = function(url) {
var e, originAnchor, urlAnchor;
originAnchor = document.createElement('a');
originAnchor.href = location.href;
urlAnchor = document.createElement('a');
try {
urlAnchor.href = url;
return !(((!urlAnchor.protocol || urlAnchor.protocol === ':') && !urlAnchor.host) || (originAnchor.protocol + '//' + originAnchor.host === urlAnchor.protocol + '//' + urlAnchor.host));
} catch (error) {
e = error;
return true;
}
};
}).call(this);
(function() {
var matches, toArray;
matches = Rails.matches;
toArray = function(e) {
return Array.prototype.slice.call(e);
};
Rails.serializeElement = function(element, additionalParam) {
var inputs, params;
inputs = [element];
if (matches(element, 'form')) {
inputs = toArray(element.elements);
}
params = [];
inputs.forEach(function(input) {
if (!input.name || input.disabled) {
return;
}
if (matches(input, 'fieldset[disabled] *')) {
return;
}
if (matches(input, 'select')) {
return toArray(input.options).forEach(function(option) {
if (option.selected) {
return params.push({
name: input.name,
value: option.value
});
}
});
} else if (input.checked || ['radio', 'checkbox', 'submit'].indexOf(input.type) === -1) {
return params.push({
name: input.name,
value: input.value
});
}
});
if (additionalParam) {
params.push(additionalParam);
}
return params.map(function(param) {
if (param.name != null) {
return (encodeURIComponent(param.name)) + "=" + (encodeURIComponent(param.value));
} else {
return param;
}
}).join('&');
};
Rails.formElements = function(form, selector) {
if (matches(form, 'form')) {
return toArray(form.elements).filter(function(el) {
return matches(el, selector);
});
} else {
return toArray(form.querySelectorAll(selector));
}
};
}).call(this);
(function() {
var allowAction, fire, stopEverything;
fire = Rails.fire, stopEverything = Rails.stopEverything;
Rails.handleConfirm = function(e) {
if (!allowAction(this)) {
return stopEverything(e);
}
};
Rails.confirm = function(message, element) {
return confirm(message);
};
allowAction = function(element) {
var answer, callback, message;
message = element.getAttribute('data-confirm');
if (!message) {
return true;
}
answer = false;
if (fire(element, 'confirm')) {
try {
answer = Rails.confirm(message, element);
} catch (error) {}
callback = fire(element, 'confirm:complete', [answer]);
}
return answer && callback;
};
}).call(this);
(function() {
var disableFormElement, disableFormElements, disableLinkElement, enableFormElement, enableFormElements, enableLinkElement, formElements, getData, isXhrRedirect, matches, setData, stopEverything;
matches = Rails.matches, getData = Rails.getData, setData = Rails.setData, stopEverything = Rails.stopEverything, formElements = Rails.formElements;
Rails.handleDisabledElement = function(e) {
var element;
element = this;
if (element.disabled) {
return stopEverything(e);
}
};
Rails.enableElement = function(e) {
var element;
if (e instanceof Event) {
if (isXhrRedirect(e)) {
return;
}
element = e.target;
} else {
element = e;
}
if (matches(element, Rails.linkDisableSelector)) {
return enableLinkElement(element);
} else if (matches(element, Rails.buttonDisableSelector) || matches(element, Rails.formEnableSelector)) {
return enableFormElement(element);
} else if (matches(element, Rails.formSubmitSelector)) {
return enableFormElements(element);
}
};
Rails.disableElement = function(e) {
var element;
element = e instanceof Event ? e.target : e;
if (matches(element, Rails.linkDisableSelector)) {
return disableLinkElement(element);
} else if (matches(element, Rails.buttonDisableSelector) || matches(element, Rails.formDisableSelector)) {
return disableFormElement(element);
} else if (matches(element, Rails.formSubmitSelector)) {
return disableFormElements(element);
}
};
disableLinkElement = function(element) {
var replacement;
if (getData(element, 'ujs:disabled')) {
return;
}
replacement = element.getAttribute('data-disable-with');
if (replacement != null) {
setData(element, 'ujs:enable-with', element.innerHTML);
element.innerHTML = replacement;
}
element.addEventListener('click', stopEverything);
return setData(element, 'ujs:disabled', true);
};
enableLinkElement = function(element) {
var originalText;
originalText = getData(element, 'ujs:enable-with');
if (originalText != null) {
element.innerHTML = originalText;
setData(element, 'ujs:enable-with', null);
}
element.removeEventListener('click', stopEverything);
return setData(element, 'ujs:disabled', null);
};
disableFormElements = function(form) {
return formElements(form, Rails.formDisableSelector).forEach(disableFormElement);
};
disableFormElement = function(element) {
var replacement;
if (getData(element, 'ujs:disabled')) {
return;
}
replacement = element.getAttribute('data-disable-with');
if (replacement != null) {
if (matches(element, 'button')) {
setData(element, 'ujs:enable-with', element.innerHTML);
element.innerHTML = replacement;
} else {
setData(element, 'ujs:enable-with', element.value);
element.value = replacement;
}
}
element.disabled = true;
return setData(element, 'ujs:disabled', true);
};
enableFormElements = function(form) {
return formElements(form, Rails.formEnableSelector).forEach(enableFormElement);
};
enableFormElement = function(element) {
var originalText;
originalText = getData(element, 'ujs:enable-with');
if (originalText != null) {
if (matches(element, 'button')) {
element.innerHTML = originalText;
} else {
element.value = originalText;
}
setData(element, 'ujs:enable-with', null);
}
element.disabled = false;
return setData(element, 'ujs:disabled', null);
};
isXhrRedirect = function(event) {
var ref, xhr;
xhr = (ref = event.detail) != null ? ref[0] : void 0;
return (xhr != null ? xhr.getResponseHeader("X-Xhr-Redirect") : void 0) != null;
};
}).call(this);
(function() {
var stopEverything;
stopEverything = Rails.stopEverything;
Rails.handleMethod = function(e) {
var csrfParam, csrfToken, form, formContent, href, link, method;
link = this;
method = link.getAttribute('data-method');
if (!method) {
return;
}
href = Rails.href(link);
csrfToken = Rails.csrfToken();
csrfParam = Rails.csrfParam();
form = document.createElement('form');
formContent = "<input name='_method' value='" + method + "' type='hidden' />";
if ((csrfParam != null) && (csrfToken != null) && !Rails.isCrossDomain(href)) {
formContent += "<input name='" + csrfParam + "' value='" + csrfToken + "' type='hidden' />";
}
formContent += '<input type="submit" />';
form.method = 'post';
form.action = href;
form.target = link.target;
form.innerHTML = formContent;
form.style.display = 'none';
document.body.appendChild(form);
form.querySelector('[type="submit"]').click();
return stopEverything(e);
};
}).call(this);
(function() {
var ajax, fire, getData, isCrossDomain, isRemote, matches, serializeElement, setData, stopEverything,
slice = [].slice;
matches = Rails.matches, getData = Rails.getData, setData = Rails.setData, fire = Rails.fire, stopEverything = Rails.stopEverything, ajax = Rails.ajax, isCrossDomain = Rails.isCrossDomain, serializeElement = Rails.serializeElement;
isRemote = function(element) {
var value;
value = element.getAttribute('data-remote');
return (value != null) && value !== 'false';
};
Rails.handleRemote = function(e) {
var button, data, dataType, element, method, url, withCredentials;
element = this;
if (!isRemote(element)) {
return true;
}
if (!fire(element, 'ajax:before')) {
fire(element, 'ajax:stopped');
return false;
}
withCredentials = element.getAttribute('data-with-credentials');
dataType = element.getAttribute('data-type') || 'script';
if (matches(element, Rails.formSubmitSelector)) {
button = getData(element, 'ujs:submit-button');
method = getData(element, 'ujs:submit-button-formmethod') || element.method;
url = getData(element, 'ujs:submit-button-formaction') || element.getAttribute('action') || location.href;
if (method.toUpperCase() === 'GET') {
url = url.replace(/\?.*$/, '');
}
if (element.enctype === 'multipart/form-data') {
data = new FormData(element);
if (button != null) {
data.append(button.name, button.value);
}
} else {
data = serializeElement(element, button);
}
setData(element, 'ujs:submit-button', null);
setData(element, 'ujs:submit-button-formmethod', null);
setData(element, 'ujs:submit-button-formaction', null);
} else if (matches(element, Rails.buttonClickSelector) || matches(element, Rails.inputChangeSelector)) {
method = element.getAttribute('data-method');
url = element.getAttribute('data-url');
data = serializeElement(element, element.getAttribute('data-params'));
} else {
method = element.getAttribute('data-method');
url = Rails.href(element);
data = element.getAttribute('data-params');
}
ajax({
type: method || 'GET',
url: url,
data: data,
dataType: dataType,
beforeSend: function(xhr, options) {
if (fire(element, 'ajax:beforeSend', [xhr, options])) {
return fire(element, 'ajax:send', [xhr]);
} else {
fire(element, 'ajax:stopped');
return false;
}
},
success: function() {
var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return fire(element, 'ajax:success', args);
},
error: function() {
var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return fire(element, 'ajax:error', args);
},
complete: function() {
var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return fire(element, 'ajax:complete', args);
},
crossDomain: isCrossDomain(url),
withCredentials: (withCredentials != null) && withCredentials !== 'false'
});
return stopEverything(e);
};
Rails.formSubmitButtonClick = function(e) {
var button, form;
button = this;
form = button.form;
if (!form) {
return;
}
if (button.name) {
setData(form, 'ujs:submit-button', {
name: button.name,
value: button.value
});
}
setData(form, 'ujs:formnovalidate-button', button.formNoValidate);
setData(form, 'ujs:submit-button-formaction', button.getAttribute('formaction'));
return setData(form, 'ujs:submit-button-formmethod', button.getAttribute('formmethod'));
};
Rails.preventInsignificantClick = function(e) {
var data, insignificantMetaClick, link, metaClick, method, nonPrimaryMouseClick;
link = this;
method = (link.getAttribute('data-method') || 'GET').toUpperCase();
data = link.getAttribute('data-params');
metaClick = e.metaKey || e.ctrlKey;
insignificantMetaClick = metaClick && method === 'GET' && !data;
nonPrimaryMouseClick = (e.button != null) && e.button !== 0;
if (nonPrimaryMouseClick || insignificantMetaClick) {
return e.stopImmediatePropagation();
}
};
}).call(this);
(function() {
var $, CSRFProtection, delegate, disableElement, enableElement, fire, formSubmitButtonClick, getData, handleConfirm, handleDisabledElement, handleMethod, handleRemote, loadCSPNonce, preventInsignificantClick, refreshCSRFTokens;
fire = Rails.fire, delegate = Rails.delegate, getData = Rails.getData, $ = Rails.$, refreshCSRFTokens = Rails.refreshCSRFTokens, CSRFProtection = Rails.CSRFProtection, loadCSPNonce = Rails.loadCSPNonce, enableElement = Rails.enableElement, disableElement = Rails.disableElement, handleDisabledElement = Rails.handleDisabledElement, handleConfirm = Rails.handleConfirm, preventInsignificantClick = Rails.preventInsignificantClick, handleRemote = Rails.handleRemote, formSubmitButtonClick = Rails.formSubmitButtonClick, handleMethod = Rails.handleMethod;
if ((typeof jQuery !== "undefined" && jQuery !== null) && (jQuery.ajax != null)) {
if (jQuery.rails) {
throw new Error('If you load both jquery_ujs and rails-ujs, use rails-ujs only.');
}
jQuery.rails = Rails;
jQuery.ajaxPrefilter(function(options, originalOptions, xhr) {
if (!options.crossDomain) {
return CSRFProtection(xhr);
}
});
}
Rails.start = function() {
if (window._rails_loaded) {
throw new Error('rails-ujs has already been loaded!');
}
window.addEventListener('pageshow', function() {
$(Rails.formEnableSelector).forEach(function(el) {
if (getData(el, 'ujs:disabled')) {
return enableElement(el);
}
});
return $(Rails.linkDisableSelector).forEach(function(el) {
if (getData(el, 'ujs:disabled')) {
return enableElement(el);
}
});
});
delegate(document, Rails.linkDisableSelector, 'ajax:complete', enableElement);
delegate(document, Rails.linkDisableSelector, 'ajax:stopped', enableElement);
delegate(document, Rails.buttonDisableSelector, 'ajax:complete', enableElement);
delegate(document, Rails.buttonDisableSelector, 'ajax:stopped', enableElement);
delegate(document, Rails.linkClickSelector, 'click', preventInsignificantClick);
delegate(document, Rails.linkClickSelector, 'click', handleDisabledElement);
delegate(document, Rails.linkClickSelector, 'click', handleConfirm);
delegate(document, Rails.linkClickSelector, 'click', disableElement);
delegate(document, Rails.linkClickSelector, 'click', handleRemote);
delegate(document, Rails.linkClickSelector, 'click', handleMethod);
delegate(document, Rails.buttonClickSelector, 'click', preventInsignificantClick);
delegate(document, Rails.buttonClickSelector, 'click', handleDisabledElement);
delegate(document, Rails.buttonClickSelector, 'click', handleConfirm);
delegate(document, Rails.buttonClickSelector, 'click', disableElement);
delegate(document, Rails.buttonClickSelector, 'click', handleRemote);
delegate(document, Rails.inputChangeSelector, 'change', handleDisabledElement);
delegate(document, Rails.inputChangeSelector, 'change', handleConfirm);
delegate(document, Rails.inputChangeSelector, 'change', handleRemote);
delegate(document, Rails.formSubmitSelector, 'submit', handleDisabledElement);
delegate(document, Rails.formSubmitSelector, 'submit', handleConfirm);
delegate(document, Rails.formSubmitSelector, 'submit', handleRemote);
delegate(document, Rails.formSubmitSelector, 'submit', function(e) {
return setTimeout((function() {
return disableElement(e);
}), 13);
});
delegate(document, Rails.formSubmitSelector, 'ajax:send', disableElement);
delegate(document, Rails.formSubmitSelector, 'ajax:complete', enableElement);
delegate(document, Rails.formInputClickSelector, 'click', preventInsignificantClick);
delegate(document, Rails.formInputClickSelector, 'click', handleDisabledElement);
delegate(document, Rails.formInputClickSelector, 'click', handleConfirm);
delegate(document, Rails.formInputClickSelector, 'click', formSubmitButtonClick);
document.addEventListener('DOMContentLoaded', refreshCSRFTokens);
document.addEventListener('DOMContentLoaded', loadCSPNonce);
return window._rails_loaded = true;
};
if (window.Rails === Rails && fire(document, 'rails:attachBindings')) {
Rails.start();
}
}).call(this);
}).call(this);
if ( true && module.exports) {
module.exports = Rails;
} else if (true) {
!(__WEBPACK_AMD_DEFINE_FACTORY__ = (Rails),
__WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
(__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) :
__WEBPACK_AMD_DEFINE_FACTORY__),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
}
}).call(this);
/***/ }),
/***/ "./src/js/app.js":
/*!***********************!*\
!*** ./src/js/app.js ***!
\***********************/
/***/ ((__unused_webpack_module, __unused_webpack_exports, __webpack_require__) => {
/* eslint no-console:0 */
// Rails Unobtrusive JavaScript (UJS) is *required* for links in Lucky that use DELETE, POST and PUT.
// Though it says "Rails" it actually works with any framework.
__webpack_require__(/*! @rails/ujs */ "./node_modules/@rails/ujs/lib/assets/compiled/rails-ujs.js").start(); // Turbolinks is optional. Learn more: https://github.com/turbolinks/turbolinks/
// require("turbolinks").start();
// If using Turbolinks, you can attach events to page load like this:
//
// document.addEventListener("turbolinks:load", function() {
// ...
// })
/***/ }),
/***/ "./src/css/app.scss":
/*!**************************!*\
!*** ./src/css/app.scss ***!
\**************************/
/***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
"use strict";
__webpack_require__.r(__webpack_exports__);
// extracted by mini-css-extract-plugin
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = __webpack_modules__;
/******/
/************************************************************************/
/******/ /* webpack/runtime/chunk loaded */
/******/ (() => {
/******/ var deferred = [];
/******/ __webpack_require__.O = (result, chunkIds, fn, priority) => {
/******/ if(chunkIds) {
/******/ priority = priority || 0;
/******/ for(var i = deferred.length; i > 0 && deferred[i - 1][2] > priority; i--) deferred[i] = deferred[i - 1];
/******/ deferred[i] = [chunkIds, fn, priority];
/******/ return;
/******/ }
/******/ var notFulfilled = Infinity;
/******/ for (var i = 0; i < deferred.length; i++) {
/******/ var [chunkIds, fn, priority] = deferred[i];
/******/ var fulfilled = true;
/******/ for (var j = 0; j < chunkIds.length; j++) {
/******/ if ((priority & 1 === 0 || notFulfilled >= priority) && Object.keys(__webpack_require__.O).every((key) => (__webpack_require__.O[key](chunkIds[j])))) {
/******/ chunkIds.splice(j--, 1);
/******/ } else {
/******/ fulfilled = false;
/******/ if(priority < notFulfilled) notFulfilled = priority;
/******/ }
/******/ }
/******/ if(fulfilled) {
/******/ deferred.splice(i--, 1)
/******/ var r = fn();
/******/ if (r !== undefined) result = r;
/******/ }
/******/ }
/******/ return result;
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/hasOwnProperty shorthand */
/******/ (() => {
/******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
/******/ })();
/******/
/******/ /* webpack/runtime/make namespace object */
/******/ (() => {
/******/ // define __esModule on exports
/******/ __webpack_require__.r = (exports) => {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/ })();
/******/
/******/ /* webpack/runtime/jsonp chunk loading */
/******/ (() => {
/******/ // no baseURI
/******/
/******/ // object to store loaded and loading chunks
/******/ // undefined = chunk not loaded, null = chunk preloaded/prefetched
/******/ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
/******/ var installedChunks = {
/******/ "/js/app": 0,
/******/ "css/app": 0
/******/ };
/******/
/******/ // no chunk on demand loading
/******/
/******/ // no prefetching
/******/
/******/ // no preloaded
/******/
/******/ // no HMR
/******/
/******/ // no HMR manifest
/******/
/******/ __webpack_require__.O.j = (chunkId) => (installedChunks[chunkId] === 0);
/******/
/******/ // install a JSONP callback for chunk loading
/******/ var webpackJsonpCallback = (parentChunkLoadingFunction, data) => {
/******/ var [chunkIds, moreModules, runtime] = data;
/******/ // add "moreModules" to the modules object,
/******/ // then flag all "chunkIds" as loaded and fire callback
/******/ var moduleId, chunkId, i = 0;
/******/ if(chunkIds.some((id) => (installedChunks[id] !== 0))) {
/******/ for(moduleId in moreModules) {
/******/ if(__webpack_require__.o(moreModules, moduleId)) {
/******/ __webpack_require__.m[moduleId] = moreModules[moduleId];
/******/ }
/******/ }
/******/ if(runtime) var result = runtime(__webpack_require__);
/******/ }
/******/ if(parentChunkLoadingFunction) parentChunkLoadingFunction(data);
/******/ for(;i < chunkIds.length; i++) {
/******/ chunkId = chunkIds[i];
/******/ if(__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) {
/******/ installedChunks[chunkId][0]();
/******/ }
/******/ installedChunks[chunkIds[i]] = 0;
/******/ }
/******/ return __webpack_require__.O(result);
/******/ }
/******/
/******/ var chunkLoadingGlobal = self["webpackChunk"] = self["webpackChunk"] || [];
/******/ chunkLoadingGlobal.forEach(webpackJsonpCallback.bind(null, 0));
/******/ chunkLoadingGlobal.push = webpackJsonpCallback.bind(null, chunkLoadingGlobal.push.bind(chunkLoadingGlobal));
/******/ })();
/******/
/************************************************************************/
/******/
/******/ // startup
/******/ // Load entry module and return exports
/******/ // This entry module depends on other loaded chunks and execution need to be delayed
/******/ __webpack_require__.O(undefined, ["css/app"], () => (__webpack_require__("./src/js/app.js")))
/******/ var __webpack_exports__ = __webpack_require__.O(undefined, ["css/app"], () => (__webpack_require__("./src/css/app.scss")))
/******/ __webpack_exports__ = __webpack_require__.O(__webpack_exports__);
/******/
/******/ })()
;

12
public/mix-manifest.json Normal file
View File

@ -0,0 +1,12 @@
{
"/js/app.js": "/js/app.js?id=00118292dfd0fb8a7c26",
"/css/app.css": "/css/app.css?id=c214bf25a7ad355b6c21",
"/css/base.css": "/css/base.css",
"/css/bootstrap.min.css": "/css/bootstrap.min.css",
"/css/bootstrap-theme.min.css": "/css/bootstrap-theme.min.css",
"/css/invert.css": "/css/invert.css",
"/css/font-awesome.min.css": "/css/font-awesome.min.css",
"/js/base.js": "/js/base.js",
"/js/bootstrap.min.js": "/js/bootstrap.min.js",
"/js/jquery-3.2.1.min.js": "/js/jquery-3.2.1.min.js"
}

View File

@ -1,3 +1,4 @@
# http://www.robotstxt.org
# Learn more about robots.txt: https://www.robotstxt.org/robotstxt.html
User-agent: *
# 'Disallow' with an empty value allows all paths to be crawled
Disallow:

View File

@ -0,0 +1,67 @@
#!/usr/bin/env bash
# This file contains a set of functions used as helpers
# for various tasks. Read the examples for each one for
# more information. Feel free to put any additional helper
# functions you may need for your app
# Returns true if the command $1 is not found
# example:
# if command_not_found "yarn"; then
# echo "no yarn"
# fi
command_not_found() {
! command -v $1 > /dev/null
return $?
}
# Returns true if the command $1 is not running
# You must supply the full command to check as an argument
# example:
# if command_not_running "redis-cli ping"; then
# print_error "Redis is not running"
# fi
command_not_running() {
$1
if [ $? -ne 0 ]; then
true
else
false
fi
}
# Returns true if the OS is macOS
# example:
# if is_mac; then
# echo "do mac stuff"
# fi
is_mac() {
if [[ "$OSTYPE" == "darwin"* ]]; then
true
else
false
fi
}
# Returns true if the OS is linux based
# example:
# if is_linux; then
# echo "do linux stuff"
# fi
is_linux() {
if [[ "$OSTYPE" == "linux"* ]]; then
true
else
false
fi
}
# Prints error and exit.
# example:
# print_error "Redis is not running. Run it with some_command"
print_error() {
printf "${BOLD_RED_COLOR}There is a problem with your system setup:\n\n"
printf "${BOLD_RED_COLOR}$1 \n\n" | indent
exit 1
}

View File

@ -0,0 +1,32 @@
#!/usr/bin/env bash
# This file contains a set of functions used to format text,
# and make printing text a little easier. Feel free to put
# any additional functions you need for formatting your shell
# output text.
# Colors
BOLD_RED_COLOR="\e[1m\e[31m"
# Indents the text 2 spaces
# example:
# printf "Hello" | indent
indent() {
while read LINE; do
echo " $LINE" || true
done
}
# Prints out an arrow to your custom notice
# example:
# notice "Installing new magic"
notice() {
printf "\n▸ $1\n"
}
# Prints out a check mark and Done.
# example:
# print_done
print_done() {
printf "✔ Done\n" | indent
}

45
script/setup Executable file
View File

@ -0,0 +1,45 @@
#!/usr/bin/env bash
# Exit if any subcommand fails
set -e
set -o pipefail
source script/helpers/text_helpers
notice "Running System Check"
./script/system_check
print_done
notice "Installing node dependencies"
yarn install --no-progress | indent
notice "Compiling assets"
yarn dev | indent
print_done
notice "Installing shards"
shards install | indent
if [ ! -f ".env" ]; then
notice "No .env found. Creating one."
touch .env
print_done
fi
notice "Creating the database"
lucky db.create | indent
notice "Verifying postgres connection"
lucky db.verify_connection | indent
notice "Migrating the database"
lucky db.migrate | indent
notice "Seeding the database with required and sample records"
lucky db.seed.required_data | indent
lucky db.seed.sample_data | indent
print_done
notice "Run 'lucky dev' to start the app"

42
script/system_check Executable file
View File

@ -0,0 +1,42 @@
#!/usr/bin/env bash
source script/helpers/text_helpers
source script/helpers/function_helpers
# Use this script to check the system for required tools and process that your app needs.
# A few helper functions are provided to make writing bash a little easier. See the
# script/helpers/function_helpers file for more examples.
#
# A few examples you might use here:
# * 'lucky db.verify_connection' to test postgres can be connected
# * Checking that elasticsearch, redis, or postgres is installed and/or booted
# * Note: Booting additional processes for things like mail, background jobs, etc...
# should go in your Procfile.dev.
if command_not_found "yarn"; then
print_error "Yarn is not installed\n See https://yarnpkg.com/lang/en/docs/install/ for install instructions."
fi
# Only if this isn't CI
if [ -z "$CI" ]; then
lucky ensure_process_runner_installed
fi
if command_not_found "createdb"; then
MSG="Please install the postgres CLI tools, then try again."
if is_mac; then
MSG="$MSG\nIf you're using Postgres.app, see https://postgresapp.com/documentation/cli-tools.html."
fi
MSG="$MSG\nSee https://www.postgresql.org/docs/current/tutorial-install.html for install instructions."
print_error "$MSG"
fi
## CUSTOM PRE-BOOT CHECKS ##
# example:
# if command_not_running "redis-cli ping"; then
# print_error "Redis is not running."
# fi

View File

@ -1,38 +1,110 @@
version: 2.0
shards:
authentic:
git: https://github.com/luckyframework/authentic.git
version: 0.8.0
avram:
git: https://github.com/luckyframework/avram.git
version: 0.21.1
backtracer:
git: https://github.com/sija/backtracer.cr.git
version: 1.2.1
bindata:
git: https://github.com/spider-gazelle/bindata.git
version: 1.9.1
carbon:
git: https://github.com/luckyframework/carbon.git
version: 0.2.0
carbon_sendgrid_adapter:
git: https://github.com/luckyframework/carbon_sendgrid_adapter.git
version: 0.1.0
cry:
git: https://github.com/luckyframework/cry.git
version: 0.4.3
crystar:
git: https://github.com/naqvis/crystar.git
version: 0.2.0
db:
git: https://github.com/crystal-lang/crystal-db.git
version: 0.10.1
dexter:
git: https://github.com/luckyframework/dexter.git
version: 0.3.3
exception_page:
git: https://github.com/crystal-loot/exception_page.git
version: 0.2.0
kemal:
git: https://github.com/kemalcr/kemal.git
version: 1.1.0+git.commit.5e2efec0503622267b57d03fe7d5151000d3bf47
future:
git: https://github.com/crystal-community/future.cr.git
version: 1.0.0
kemal-flash:
git: https://github.com/nephos/kemal-flash.git
version: 0.1.0+git.commit.d1ea6ce9caaed840a062e07a9223cc404cf3adc7
habitat:
git: https://github.com/luckyframework/habitat.git
version: 0.4.7
kemal-session:
git: https://github.com/kemalcr/kemal-session.git
version: 1.0.0+git.commit.2ebaf68ed48da763a9cdd0f8dcbc6347981e115d
jwt:
git: https://github.com/crystal-community/jwt.git
version: 1.5.1
kilt:
git: https://github.com/jeromegn/kilt.git
version: 0.6.1
lucky:
git: https://github.com/luckyframework/lucky.git
version: 0.28.0
markd:
git: https://github.com/nephos/markd.git
version: 0.4.1+git.commit.8b67caf4e6ecd89d9dc533187acacf7bc835d05f
lucky_env:
git: https://github.com/luckyframework/lucky_env.git
version: 0.1.4
radix:
git: https://github.com/luislavena/radix.git
version: 0.4.1
lucky_flow:
git: https://github.com/luckyframework/lucky_flow.git
version: 0.7.3
slang:
git: https://github.com/jeromegn/slang.git
version: 1.7.3+git.commit.901df64c9a1c1df91d3acd00762509c9b6d3cfd8
lucky_router:
git: https://github.com/luckyframework/lucky_router.git
version: 0.5.1
lucky_task:
git: https://github.com/luckyframework/lucky_task.git
version: 0.1.0
openssl_ext:
git: https://github.com/spider-gazelle/openssl_ext.git
version: 2.1.5
pg:
git: https://github.com/will/crystal-pg.git
version: 0.24.0
pulsar:
git: https://github.com/luckyframework/pulsar.git
version: 0.2.2
selenium:
git: https://github.com/matthewmcgarvey/selenium.cr.git
version: 0.9.1
shell-table:
git: https://github.com/luckyframework/shell-table.cr.git
version: 0.9.3+git.commit.fefbc8b19d18630660b2653de755217597808b1b
teeplate:
git: https://github.com/luckyframework/teeplate.git
version: 0.8.4
webdrivers:
git: https://github.com/matthewmcgarvey/webdrivers.cr.git
version: 0.4.0
wordsmith:
git: https://github.com/luckyframework/wordsmith.git
version: 0.3.0

View File

@ -1,28 +1,38 @@
name: wikicr
version: 0.2.0
name: kisswiki
version: 0.1.0
authors:
- Arthur Poulet <arthur.poulet@sceptique.eu>
crystal: ~> 1.0.0
targets:
kisswiki:
main: src/kisswiki.cr
license: MIT
crystal: 1.1.1
dependencies:
kemal:
github: kemalcr/kemal
branch: master
kilt:
github: jeromegn/kilt
slang:
github: jeromegn/slang
branch: master
kemal-session:
github: kemalcr/kemal-session
branch: master
kemal-flash:
github: Nephos/kemal-flash
branch: bugfix/update-crystal-json
markd:
github: Nephos/markd
branch: feature-toc-fix
lucky:
github: luckyframework/lucky
version: ~> 0.28.0
authentic:
github: luckyframework/authentic
version: ~> 0.8.0
carbon:
github: luckyframework/carbon
version: ~> 0.2.0
carbon_sendgrid_adapter:
github: luckyframework/carbon_sendgrid_adapter
version: ~> 0.1.0
lucky_env:
github: luckyframework/lucky_env
version: ~> 0.1.3
lucky_task:
github: luckyframework/lucky_task
version: ~> 0.1.0
jwt:
github: crystal-community/jwt
version: ~> 1.5.0
development_dependencies:
lucky_flow:
github: luckyframework/lucky_flow
version: ~> 0.7.3

View File

@ -1,69 +0,0 @@
describe Acl do
it "test the users permissions" do
acls = Acl::Groups.new File.tempfile("spec").to_s
g1 = Acl::Group.new(
name: "user",
default: Acl::Perm::Read,
permissions: {
"/tmp/protected" => Acl::Perm::None,
"/tmp/write/*" => Acl::Perm::Write,
"/match/*" => Acl::Perm::Write,
"/match/not-file" => Acl::Perm::None,
"/match/not-dir/*" => Acl::Perm::None,
})
g2 = Acl::Group.new(
name: "admin",
permissions: {
"/match/*" => Acl::Perm::Read,
},
default: Acl::Perm::Write)
acls.add g1
acls.add g2
u1 = Wikicr::User.new "u1", "", %w(user)
u2 = Wikicr::User.new "u2", "", %w(user admin)
# simple
acls.permitted?(u1, "/", Acl::Perm::Read).should be_true
acls.permitted?(u1, "/tmp", Acl::Perm::Read).should be_true
acls.permitted?(u1, "/tmp", Acl::Perm::Write).should be_false
acls.permitted?(u1, "/tmp/protected", Acl::Perm::Read).should be_false
acls.permitted?(u2, "/tmp/protected", Acl::Perm::Read).should be_true
# matching
acls.permitted?(u1, "/tmp/write/test", Acl::Perm::Read).should be_true
acls.permitted?(u1, "/tmp/write/test", Acl::Perm::Write).should be_true
acls.permitted?(u1, "/match/write-ok", Acl::Perm::Read).should be_true
acls.permitted?(u1, "/match/write-ok", Acl::Perm::Write).should be_true
# TODO: enable those tests
acls.permitted?(u1, "/match/not-file", Acl::Perm::Write).should be_false
acls.permitted?(u1, "/match/not-dir/any", Acl::Perm::Write).should be_false
acls.permitted?(u1, "/match/not-file", Acl::Perm::Read).should be_false
acls.permitted?(u1, "/match/not-dir/any", Acl::Perm::Read).should be_false
end
it "test the paths matching" do
Acl::Path.new("/*").acl_match?("/a/test").should eq(true)
Acl::Path.new("/a*").acl_match?("/a/test").should eq(true)
Acl::Path.new("/a/test*").acl_match?("/a/test").should eq(true)
Acl::Path.new("/a/test*").acl_match?("/a/test/").should eq(true)
Acl::Path.new("/a/test*").acl_match?("/b/test").should eq(false)
Acl::Path.new("/a/test*").acl_match?("/a/other").should eq(false)
end
it "groups having" do
acls = Acl::Groups.new File.tempfile("spec").to_s
acls.add "guest"
acls.add "admin"
acls["guest"]["/*"] = Acl::Perm::Read
acls["guest"]["/write/*"] = Acl::Perm::Write
acls["guest"]["/write/admin"] = Acl::Perm::Read
acls["admin"]["/*"] = Acl::Perm::Write
acls.groups_having_any_access_to("/", Acl::Perm::Read).should eq(["guest", "admin"])
acls.groups_having_any_access_to("/", Acl::Perm::Write).should eq(["admin"])
acls.groups_having_any_access_to("/write", Acl::Perm::Write).should eq(["admin"])
acls.groups_having_any_access_to("/write/anypage", Acl::Perm::Write).should eq(["guest", "admin"])
acls.groups_having_any_access_to("/write/admin", Acl::Perm::Write).should eq(["admin"])
acls.groups_having_direct_access_to("/*", Acl::Perm::Read).should eq(["guest", "admin"])
acls.groups_having_direct_access_to("/*", Acl::Perm::Write).should eq(["admin"])
end
end

0
spec/flows/.keep Normal file
View File

View File

@ -0,0 +1,31 @@
require "../spec_helper"
describe "Authentication flow" do
it "works" do
flow = AuthenticationFlow.new("test@example.com")
flow.sign_up "password"
flow.should_be_signed_in
flow.sign_out
flow.sign_in "wrong-password"
flow.should_have_password_error
flow.sign_in "password"
flow.should_be_signed_in
end
# This is to show you how to sign in as a user during tests.
# Use the `visit` method's `as` option in your tests to sign in as that user.
#
# Feel free to delete this once you have other tests using the 'as' option.
it "allows sign in through backdoor when testing" do
user = UserFactory.create
flow = BaseFlow.new
flow.visit Me::Show, as: user
should_be_signed_in(flow)
end
end
private def should_be_signed_in(flow)
flow.el("@sign-out-button").should be_on_page
end

View File

@ -0,0 +1,18 @@
require "../spec_helper"
describe "Reset password flow" do
it "works" do
user = UserFactory.create
flow = ResetPasswordFlow.new(user)
flow.request_password_reset
flow.should_have_sent_reset_email
flow.reset_password "new-password"
flow.should_be_signed_in
flow.sign_out
flow.sign_in "wrong-password"
flow.should_have_password_error
flow.sign_in "new-password"
flow.should_be_signed_in
end
end

View File

@ -1,114 +0,0 @@
describe Acl::Group do
it "test initialize" do
# First initializer, simple
g1 = Acl::Group.new("name1",
{Acl::Path.new("/") => Acl::Perm::Read},
Acl::Perm::None
)
# First initializer, named arguments
g2 = Acl::Group.new(
name: "name2",
permissions: {Acl::Path.new("/o") => Acl::Perm::Write},
default: Acl::Perm::Read
)
# Sec initializer, simple
g3 = Acl::Group.new("name3",
{"/" => Acl::Perm::Read},
Acl::Perm::None
)
# Sec initializer, named arguments
g4 = Acl::Group.new(
name: "name4",
permissions: {"/o" => Acl::Perm::Write},
default: Acl::Perm::Read
)
g1.name.should eq "name1"
g2.name.should eq "name2"
g3.name.should eq "name3"
g4.name.should eq "name4"
g1.default.should eq Acl::Perm::None
g2.default.should eq Acl::Perm::Read
g3.default.should eq Acl::Perm::None
g4.default.should eq Acl::Perm::Read
end
it "test permitted?" do
g = Acl::Group.new(
name: "guest",
permissions: {
Acl::Path.new("/public*") => Acl::Perm::Write,
Acl::Path.new("/restricted*") => Acl::Perm::Read,
Acl::Path.new("/users*") => Acl::Perm::Read,
Acl::Path.new("/users/guest") => Acl::Perm::Write,
Acl::Path.new("/users/protected/*") => Acl::Perm::None,
},
default: Acl::Perm::None
)
g.permitted?("/", Acl::Perm::Read).should be_false
g.permitted?("/users", Acl::Perm::Read).should be_true
g.permitted?("/users/guest", Acl::Perm::Read).should be_true
g.permitted?("/users/admin", Acl::Perm::Read).should be_true
g.permitted?("/users/guest", Acl::Perm::Write).should be_true
g.permitted?("/users/admin", Acl::Perm::Write).should be_false
g.permitted?("/users/protected/any", Acl::Perm::Read).should be_false
g.permitted?("/public", Acl::Perm::Read).should be_true
g.permitted?("/public", Acl::Perm::Write).should be_true
g.permitted?("/public/some", Acl::Perm::Write).should be_true
g.permitted?("/public/some", Acl::Perm::Write).should be_true
g.permitted?("/publicXXX/some", Acl::Perm::Write).should be_true
end
it "advanced test permitted?" do
g = Acl::Group.new(
name: "guest",
permissions: {
Acl::Path.new("/write/*") => Acl::Perm::Write,
Acl::Path.new("/read/*") => Acl::Perm::Read,
Acl::Path.new("/none/*") => Acl::Perm::None,
Acl::Path.new("/read/none") => Acl::Perm::None,
Acl::Path.new("/write/none") => Acl::Perm::None,
Acl::Path.new("/none/readonly") => Acl::Perm::Read,
Acl::Path.new("/write/readonly") => Acl::Perm::Read,
Acl::Path.new("/read/writeonly") => Acl::Perm::Write,
Acl::Path.new("/none/writeonly") => Acl::Perm::Write,
},
default: Acl::Perm::Read
)
g.permitted?("/", Acl::Perm::Read).should be_true
g.permitted?("/", Acl::Perm::Write).should be_false
g.permitted?("/none/any", Acl::Perm::None).should be_true
g.permitted?("/none/any", Acl::Perm::Read).should be_false
g.permitted?("/read/any", Acl::Perm::Read).should be_true
g.permitted?("/read/any", Acl::Perm::Write).should be_false
g.permitted?("/write/any", Acl::Perm::Write).should be_true
g.permitted?("/read/none", Acl::Perm::Read).should be_false
g.permitted?("/write/none", Acl::Perm::Read).should be_false
g.permitted?("/none/readonly", Acl::Perm::Read).should be_true
g.permitted?("/write/readonly", Acl::Perm::Write).should be_false
g.permitted?("/none/writeonly", Acl::Perm::Write).should be_true
g.permitted?("/read/writeonly", Acl::Perm::Write).should be_true
end
it "test permissions access" do
g = Acl::Group.new(
name: "guest",
permissions: {
"/public*" => Acl::Perm::Write,
"/restricted*" => Acl::Perm::Read,
"/users*" => Acl::Perm::Read,
"/users/guest" => Acl::Perm::Write,
},
default: Acl::Perm::None
)
g["/"]?.should eq nil
g["/"].should eq g.default
# TODO: enable this test after changing the design of operator [] to do not match path
# g["/public"]?.should eq nil
g["/public*"]?.should eq Acl::Perm::Write
g["/"] = Acl::Perm::Read
g["/"]?.should eq Acl::Perm::Read
g.delete("/")
g["/"]?.should eq nil
end
end

View File

@ -1,26 +0,0 @@
describe Wikicr::MarkdPatch do
page = Wikicr::Page.new "", real_url: false
index = Wikicr::Page::Index.new "/tmp/specs.index.yaml"
it "basic markd patching" do
raw = "hello <<test1>>"
html = %Q{<p>hello <a href="/test1" title="test1">test1</a></p>\n}
Wikicr::MarkdPatch.to_html(raw, page, index).should eq(html)
end
it "wiki tag markd patching" do
raw = "hello {{test2}}"
html = %Q{<p>hello <a href="/test2" title="test2">test2</a></p>\n}
Wikicr::MarkdPatch.to_html(raw, page, index).should eq(html)
raw = "hello {{title 2|test2}}"
html = %Q{<p>hello <a href="/test2" title="title 2">title 2</a></p>\n}
Wikicr::MarkdPatch.to_html(raw, page, index).should eq(html)
end
it "section anchors" do
raw = "# titleA\n1234567890\n## titleB"
html = %Q{<h1><a id="anchor-titleA" class="anchor" href="#anchor-titleA"></a>titleA</h1>\n<p>1234567890</p>\n<h2><a id="anchor-titleB" class="anchor" href="#anchor-titleB"></a>titleB</h2>\n}
Wikicr::MarkdPatch.to_html(raw, page, index).should eq(html)
end
end

View File

@ -1,64 +0,0 @@
page = Wikicr::Page.new ""
describe Wikicr::Page::Index do
it "one by title or url" do
index = Wikicr::Page::Index.new(file: "placeholder")
index.entries["page1"] = Wikicr::Page::Index::Entry.new path: "path1", url: "url1", title: "title1"
index.entries["page2"] = Wikicr::Page::Index::Entry.new path: "path2", url: "url2", title: "title2"
index.entries["page3"] = Wikicr::Page::Index::Entry.new path: "path3", url: "url3", title: "Title3"
index.entries["page4"] = Wikicr::Page::Index::Entry.new path: "path4", url: "url4", title: "Title3"
title2 = index.one_by_title_or_url text: "title2", context: page
title2.should eq index.entries["page2"]
url2 = index.one_by_title_or_url text: "url2", context: page
url2.should eq index.entries["page2"]
urlnil = index.one_by_title_or_url text: "urlnil", context: page
index.entries.each { |_, entry| urlnil.should_not eq(entry) }
end
it "all by tags" do
index = Wikicr::Page::Index.new(file: "placeholder")
index.entries["entry1"] = Wikicr::Page::Index::Entry.new(
path: "path 1",
url: "url 1",
title: "title 1",
tags: ["tag1", "tag12", "tag13", "tag14"]
)
index.entries["entry2"] = Wikicr::Page::Index::Entry.new(
path: "path 2",
url: "url 2",
title: "title 2",
tags: ["tag12"]
)
index.entries["entry3"] = Wikicr::Page::Index::Entry.new(
path: "path 3",
url: "url 3",
title: "title 3",
tags: ["tag13", "tag134"]
)
index.entries["entry4"] = Wikicr::Page::Index::Entry.new(
path: "path 4",
url: "url 4",
title: "title 4",
tags: ["tag14", "tag134"]
)
expected = {"entry1" => index.entries["entry1"]}
index.all_by_tags(tags_line: "tag1", context: page).should eq(expected)
expected = {"entry1" => index.entries["entry1"], "entry2" => index.entries["entry2"]}
index.all_by_tags(tags_line: "tag12", context: page).should eq(expected)
expected = {"entry2" => index.entries["entry2"]}
index.all_by_tags(tags_line: "tag12 -tag1", context: page).should eq(expected)
expected = {"entry1" => index.entries["entry1"]}
index.all_by_tags(tags_line: "tag12 +tag13", context: page).should eq(expected)
expected = {"entry1" => index.entries["entry1"], "entry2" => index.entries["entry2"], "entry3" => index.entries["entry3"]}
index.all_by_tags(tags_line: "tag12 tag13", context: page).should eq(expected)
end
end

View File

@ -1,15 +0,0 @@
describe Wikicr::Page do
it "test basic" do
page = Wikicr::Page.new(url: "home", real_url: false, parse_title: false)
page.url.should eq "home"
page.real_url.should eq "/pages/home"
page.path.should eq File.expand_path("data/home.md")
end
it "test another basic" do
page = Wikicr::Page.new(url: "/pages/home", real_url: true, parse_title: false)
page.url.should eq "home"
page.real_url.should eq "/pages/home"
page.path.should eq File.expand_path("data/home.md")
end
end

View File

@ -0,0 +1,17 @@
require "../../../spec_helper"
describe Api::Me::Show do
it "returns the signed in user" do
user = UserFactory.create
response = ApiClient.auth(user).exec(Api::Me::Show)
response.should send_json(200, email: user.email)
end
it "fails if not authenticated" do
response = ApiClient.exec(Api::Me::Show)
response.status_code.should eq(401)
end
end

View File

@ -0,0 +1,33 @@
require "../../../spec_helper"
describe Api::SignIns::Create do
it "returns a token" do
UserToken.stub_token("fake-token") do
user = UserFactory.create
response = ApiClient.exec(Api::SignIns::Create, user: valid_params(user))
response.should send_json(200, token: "fake-token")
end
end
it "returns an error if credentials are invalid" do
user = UserFactory.create
invalid_params = valid_params(user).merge(password: "incorrect")
response = ApiClient.exec(Api::SignIns::Create, user: invalid_params)
response.should send_json(
400,
param: "password",
details: "password is wrong"
)
end
end
private def valid_params(user : User)
{
email: user.email,
password: "password",
}
end

View File

@ -0,0 +1,34 @@
require "../../../spec_helper"
describe Api::SignUps::Create do
it "creates user on sign up" do
UserToken.stub_token("fake-token") do
response = ApiClient.exec(Api::SignUps::Create, user: valid_params)
response.should send_json(200, token: "fake-token")
new_user = UserQuery.first
new_user.email.should eq(valid_params[:email])
end
end
it "returns error for invalid params" do
invalid_params = valid_params.merge(password_confirmation: "wrong")
response = ApiClient.exec(Api::SignUps::Create, user: invalid_params)
UserQuery.new.select_count.should eq(0)
response.should send_json(
400,
param: "password_confirmation",
details: "password_confirmation must match"
)
end
end
private def valid_params
{
email: "test@email.com",
password: "password",
password_confirmation: "password",
}
end

0
spec/setup/.keep Normal file
View File

View File

@ -0,0 +1,3 @@
Spec.before_each do
AppDatabase.truncate
end

View File

@ -0,0 +1,13 @@
# For more detailed documentation, visit
# https://luckyframework.org/guides/testing/html-and-interactivity
LuckyFlow.configure do |settings|
settings.stop_retrying_after = 200.milliseconds
settings.base_uri = Lucky::RouteHelper.settings.base_uri
# # By default, LuckyFlow is set in "headless" mode (no browser window shown).
# # Uncomment this to enable running `LuckyFlow` in a Google Chrome window instead.
# # Be sure to disable for CI.
# settings.driver = LuckyFlow::Drivers::Chrome
end
Spec.before_each { LuckyFlow::Server::INSTANCE.reset }

View File

@ -0,0 +1,3 @@
Spec.before_each do
Carbon::DevAdapter.reset
end

View File

@ -0,0 +1,2 @@
Db::Create.new(quiet: true).call
Db::Migrate.new(quiet: true).call

View File

@ -0,0 +1,10 @@
app_server = AppServer.new
spawn do
app_server.listen
end
Spec.after_suite do
LuckyFlow.shutdown
app_server.close
end

View File

@ -1,10 +1,22 @@
ENV["LUCKY_ENV"] = "test"
ENV["DEV_PORT"] = "5001"
require "spec"
require "lucky_flow"
require "../src/app"
require "./support/flows/base_flow"
require "./support/**"
require "../db/migrations/**"
require "../src/lib/lockable"
require "../src/lib/options"
# Add/modify files in spec/setup to start/configure programs or run hooks
#
# By default there are scripts for setting up and cleaning the database,
# configuring LuckyFlow, starting the app server, etc.
require "./setup/**"
require "../src/lib/file_tree"
require "../src/lib/acl"
require "../src/lib/page"
require "../src/lib/wikimd/**"
require "../src/lib/users/**"
include Carbon::Expectations
include Lucky::RequestExpectations
include LuckyFlow::Expectations
Avram::Migrator::Runner.new.ensure_migrated!
Avram::SchemaEnforcer.ensure_correct_column_mappings!
Habitat.raise_if_missing_settings!

0
spec/support/.keep Normal file
View File

View File

@ -0,0 +1,10 @@
class ApiClient < Lucky::BaseHTTPClient
def initialize
super
headers("Content-Type": "application/json")
end
def self.auth(user : User)
new.headers("Authorization": UserToken.generate(user))
end
end

View File

View File

@ -0,0 +1,6 @@
class UserFactory < Avram::Factory
def initialize
email "#{sequence("test-email")}@example.com"
encrypted_password Authentic.generate_encrypted_password("password")
end
end

View File

@ -0,0 +1,40 @@
class AuthenticationFlow < BaseFlow
private getter email
def initialize(@email : String)
end
def sign_up(password)
visit SignUps::New
fill_form SignUpUser,
email: email,
password: password,
password_confirmation: password
click "@sign-up-button"
end
def sign_out
visit Me::Show
sign_out_button.click
end
def sign_in(password)
visit SignIns::New
fill_form SignInUser,
email: email,
password: password
click "@sign-in-button"
end
def should_be_signed_in
sign_out_button.should be_on_page
end
def should_have_password_error
el("body", text: "Password is wrong").should be_on_page
end
private def sign_out_button
el("@sign-out-button")
end
end

View File

@ -0,0 +1,3 @@
# Add methods that all or most Flows need to share
class BaseFlow < LuckyFlow
end

View File

@ -0,0 +1,42 @@
class ResetPasswordFlow < BaseFlow
private getter user, authentication_flow
delegate sign_in, sign_out, should_have_password_error, should_be_signed_in,
to: authentication_flow
delegate email, to: user
def initialize(@user : User)
@authentication_flow = AuthenticationFlow.new(user.email)
end
def request_password_reset
with_fake_token do
visit PasswordResetRequests::New
fill_form RequestPasswordReset,
email: email
click "@request-password-reset-button"
end
end
def should_have_sent_reset_email
with_fake_token do
user = UserQuery.new.email(email).first
PasswordResetRequestEmail.new(user).should be_delivered
end
end
def reset_password(password)
user = UserQuery.new.email(email).first
token = Authentic.generate_password_reset_token(user)
visit PasswordResets::New.with(user.id, token)
fill_form ResetPassword,
password: password,
password_confirmation: password
click "@update-password-button"
end
private def with_fake_token
PasswordResetRequestEmail.temp_config(stubbed_token: "fake") do
yield
end
end
end

View File

@ -1,6 +0,0 @@
require "./spec_helper"
require "./acl_spec"
require "./group_spec"
require "./markdown_spec"
require "./page_spec"

View File

@ -0,0 +1,5 @@
class Api::Me::Show < ApiAction
get "/api/me" do
json UserSerializer.new(current_user)
end
end

View File

@ -0,0 +1,13 @@
class Api::SignIns::Create < ApiAction
include Api::Auth::SkipRequireAuthToken
post "/api/sign_ins" do
SignInUser.run(params) do |operation, user|
if user
json({token: UserToken.generate(user)})
else
raise Avram::InvalidOperationError.new(operation)
end
end
end
end

View File

@ -0,0 +1,8 @@
class Api::SignUps::Create < ApiAction
include Api::Auth::SkipRequireAuthToken
post "/api/sign_ups" do
user = SignUpUser.create!(params)
json({token: UserToken.generate(user)})
end
end

14
src/actions/api_action.cr Normal file
View File

@ -0,0 +1,14 @@
# Include modules and add methods that are for all API requests
abstract class ApiAction < Lucky::Action
# APIs typically do not need to send cookie/session data.
# Remove this line if you want to send cookies in the response header.
disable_cookies
accepted_formats [:json]
include Api::Auth::Helpers
# By default all actions require sign in.
# Add 'include Api::Auth::SkipRequireAuthToken' to your actions to allow all requests.
include Api::Auth::RequireAuthToken
include Lucky::EnforceUnderscoredRoute
end

View File

@ -0,0 +1,41 @@
abstract class BrowserAction < Lucky::Action
include Lucky::ProtectFromForgery
include Lucky::EnforceUnderscoredRoute
# This module disables Google FLoC by setting the
# [Permissions-Policy](https://github.com/WICG/floc) HTTP header to `interest-cohort=()`.
#
# This header is a part of Google's Federated Learning of Cohorts (FLoC) which is used
# to track browsing history instead of using 3rd-party cookies.
#
# Remove this include if you want to use the FLoC tracking.
include Lucky::SecureHeaders::DisableFLoC
accepted_formats [:html, :json], default: :html
# This module provides current_user, sign_in, and sign_out methods
include Authentic::ActionHelpers(User)
# When testing you can skip normal sign in by using `visit` with the `as` param
#
# flow.visit Me::Show, as: UserFactory.create
include Auth::TestBackdoor
# By default all actions that inherit 'BrowserAction' require sign in.
#
# You can remove the 'include Auth::RequireSignIn' below to allow anyone to
# access actions that inherit from 'BrowserAction' or you can
# 'include Auth::AllowGuests' in individual actions to skip sign in.
include Auth::RequireSignIn
# `expose` means that `current_user` will be passed to pages automatically.
#
# In default Lucky apps, the `MainLayout` declares it `needs current_user : User`
# so that any page that inherits from MainLayout can use the `current_user`
expose current_user
# This method tells Authentic how to find the current user
private def find_current_user(id) : User?
UserQuery.new.id(id).first?
end
end

View File

@ -0,0 +1,63 @@
# This class handles error responses and reporting.
#
# https://luckyframework.org/guides/http-and-routing/error-handling
class Errors::Show < Lucky::ErrorAction
DEFAULT_MESSAGE = "Something went wrong."
default_format :html
dont_report [Lucky::RouteNotFoundError, Avram::RecordNotFoundError]
def render(error : Lucky::RouteNotFoundError | Avram::RecordNotFoundError)
if html?
error_html "Sorry, we couldn't find that page.", status: 404
else
error_json "Not found", status: 404
end
end
# When the request is JSON and an InvalidOperationError is raised, show a
# helpful error with the param that is invalid, and what was wrong with it.
def render(error : Avram::InvalidOperationError)
if html?
error_html DEFAULT_MESSAGE, status: 500
else
error_json \
message: error.renderable_message,
details: error.renderable_details,
param: error.invalid_attribute_name,
status: 400
end
end
# Always keep this below other 'render' methods or it may override your
# custom 'render' methods.
def render(error : Lucky::RenderableError)
if html?
error_html DEFAULT_MESSAGE, status: error.renderable_status
else
error_json error.renderable_message, status: error.renderable_status
end
end
# If none of the 'render' methods return a response for the raised Exception,
# Lucky will use this method.
def default_render(error : Exception) : Lucky::Response
if html?
error_html DEFAULT_MESSAGE, status: 500
else
error_json DEFAULT_MESSAGE, status: 500
end
end
private def error_html(message : String, status : Int)
context.response.status_code = status
html Errors::ShowPage, message: message, status: status
end
private def error_json(message : String, status : Int, details = nil, param = nil)
json ErrorSerializer.new(message: message, details: details, param: param), status: status
end
private def report(error : Exception) : Nil
# Send to Rollbar, send an email, etc.
end
end

18
src/actions/home/index.cr Normal file
View File

@ -0,0 +1,18 @@
class Home::Index < BrowserAction
include Auth::AllowGuests
get "/" do
if current_user?
redirect Me::Show
else
# When you're ready change this line to:
#
# redirect SignIns::New
#
# Or maybe show signed out users a marketing page:
#
# html Marketing::IndexPage
html Lucky::WelcomePage
end
end
end

5
src/actions/me/show.cr Normal file
View File

@ -0,0 +1,5 @@
class Me::Show < BrowserAction
get "/me" do
html ShowPage
end
end

0
src/actions/mixins/.keep Normal file
View File

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