diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 000000000..a5156fbfa
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,10 @@
+static/* linguist-vendored
+config/* linguist-vendored
+data/* linguist-vendored
+files/* linguist-vendored
+fileslocal/* linguist-vendored
+log/* linguist-vendored
+nimcache/* linguist-vendored
+private/* linguist-vendored
+public/* linguist-vendored
+plugins/* linguist-vendored
diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
new file mode 100644
index 000000000..497791eea
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE.md
@@ -0,0 +1,69 @@
+
+### Bug Short Description:
+
+Short concise description of the problem. No narrative or conversational language.
+
+
+
+### Operating System:
+*Choose 1 or more. Mark the checkbox it with an `X`.*
+- [ ] GNU/Linux.
+- [ ] Apple Os X.
+- [ ] Microsoft Windows.
+- [ ] Other or Unknown or Unsupported.
+
+
+
+### Bug Severity:
+*Choose only 1. Mark the checkbox it with an `X`.*
+- [ ] Low, Minor, Aesthetic, Small, Detail, Trivial.
+- [ ] Medium, Normal, Standard.
+- [ ] High, Important, Major.
+- [ ] Critical, Catastrophic, Epic Fail.
+- [ ] Other or Unknown.
+
+
+
+## Version
+*Semantic Version of this software the Bug Reproduces into. Type in the Version Number*
+```
+ 0.0.0
+```
+
+
+
+### Workarounds:
+*Any Workarounds you have tried. Choose none or one or more. Mark the checkbox it with an `X`.*
+- [ ] Uninstalling and Reinstalling, Reloading, Rebooting, Restarting, etc.
+- [ ] Run as Administrator, Run as root, Run as different user, etc.
+- [ ] Run on another computer, Run on a Virtual Machine, Run on another OS, etc.
+
+
+
+### Steps to reproduce:
+- 1.
+- 2.
+- 3.
+- 4.
+- 5.
+
+
+
+### Actual Output:
+```
+PASTE ACTUAL OUTPUT CODE HERE, TRACEBACK, CRASH, CORE DUMP, ERROR, ETC, IF ANY.
+```
+
+
+
+### Expected Output:
+```
+PASTE EXPECTED OUTPUT CODE HERE, WHEN THE SOFTWARE WORKS OK, ETC, IF ANY.
+```
+
+
+
+### Screenshots or Images
+*(if applicable)*
+
+
diff --git a/.github/PULL REQUEST_TEMPLATE.md b/.github/PULL REQUEST_TEMPLATE.md
new file mode 100644
index 000000000..67d7200b3
--- /dev/null
+++ b/.github/PULL REQUEST_TEMPLATE.md
@@ -0,0 +1,40 @@
+
+### Pull Request Short Description:
+
+Short concise description of the problem. No narrative or conversational language.
+
+
+
+### What does this implement/fix/improves?
+
+Explain your changes. No narrative or conversational language.
+
+
+
+### Does this close any currently open issues?
+*Choose only 1. Mark the checkbox it with an `X`.*
+- [ ] **No**, this does Not close any currently open issues.
+- [ ] **Yes**, this close the currently open issue number:
+
+
+
+### Checklist:
+*Choose 1 or more. Mark the checkbox it with an `X`.*
+- [ ] Is in Sync with latest origin master branch.
+- [ ] Added Examples.
+- [ ] Added Unit Tests or Integration Tests or Automation Tests.
+- [ ] Added Documentation or DocStrings or code comments.
+- [ ] I ran the code locally, it works on my machine.
+
+
+
+### Any other comments?
+
+Short comments. No narrative or conversational language.
+
+
+
+### Screenshots or Images
+*(if applicable)*
+
+
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 31f689196..639f68cf5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,16 +1,41 @@
-## v4.0.12
+## v5.0.0
### Changes
- Add Server Info page for Admins, it displays runtime server stats
- Add Force Server Restart for Admins, restart on 1 second
- Update Bulma version
- Filter avatar image file format, because Crop thingy get buggy/slow with GIF
+- 2 Factor Authentication
- Add MimeType, Size, CheckSum to Files page, useful for UI/UX building
- Add button to Copy all the Logs content on one click on Logs page
- Add Dockerfile to the repo
+- Add Vagrantfile to the repo
+- Add Service file to the repo
- Update Readme
- Update Nimble file
- First release of 2019
+### Breaking changes
+- New column in `person` table: `twofa`:
+```sql
+ALTER TABLE person ADD COLUMN twofa varchar(60);
+```
+- New column in `blog` table: `viewCount`:
+```sql
+ALTER TABLE blog ADD COLUMN viewCount INTEGER default 1;
+```
+- New column in `blog` table: `pubDate`:
+```sql
+ALTER TABLE blog ADD COLUMN pubDate VARCHAR(100);
+```
+- New table: `files`:
+```nim
+./nimwc --newdb
+```
+- Dependency [firejail](https://github.com/juancarlospaco/nim-firejail), install firejail on your system
+- Dependency [webp](https://github.com/juancarlospaco/nim-webp-tools), install libwebp on your system
+
+
+
## v4.0.11
### Changes
- Remove min and max length on meta text
diff --git a/Dockerfile b/Dockerfile
deleted file mode 100644
index 418f8c4d8..000000000
--- a/Dockerfile
+++ /dev/null
@@ -1,4 +0,0 @@
-FROM nimlang/nim
-RUN nimble -y refresh
-RUN nimble -y install nimwc@4.0.12
-RUN rm -rf /var/lib/apt/lists/* /var/tmp/* /tmp/nimblecache/ /tmp/*
diff --git a/LICENSE b/LICENSE
index 94a9ed024..f17901554 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,674 +1,100 @@
- GNU GENERAL PUBLIC LICENSE
- Version 3, 29 June 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc.
- 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.
-
-
- Copyright (C)
-
- 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 .
-
-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:
-
- Copyright (C)
- 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
-.
-
- 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
-.
+Peer Production License (PPL)
+
+THE WORK (AS DEFINED BELOW) IS PROVIDED UNDER THE TERMS OF THIS COPYFARLEFT PUBLIC LICENSE ("LICENSE").
+THE WORK IS PROTECTED BY COPYRIGHT AND ALL OTHER APPLICABLE LAWS.
+ANY USE OF THE WORK OTHER THAN AS AUTHORIZED UNDER THIS LICENSE OR COPYRIGHT LAW IS PROHIBITED.
+
+BY EXERCISING ANY RIGHTS TO THE WORK PROVIDED IN THIS LICENSE, YOU AGREE TO BE BOUND BY THE TERMS OF THIS LICENSE.
+TO THE EXTENT THIS LICENSE MAY BE CONSIDERED TO BE A CONTRACT, THE LICENSOR GRANTS YOU THE RIGHTS CONTAINED HERE IN AS CONSIDERATION FOR ACCEPTING THE TERMS AND CONDITIONS OF THIS LICENSE AND FOR AGREEING TO BE BOUND BY THE TERMS AND CONDITIONS OF THIS LICENSE.
+
+1. Definitions
+
+a. "Adaptation" means a Work based upon the Work, or upon the Work and other pre-existing Works, such as a translation, adaptation, derivative Work, arrangement of music or other alterations of a literary or artistic Work, or phonogram or performance and includes cinematographic Adaptations or any other form in which the Work may be recast, transformed, or adapted including in any form recognizably derived from the original, except that a Work that constitutes a Collection will not be considered an adaptation for the purpose of this license. For the avoidance of doubt, where the Work is a musical Work, performance or phonogram, the synchronization of the Work in timed-relation with a moving image ("synching") will be considered an adaptation for the purpose of this license.
+
+b. "Collection" means a Collection of literary or artistic Works, such as encyclopedias and anthologies, or performances, phonograms or broadcasts, or other Works or subject matter other than Works listed in Section 1(f) below, which, by reason of the selection and arrangement of their contents, constitute intellectual creations, in which the Work is included in its entirety in unmodified form along with one or more other contributions, each constituting separate and independent Works in themselves, which together are assembled into a collective whole. A Work that constitutes a Collection will not be considered an adaptation (as defined above) for the purposes of this license.
+
+c. "Distribute" means to make available to the public the original and copies of the Work or adaptation, as appropriate, through sale, gift or any other transfer of possession or ownership.
+
+d. "Licensor" means the individual, individuals, entity or entities that offer(s) the Work under the terms of this license.
+
+e. "Original Author" means, in the case of a literary or artistic Work, the individual, in dividuals, entity or entities who created the Work or if no individual or entity can be identified, the publisher; and in addition (i) in the case of a performance the actors, singers, musicians, dancers, and other persons who act, sing, deliver, declaim, play in, interpret or otherwise perform literary or artistic Works or expressions of folklore; (ii) in the case of a phonogram the producer being the person or legal entity who first fixes the sounds of a performance or other sounds; and, (iii) in the case of broadcasts, the organization that transmits the broadcast.
+
+f. "Work" means the literary and/or artistic Work offered under the terms of this license including without limitation any production in the literary, scientific and artistic domain, whatever may be the mode or form of its expression including digital form, such as a book, pamphlet and other writing; a lecture, address, sermon or other Work of the same nature; a dramatic or dramatico-musical Work; a choreographic Work or entertainment in dumb show; a musical composition with or without words; a cinematographic Work to which are assimilated Works expressed by a process analogous to cinematography; a Work of drawing, painting, architecture, sculpture, engraving or lithography; a photographic Work to which are assimilated Works expressed by a pro cess analogous to photography; a Work of applied art; an illustration, map, plan, sketch or three-dimensional Work relative to geography, topography, architecture or science; a performance; a broadcast; a phonogram; a compilation of data to the extent it is protected as a copyrightable Work; or a Work performed by a variety or circus performer to the extent it is not otherwise considered a literary or artistic Work.
+
+g. "You" means an individual or entity exercising rights under this license who has not previously violated the terms of this license with respect to the Work, or who has received express permission from the Licensor to exercise rights under this license despite a previous violation.
+
+h. "Publicly Perform" means to perform public recitations of the Work and to communicate to the public those public recitations, by any means or process, including by wire or wireless means or public digital performances; to make available to the public Works in such a way that members of the public may access these Works from a place and at a place individually chosen by them; to perform the Work to the public by any means or process and the communication to the public of the performances of the Work, including by public digital performance; to broadcast and rebroadcast the Work by any means including signs, sounds or images.
+
+i. "Reproduce" means to make copies of the Work by any means including without limitation by sound or visual recordings and the right of fixation and reproducing fixations of the Work, including storage of a protected performance or phonogram in digital form or other electronic medium.
+
+2. FAIR DEALING RIGHTS
+
+Nothing in this license is intended to reduce, limit, or restrict any uses free from copyright or rights arising from limitations or exceptions that are provided for in connection with the copyright protection under copyright law or other applicable laws.
+
+3. LICENSE GRANT
+
+Subject to the terms and conditions of this license, Licensor hereby grants You a worldwide, royalty-free, non-exclusive, perpetual (for the duration of the applicable copyright) license to exercise the rights in the Work as stated below:
+
+a. To Reproduce the Work, to incorporate the Work into one or more Collections, and to Reproduce the Work as incorporated in the Collections;
+
+b. To create and Reproduce Adaptations provided that any such adaptation, including any translation in any medium, takes reasonable steps to clearly label, demarcate or otherwise identify that changes were made to the original Work. For example, a translation could be marked "the original Work was translated from English to Spanish," or a modification could indicate "the original Work has been modified.";
+
+c. To Distribute and Publicly Perform the Work including as incorporated in Collections; and,
+
+d. To Distribute and Publicly Perform Adaptations. The above rights may be exercised in all media and formats whether now known or hereafter devised. The above rights include the right to make such modifications as are technically necessary to exercise the rights in other media and formats. Subject to Section 8(f), all rights not expressly granted by Licensor are hereby reserved, including but not limited to the rights set forth in Section 4(f).
+
+4. RESTRICTIONS
+
+The license granted in Section 3 above is expressly made subject to and limited by the following restrictions:
+
+a. You may distribute or publicly perform the Work only under the terms of this license. You must include a copy of, or the uniform resource identifier (uri) for, this license with every copy of the Work You distribute or publicly perform. You may not offer or impose any terms on the Work that restrict the terms of this license or the ability of the recipient of the Work to exercise the rights granted to that recipient under the terms of the license. You may not sublicense the Work. You must keep intact all notices that refer to this license and to the disclaimer of warranties with every copy of the Work You distribute or publicly perform. When You distribute or publicly perform the Work, You may not impose any effective technological measures on the Work that restrict the ability of a recipient of the Work from You to exercise the rights granted to that recipient under the terms of the license. This Section 4(a) applies to the Work as incorporated in a Collection, but this does not require the Collection apart from the Work itself to be made subject to the terms of this license. If You create a Collection, upon notice from any Licensor You must, to the extent practicable, remove from the Collection any credit as required by Section 4(d), as requested. If You create an adaptation, upon notice from any Licensor You must, to the extent practicable, remove from the adaptation any credit as required by Section 4(d), as requested.
+
+b. Subject to the exception in Section 4(c), You may not exercise any of the rights granted to You in Section 3 above in any manner that is primarily intended for or directed to ward commercial advantage or private monetary compensation. The exchange of the Work for other copyrighted Works by means of digital filesharing or otherwise shall not be considered to be intended for or directed toward commercial advantage or private monetary compensation, provided there is no payment of any monetary compensation in connection with the exchange of copyrighted Works.
+
+c. You may exercise the rights granted in Section 3 for commercial purposes only if:
+
+i. You are a Worker-owned business or Worker-owned collective; and
+
+ii. All financial gain, surplus, profits and benefits produced by the business or collective are distributed among the Workerowners
+
+d. Any use by a business that is privately owned and managed, and that seeks to generate profit from the labor of employees paid by salary or other wages, is not permitted under this license.
+
+e. If You distribute, or publicly perform the Work or any Adaptations or Collections, You must, unless a request has been made pursuant to Section 4(a), keep intact all copyright notices for the Work and provide, reasonable to the medium or means You are utilizing: (i) the name of the Original Author (or pseudonym, if applicable) if supplied, and/or if the Original Author and/or Licensor designate another party or parties (e.g., a sponsor institute, publishing entity, journal) for attribution ("attribution parties") in Licensor's copyright notice, terms of service or by other reasonable means, the name of such party or parties; (ii) the title of the Work if supplied; (iii) to the extent reason ably practicable, the uri, if any, that Licensor specifies to be associated with the Work, unless such uri does not refer to the copyright notice or licensing information for the Work; and, (iv) consistent with Section 3(b), in the case of an adaptation, a credit identifying the use of the Work in the adaptation (e.g., "french translation of the Work by Original Author," or "Screenplay based on original Work by Original Author"). The credit required by this Section 4(d) may be implemented in any reasonable manner; provided, however, that in the case of a adaptation or Collection, at a minimum such credit will appear, if a credit for all contributing authors of the adaptation or Collection appears, then as part of these credits and in a manner at least as prominent as the credits for the other contributing authors. For the avoidance of doubt, You may only use the credit required by this Section for the purpose of attribution in the manner set out above and, by exercising Your rights under this license, You may not implicitly or explicitly assert or imply any connection with, sponsorship or endorsement by the Original Author, Licensor and/or attribution parties, as appropriate, of You or Your use of the Work, without the separate, express prior written permission of the Original Author, Licensor and/or attribution parties.
+
+f. For the avoidance of doubt:
+
+i. Non-waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can not be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this license;
+
+ii. Waivable Compulsory License Schemes. In those jurisdictions in which the right to collect royalties through any statutory or compulsory licensing scheme can be waived, the Licensor reserves the exclusive right to collect such royalties for any exercise by You of the rights granted under this license if Your exercise of such rights is for a purpose or use which is otherwise than noncommercial as permitted under Section 4(b) and otherwise waives the right to collect royalties through any statutory or compulsory licensing scheme; and,
+
+iii. Voluntary License Schemes. The Licensor reserves the right to collect royalties, whether individually or, in the event that the Licensor is a member of a collecting society that administers voluntary licensing schemes, via that society, from any exercise by You of the rights granted under this license that is for a purpose or use which is otherwise than noncommercial as permitted under Section 4(b).
+
+g. Except as otherwise agreed in writing by the Licensor or as may be otherwise permitted by applicable law, if You Reproduce, distribute or publicly perform the Work either by itself or as part of any Adaptations or Collections, You must not distort, mutilate, modify or take other derogatory action in relation to the Work which would be prejudicial to the Original Author's honor or reputation. Licensor agrees that in those jurisdictions (e.g. Japan), in which any exercise of the right granted in Section 3(b) of this license (the right to make Adaptations) would be deemed to be a distortion, mutilation, modification or other derogatory action prejudicial to the Original Author's honor and reputation, the Licensor will waive or not assert, as appropriate, this Section, to the fullest extent permitted by the applicable national law, to enable You to reasonably exercise Your right under Section 3(b) of this license (right to make Adaptations) but not otherwise.
+
+5. REPRESENTATIONS, WARRANTIES AND DISCLAIMER
+
+UNLESS OTHERWISE MUTUALLY AGREED TO BY THE PARTIES IN WRITING, LICENSOR OFFERS THE WORK AS IS AND MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND CONCERNING THE WORK, EXPRESS, IMPLIED, STATUTORY OR OTHERWISE, INCLUDING, WITHOUT LIMITATION, WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, ACCURACY, OR THE PRESENCE OF ABSENCE OF ERRORS, WHETHER OR NOT DISCOVERABLE. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OF IMPLIED WARRANTIES, SO SUCH EXCLUSION MAY NOT APPLY TO YOU.
+
+6. LIMITATION ON LIABILITY
+
+EXCEPT TO THE EXTENT REQUIRED BY APPLICABLE LAW, IN NO EVENT WILL LICENSOR BE LIABLE TO YOU ON ANY LEGAL THEORY FOR ANY SPECIAL, INCIDENTAL, CONSEQUENTIAL, PUNITIVE OR EXEMPLARY DAMAGES ARISING OUT OF THIS LICENSE OR THE USE OF THE WORK, EVEN IF LICENSOR HAS BEEN ADVISED OF THE POS SIBILITY OF SUCH DAMAGES.
+
+7. TERMINATION
+
+a. This license and the rights granted hereunder will terminate automatically upon any breach by You of the terms of this license. Individuals or entities who have received Adaptations or Collections from You under this license, however, will not have their licenses terminated provided such individuals or entities remain in full compliance with those licenses. Sections 1, 2, 5, 6, 7, and 8 will survive any termination of this license.
+
+b. Subject to the above terms and conditions, the license granted here is perpetual (for the duration of the applicable copyright in the Work). Notwithstanding the above, Licensor reserves the right to release the Work under different license terms or to stop distributing the Work at any time; provided, however that any such election will not serve to withdraw this license (or any other license that has been, or is required to be, granted under the terms of this license), and this license will continue in full force and effect unless terminated as stated above.
+
+8. MISCELLANEOUS
+
+a. Each time You distribute or publicly perform the Work or a Collection, the Licensor offers to the recipient a license to the Work on the same terms and conditions as the license granted to You under this license.
+
+b. Each time You distribute or publicly perform an adaptation, Licensor offers to the recipient a license to the original Work on the same terms and conditions as the license granted to You under this license.
+
+c. If any provision of this license is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this license, and without further action by the parties to this agreement, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable.
+
+d. No term or provision of this license shall be deemed waived and no breach consented to unless such waiver or consent shall be in writing and signed by the party to be charged with such waiver or consent.
+
+e. This license constitutes the entire agreement between the parties with respect to the Work licensed here. There are no understandings, agreements or representations with respect to the Work not specified here. Licensor shall not be bound by any additional provisions that may appear in any communication from You. This license may not be modified without the mutual written agreement of the Licensor and You.
+
+f. The rights granted under, and the subject matter referenced, in this license were draft ed utilizing the terminology of the berne convention for the protection of literary and artistic Works (as amended on september 28, 1979), the rome convention of 1961, the wipo copyright treaty of 1996, the wipo performances and phonograms treaty of 1996 and the universal copyright convention (as revised on july 24, 1971). These rights and subject matter take effect in the relevant jurisdiction in which the license terms are sought to be enforced according to the corresponding provisions of the implemen tation of those treaty provisions in the applicable national law. If the standard suite of rights granted under applicable copyright law includes additional rights not granted under this license, such additional rights are deemed to be included in the license; this license is not intended to restrict the license of any rights under applicable law.
diff --git a/README.md b/README.md
index 3fba2d241..ad02863f4 100644
--- a/README.md
+++ b/README.md
@@ -5,40 +5,103 @@ A quick website tool. Run the nim file and access your webpage. Website: [https:
-## Main features:
-
-- Webserver hosting your page on 127.0.0.1:7000
-- Edit your pages with Summernote, raw HTML (CodeMirror) or drag'n'drop with GrapesJS
-- Blog - add and edit blog posts
-- Pages - add and edit pages
-- Custom head, navbar and footer
-- Custom title, meta description and keywords for each page
-- Edit core or custom js- and css-files
-- Upload files (private or public)
+# Features
+
+## Blogs and pages
+- 1 Click Blogging posts directly from browser.
+- 1 Click Static web pages directly from browser.
+- WYSIWYG & Drag'n'Drop Editors with [Summernote](https://summernote.org), [CodeMirror](https://codemirror.net) or [GrapesJS](https://grapesjs.com).
+- Custom title, meta description and keywords for each page, SEO friendly.
+- Custom head, navbar and footer, no hardcoded watermarks, links or logos.
+- Upload files and images (private or public) directly from browser.
+- 1 language for the whole stack, including high performance modules, scripting, devops, deploy, from WebAssembly to Assembly.
+
+## Security
+- Self-Firejailing Web Framework (It Firejails itself) Best Linux Security integrated on the Core.
+- 2 Factor Athentication TOTP
+- ReCAPTCHA
+- HoneyPot-Field
+- BCrypt+Salt password hashing
+- SQL Type-checked and Query-checked at compile-time, no SQL injections.
+- Multiple users with different ranks, role based access control.
+- Admin can choose how much CPU & RAM NimWC can use from the Admin Dashboard.
+- [We recommend FreeOTP 2 Factor Athentication App because is Open Source.](https://freeotp.github.io)
+
+## Configuration
+- Edit core or custom JS and CSS directly from browser, UI/UX Designer friendly.
- Log Viewer directly from browser.
- Auto-Rotating file Logger.
-- Uses responsive Bulma CSS framework, supports Bootstrap CSS framework.
-- JavaScript framework agnostic, use Nim, Karax, vanilla JS, you choose.
+- Server Info Page for Admins.
+- Force Server restart for Admins.
+- Edit main config file directly from browser
+- Recompilation without down times.
+- Webserver hosting your page on 127.0.0.1:7000
- Colored output on the Terminal.
-- Plugin skeleton creator.
-- Multiple users
-- Add plugins
+- Email notification on critical errors.
+
+## Plugins
+- Plugin Store integrated
+- Enable and disable plugins directly from browser. Open Source or Private Plugins.
+- Plugin skeleton creator to create your own new plugins.
+- Plugins can do anything you want on Frontend and Backend.
+- Develop your own plugins - [NimWC plugin repository](https://github.com/ThomasTJdev/nimwc_plugins)
+
+## Database
+- [Postgres](https://www.postgresql.org) (if you are using the NimWC docker file, you do not need to install Postgres)
+- SQLite
+
+## Performance
+- High performance with low resources (RPi, VPS, cloud, old pc, etc).
+- Runs on any non-Windows OS, Architecture and Hardware that can compile C code.
+- [Independent TechEmpower Benchmarks show Nim web server as one of the fastest in the world.](https://www.techempower.com/benchmarks/#section=data-r17&hw=cl&test=json)
+- High Availability design by default.
+- Full Stack with the same programming language, including DevOps and Scripting.
+- 0 Dependency binary (Postgres/SSL/WebP/Firejail required if using it).
+- No `/node_modules/`, but very powerful builtin Templating engine.
+- Compile-Time precomputed arbitrary function execution is used when possible.
+- No Global Interpreter Lock, no single-Thread, no single-Core, no Interpreter. Use all your 32 CPU Cores.
+
+## Responsive
+- Uses responsive [Bulma CSS framework](https://bulma.io), supports [Bootstrap CSS framework](https://getbootstrap.com).
+- JavaScript framework agnostic, use Nim, [Karax](https://github.com/pragmagic/karax), vanilla JS, you choose.
+
+## Other
+- [WebP](https://caniuse.com/#feat=webp) automatic Image and Photo Optimizations.
+- [NGINX Config](https://github.com/ThomasTJdev/nim_websitecreator/tree/master/devops/) template.
+- [SystemD Service](https://github.com/ThomasTJdev/nim_websitecreator/tree/master/devops/) template.
+- [Vagrantfile](https://github.com/ThomasTJdev/nim_websitecreator/tree/master/devops/) template.
+- [Dockerfile](https://github.com/ThomasTJdev/nim_websitecreator/tree/master/devops/) template.
+
+
+# Requirements
+
+To get started you only need:
+
+- Linux (For Windows [see Docker-for-Windows](http://docs.docker.com/docker-for-windows))
+- Nim >= `0.19.2`
+
-## Requirements
+Development Dependencies (automatically installed by Nimble):
+
+- Jester >= `0.4.1`
+- reCAPTCHA >= `1.0.2`
+- bCrypt >= `0.2.1`
+- datetime2human >= `0.2.2`
+- otp >= `0.1.1`
+- firejail >= `0.4.0`
+- webp >= `0.1.0`
-- Linux
-- Nim >= `0.19.2`
-- Nim modules (automated when using Nimble):
- - jester >= `0.4.1`
- - reCAPTCHA >= `1.0.2`
- - bcrypt >= `0.2.1`
+
-# Compiling / Installing
+
+# Install
## Install Nim
+
To compile and install you need [Nim](https://nim-lang.org/). You can easily install Nim using [choosenim](https://nim-lang.org/install_unix.html) with:
+
```
curl https://nim-lang.org/choosenim/init.sh -sSf | sh
```
@@ -48,8 +111,9 @@ curl https://nim-lang.org/choosenim/init.sh -sSf | sh
You only need to perform 1a **or** 1b - not both of them.
-### 1a) Install:
+### 1a) Install
+
If you are using [Nimble](https://github.com/nim-lang/nimble) an executable will be generated and symlinked to `nimwc`, which then can be executed anywhere on your system.
```bash
@@ -68,9 +132,12 @@ nimwc
# Login
127.0.0.1:7000/login
```
+
-### 1b) Compile:
+### 1b) Compile
+
+
This will generate the executable in the folder.
@@ -95,8 +162,12 @@ nim c -d:ssl nimwc.nim
127.0.0.1:7000/login
```
+
+
+
+# Use
-## Argument (args):
+## Arguments
These arguments should be prepended to executable file, e.g. `./nimwc cdata`
@@ -122,6 +193,7 @@ These options are only available at compiletime:
* `-d:devemailon` = Send email when `-d:dev` is activated
* `-d:demo` = Used on public test site [Nim Website Creator](https://nimwc.org). This option will override the database each hour with the standard data.
* `-d:gitupdate` = Updates and force a hard reset
+* `-d:postgres` = Use Postgres database instead of SQLite
# User profiles
@@ -133,6 +205,8 @@ There are 3 main user profiles:
The access rights below applies to main program. Plugins can have their own definition of user rights.
+
+
## User
The "User" can login and see private pages and blog pages. This user has no access to adding or editing anything.
@@ -145,6 +219,8 @@ The "Moderator" can login and see private pages and blog pages. The user **can**
The "Admin" has access to anything.
+
+
# Blog
You can easily add and edit blogpages. The blogpages support metadata: meta description and meta keywords. It is also possible to specify a category and tags.
@@ -174,35 +250,45 @@ The plugin repository are located here: [NimWC plugin repository](https://github
When editing a blogpage or a normal page press Ctrl+S to save.
-# Google reCAPTCHA
+
+# GrapesJS
+
+GrapesJS is a Web Builder Framework. To use GrapeJS with a CSS framework (Bulma or Bootstrap), you have to edit `public/js/grapejs_custom.js` and `public/js/grapejsbs4.min.js`. Bootstrap support in `public/js/grapejs_custom.js` is commented out.
+
+
+# DevOps
+
+
+ Docker, Vagrant, SystemD Service, NGNIX, Admin stuff, etc
+
+**Docker**
+
+- [Use the Dockerfile](https://github.com/ThomasTJdev/nim_websitecreator/blob/master/devops/Dockerfile) as starting point for your NimWC containers.
+
+
+**Vagrant**
+
+- [Use the Vagrantfile](https://github.com/ThomasTJdev/nim_websitecreator/blob/master/devops/Vagrantfile) as starting point for your NimWC VMs.
+
+
+**NGNIX Config**
+
+- [Use the NGNIX Config file](https://github.com/ThomasTJdev/nim_websitecreator/blob/master/devops/config_nginx_default.cfg) as starting point for your NGNIX Server configuration.
+
+
+**Google reCAPTCHA**
To activate Google reCAPTCHA [claim you site and server key](https://www.google.com/recaptcha/admin) and insert them into `config.cfg`.
-# Autorun - systemctl
-## Service file
+**SystemD**
-Create a new file called nimwc.service inside /lib/systemd/system/:
-```
-sudo nano /lib/systemd/system/nimwc.service
-```
+- [Use the SystemD Service file](https://github.com/ThomasTJdev/nim_websitecreator/blob/master/devops/nimwc.service) as starting point for your NimWC SystemD Services.
+
+Copy the file called `nimwc.service` inside `/lib/systemd/system/`
-Add the following to the file:
```
-[Unit]
-Description=nimwc
-After=network.target
-
-[Service]
-User=ubuntu # MODIFY to your username
-Type=simple
-WorkingDirectory=/home//.nimble/pkgs/nimwc-2.0.0/ # MODIFY to your installation path
-ExecStart=/home//.nimble/pkgs/nimwc-2.0.0/nimwc # MODIFY to your installation path
-Restart=always
-RestartSec=3
-
-[Install]
-WantedBy=multi-user.target
+sudo nano /lib/systemd/system/nimwc.service
```
## Enable auto start and start it:
@@ -212,14 +298,43 @@ sudo systemctl start nimwc
sudo systemctl status nimwc
```
-# GrapesJS
-GrapesJS is a Web Builder Framework. To use GrapeJS with a CSS framework (Bulma or Bootstrap), you have to edit `public/js/grapejs_custom.js` and `public/js/grapejsbs4.min.js`. Bootstrap support in `public/js/grapejs_custom.js` is commented out.
-# Trouble
+
+
+
+# How to Firejail
+
+
+
+- Default settings will work Ok on most systems, sane defaults.
+- Some settings are kind of technical, you should know some Linux Kernel related stuff.
+- Links are provided on the Firejail config page when makes sense.
+- You can harden your system even more by tweaking the Firejail config.
+- You can always come back to the default settings and it will work Ok.
+- Check that Firejail Status at bottom of the page is mostly green.
+
+You can choose how much CPU & RAM NimWC can use,
+Firejail will make NimWC believe that theres less CPU & RAM that the actually physically available.
+If you choose too small resources for too big load,
+then it will feel like when you try to run a heavy program on a VirtualBox with too small CPU & RAM,
+but will still run, or do the best to try to run.
+This can be useful for Clouds that charge you extra when you pass certain threshold of CPU & RAM usage.
+
+NimWC does not depend on any Hardware device to run, like audio, video, USB, DVD, etc,
+so you can block the access to the hardware peripehals,
+that also blocks its hardware drivers and libraries that may have vulnerabilities, making your NimWC more secure.
+
+Theres options to block root user and the rest of the users on the Linux system,
+thats help protect your NimWC agaisnt Privilege Scalations,
+thats when an unprivileged normal user becomes superuser root, or an user can see other users stuff.
-Remove `nimcache` and `nimwcpkg/nimcache` and re-compile
+Caches and Temporary directories are mounted as private temporary unique autogenerated TMPFS,
+meaning that the real ones can not be altered from within NimWC.
+The features come from the Linux Kernel itself,
+so theres zero cost on performance and the technology is already there even if you use it or not.
-# Docker
+So in conclusion NimWC being compiled binary wont need access to most of your system,
+just its own folder, the integration with Firejails hides everything else.
-- [Use the Dockerfile](https://github.com/ThomasTJdev/nim_websitecreator/blob/master/Dockerfile) as starting point for your NimWC containers.
+
diff --git a/config/config_default.cfg b/config/config_default.cfg
index a0e05043f..002f9d8ca 100644
--- a/config/config_default.cfg
+++ b/config/config_default.cfg
@@ -1,9 +1,10 @@
[Database]
-folder = "data"
-host = "data/website.db"
-name = "website"
+folder = "data" # Not relevant when using Postgres
+host = "data/website.db" # Postgres example: localhost
+name = "website" # Database name
user = "user"
pass = ""
+port = 5432
[Storage]
storagedev = "fileslocal"
@@ -16,8 +17,8 @@ logfile = "log/log.log"
[Server]
website = "https://nimwc.org" # Pretty url
title = "Nim Website Creator"
-url = "127.0.0.1" # Where is jester binding the webserver
-port = "7000"
+url = "127.0.0.1" # Where jester is binding the webserver
+port = 7000 # The port jester uses
[Proxy]
url = "/"
@@ -35,3 +36,40 @@ SMTPPassword = ""
SMTPFrom = ""
SMTPEmailAdmin = ""
SMTPEmailSupport = ""
+
+[firejail]
+noDvd=true
+noSound=true
+noAutoPulse=true
+no3d=true
+noX=true
+noVideo=true
+noDbus=true
+noDebuggers=true
+noMachineId=true
+noRoot=true
+noAllusers=true
+noU2f=true
+privateTmp=true
+privateCache=true
+privateDev=true
+noShell=true
+forceEnUsUtf8=true
+caps=true
+seccomp=true
+noTv=true
+writables=true
+noMnt=true
+maxSubProcesses=0
+maxOpenFiles=0
+maxFileSize=0
+maxPendingSignals=0
+timeout=0
+maxCpu=0
+maxRam=0
+cpuCoresByNumber=0
+hostsFile=/etc/hosts
+dns0=""
+dns1=""
+dns2=""
+dns3=""
diff --git a/devops/Dockerfile b/devops/Dockerfile
new file mode 100644
index 000000000..f370c28ff
--- /dev/null
+++ b/devops/Dockerfile
@@ -0,0 +1,12 @@
+FROM archlinux/base
+RUN export CHOOSENIM_NO_ANALYTICS=1 ; export PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH ; echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> ~/.profile ; echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> ~/.bashrc ; echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> /root/.profile ; echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> /root/.bashrc ; source /root/.bashrc
+RUN pacman -Syu --needed --noconfirm --quiet git pacman-contrib base-devel libwebp firejail
+RUN curl -sfk https://nim-lang.org/choosenim/init.sh > init.sh && sh init.sh -y
+RUN /root/.nimble/bin/nimble -y refresh
+# RUN nimble -y install nimwc@4.5.0
+# RUN /root/.nimble/bin/nimble -y install nimwc@4.0.12
+RUN git clone https://github.com/ThomasTJdev/nim_websitecreator.git && cd nim_websitecreator
+# RUN /root/.nimble/bin/nim c -d:release -d:ssl -d:sqlite --passL:"-s" /root/nim_websitecreator/nimwc.nim
+RUN rm -rf /var/lib/apt/lists/* /var/tmp/* /tmp/nimblecache/* /tmp/* /var/log/journal/*
+EXPOSE 5000
+EXPOSE 7000
diff --git a/devops/Vagrantfile b/devops/Vagrantfile
new file mode 100644
index 000000000..705326ee6
--- /dev/null
+++ b/devops/Vagrantfile
@@ -0,0 +1,106 @@
+# -*- mode: ruby -*-
+# vi: set ft=ruby :
+
+
+ENV["LC_ALL"] = "en_US.UTF-8" # This Locale will be shared on Host and Guest.
+
+VAGRANTFILE_API_VERSION = "2" # Vagrantfile API/syntax version. Dont touch.
+
+
+$script = <<-SCRIPT
+
+echo Updating and Upgrading Pacman...
+yes | pacman -Syuu --needed
+
+echo Installing Database Server...
+pacman -Syu --needed --noconfirm --quiet git pacman-contrib base-devel libwebp firejail
+
+echo Installing Nim with ChooseNim...
+export CHOOSENIM_NO_ANALYTICS=1
+export PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH
+echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> ~/.profile
+echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> ~/.bashrc
+echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> /root/.profile
+echo "PATH=$HOME/.nimble/bin:/root/.nimble/bin:$PATH" >> /root/.bashrc
+source /root/.bashrc
+curl -sfk https://nim-lang.org/choosenim/init.sh > init.sh
+sh init.sh -y
+
+echo Updating Nimble...
+nimble -y refresh
+
+echo Installing Nim Website Creator...
+git clone https://github.com/ThomasTJdev/nim_websitecreator.git
+cd nim_websitecreator
+nim c -d:release -d:ssl -d:sqlite --passL:"-s" nimwc.nim
+
+echo Clean out...
+yes | pacman -Scc
+rm -rf /var/lib/apt/lists/* /var/tmp/* /tmp/nimblecache/* /tmp/* /var/log/journal/*
+
+SCRIPT
+
+
+Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
+
+ # Every Vagrant requires a box. See list http://vagrantbox.es
+ config.vm.box = "archlinux/archlinux"
+
+ # If true, then any SSH connections made will enable agent forwarding.
+ config.ssh.forward_agent = true
+
+ # Check for updates of the box on every boot.
+ config.vm.box_check_update = true
+
+ # Check SSL certificates of the server.
+ config.vm.box_download_insecure = true
+
+ # Checks all HTTP redirects, will be treated as trusted.
+ config.vm.box_download_location_trusted = true
+
+ # Time in seconds that Vagrant will wait for the machine to gracefully halt.
+ config.vm.graceful_halt_timeout = 5
+
+ # The hostname the virtual machine should have.
+ config.vm.hostname = "nim"
+
+ # Post boot up message.
+ config.vm.post_up_message = "Nim Website Creator Vagrant Box http://nimwc.org"
+
+ # Simple Bash Shell Provider, more than enough for Nim.
+ config.vm.provision "shell", inline: $script
+
+ # Create a forwarded port mapping which allows access to a specific port
+ # within the machine from a port on the host machine. In the example below,
+ # accessing "localhost:8080" will access port 80 on the guest machine.
+ # config.vm.network "forwarded_port", guest: 80, host: 8080
+
+ # Create a private network, which allows host-only access to the machine
+ # using a specific IP.
+ # config.vm.network "private_network", ip: "192.168.33.10"
+ # config.vm.network :private_network, ip: "192.168.58.111"
+
+ # Create a public network, which generally matched to bridged network.
+ # Bridged networks make the machine appear as another physical device on
+ # your network.
+ # config.vm.network "public_network"
+
+ # Share an additional folder to the guest VM. The first argument is
+ # the path on the host to the actual folder. The second argument is
+ # the path on the guest to mount the folder. And the optional third
+ # argument is a set of non-required options.
+ # config.vm.synced_folder "../data", "/vagrant_data"
+
+ config.vm.provider :virtualbox do |vb|
+ # Boot with headless mode or not.
+ vb.gui = false
+
+ # Use VBoxManage to customize the VM. For example to change memory:
+ vb.customize [
+ 'modifyvm', :id,
+ '--natdnshostresolver1', 'on',
+ '--memory', '1024',
+ '--cpus', '2'
+ ]
+ end
+end
diff --git a/devops/build_docker.sh b/devops/build_docker.sh
new file mode 100755
index 000000000..3c16f24a0
--- /dev/null
+++ b/devops/build_docker.sh
@@ -0,0 +1,2 @@
+#!/bin/bash
+docker build -t nimwc:1.0 . # Build a Docker from the Dockerfile.
diff --git a/config/config_nginx_default.cfg b/devops/config_nginx_default.cfg
similarity index 89%
rename from config/config_nginx_default.cfg
rename to devops/config_nginx_default.cfg
index ccf388b72..edb7acba4 100644
--- a/config/config_nginx_default.cfg
+++ b/devops/config_nginx_default.cfg
@@ -1,4 +1,5 @@
# Template for nginx configuration sites-available/default
+# Check if the config is valid using: nginx -t YourConfig.cfg
# To use SSL Let's Encrypt, install certbot and run:
# $sudo certbot --nginx -d webpage.com www.webpage.com
@@ -18,7 +19,7 @@ server {
location / {
root /home/user/nim/nimwc/public;
- if ($request_uri ~* ".(ico|css|js|gif|jpe?g|png|svg)$") {
+ if ($request_uri ~* ".(ico|css|js|gif|jpeg|jpg|png|svg|bmp|webp)$") {
expires max;
access_log off;
add_header Pragma public;
@@ -36,4 +37,4 @@ server {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
-}
\ No newline at end of file
+}
diff --git a/devops/nimwc.desktop b/devops/nimwc.desktop
new file mode 100644
index 000000000..1ba469ec6
--- /dev/null
+++ b/devops/nimwc.desktop
@@ -0,0 +1,12 @@
+[Desktop Entry]
+Comment=Nim Website Creator
+Exec=nimwc
+GenericName=Nim Website Creator
+Icon=system-run
+Name=nimwc
+StartupNotify=false
+Terminal=true
+Type=Application
+Categories=Utility
+X-DBUS-ServiceName=nimwc
+X-KDE-StartupNotify=false
diff --git a/devops/nimwc.service b/devops/nimwc.service
new file mode 100644
index 000000000..384c7cdfc
--- /dev/null
+++ b/devops/nimwc.service
@@ -0,0 +1,25 @@
+[Unit]
+Description=Nim Website Creator SystemD Service
+Documentation=https://github.com/ThomasTJdev/nim_websitecreator#nim-website-creator
+After=network-online.target # postgres.service
+
+[Service]
+Type=simple
+User=nobody # Change to your user.
+Restart=always # on-failure
+RestartSec=1 # Sleep Seconds before restarting the process.
+RuntimeMaxSec=1w # Restart process periodically. 1w=week, 1d=day, 1m=minute.
+TimeoutStartSec=999 # Timeout Seconds while starting the process.
+TimeoutStopSec=999 # Timeout Seconds while stopping the process.
+# ExecStartPre= # Execute BEFORE start.
+ExecStart=nimwc # Execute your nimwc command.
+# ExecStartPost= # Execute AFTER start.
+# ExecReload= # Execute while restarting the process.
+# ExecStop= # Execute while stopping the process.
+# ExecStopPost= # Execute AFTER stopping the process.
+# Environment= # You can add any Environment variables here.
+WorkingDirectory=/home//.nimble/pkgs/nimwc-5.0.0/ # MODIFY to your installation path
+ExecStart=/home//.nimble/bin/nimwc
+
+[Install]
+WantedBy=multi-user.target
diff --git a/devops/run_docker.sh b/devops/run_docker.sh
new file mode 100755
index 000000000..ea6491eb5
--- /dev/null
+++ b/devops/run_docker.sh
@@ -0,0 +1,2 @@
+#!/bin/bash
+docker run --rm -i -t -w /tmp -p 5000:5000 nimwc:1.0 # Run docker.
diff --git a/nimwc.nim b/nimwc.nim
index 42b48d6f7..a626a4dd8 100644
--- a/nimwc.nim
+++ b/nimwc.nim
@@ -1,5 +1,11 @@
import os, osproc, rdstdin, sequtils, strutils, terminal, times, json
-{.passL: "-s".} # Force strip all on the resulting Binary, so its smaller.
+
+when not defined(firejail): {.warning: "Firejail is Disabled, Running Unsecure.".}
+else: import firejail, parsecfg
+
+when defined(windows):
+ {.fatal: "Cannot run on Windows, but you can try Docker for Windows: http://docs.docker.com/docker-for-windows".}
+when defined(release): {.passL: "-s".} # Force strip all on the resulting Binary.
const
update_cmds = [
@@ -15,41 +21,43 @@ const
"mv tmp/js_custom.js plugins/js/js_custom.js",
] ## Bash Commands to Update NimWC.
- compile_start_msg = """Compiling, Please wait...
- - Using compile options from *.nim.cfg
- - Using params: """ ## Message to show when started Compiling.
+ compile_start_msg = """⏰ Compiling, Please wait ⏰
+ ☑️ Using compile options from *.nim.cfg
+ ☑️ Using params: """ ## Message to show when started Compiling.
- compile_ok_msg = """Compiling done!.
+ compile_ok_msg = """ Nim Website Creator Compiled Ok!
- - To start Nim Website Creator and access at http://127.0.0.1:
- # Manually compiled
- ./nimwc
+ ☑️️ To start Nim Website Creator and access at http://127.0.0.1:
+ # Manually compiled
+ ./nimwc
- # Through nimble, then just run with symlink
- nimwc
+ # Through nimble, then just run with symlink
+ nimwc
- - To add an admin user, append args:
- ./nimwc newuser -u:name -p:password -e:email
+ ☑️ To add an admin user, append args:
+ ./nimwc newuser -u:name -p:password -e:email
- - To insert standard data in the database, append args:
- ./nimwc insertdata
+ ☑️ To insert standard data in the database, append args:
+ ./nimwc insertdata
- - To insert standard data in the database:
- ./nimwc --insertdata
+ ☑️ To insert standard data in the database:
+ ./nimwc --insertdata
- - Access Settings page at http://127.0.0.1:/settings
+ ☑️ Access Settings page at http://127.0.0.1:/settings
""" ## Message to show when finished Compiling OK.
- compile_fail_msg = """Compiling Failed.
+ compile_fail_msg = """ Compile Error
- - A Compile-time or Configuration error occurred.
- You can check your source code with: nim check
- Check the Configuration of NimWC and its Plugins.
+ ⚠️ Compile-time or Configuration or Plugin error occurred.
+ ➡️ You can check your source code with: nim check YourFile.nim
+ ➡️ Check the Configuration of NimWC and its Plugins.
+ ➡️ Remove new Plugins, restore previous Configuration.
+ Check that you have the latest Version. Check the Documentation.
""" ## Message to show when Compiling Failed.
- doc = """
- nimwc: Nim Website Creator.
- A quick website tool. Run the nim file and access your webpage.
+ doc = """ Nim Website Creator - https://NimWC.org
+ Self-Firejailing 2-Factor-Auth Nim Web Framework thats simple to use.
+ Run it, access your web, customize, add plugins, deploy today anywhere.
Usage:
nimwc
@@ -60,41 +68,50 @@ const
-u:
-p:
-e:`
- --insertdata Insert standard data (this will override existing data).
- bulma - standard data based on Bulma
- bootstrap - standard data based on Bootstrap
- clean - standard data without a CSS/JS framework
- --newdb Generates the database with standard tables (does **not**
- override or delete tables). `newdb` will be initialized
- automatic, if no database exists.
+ --insertdata Insert standard data (override existing data).
+ bulma - standard data based on Bulma
+ bootstrap - standard data based on Bootstrap
+ clean - standard data without a CSS/JS framework
+ --newdb Generates the database with standard tables
+ (does NOT override or delete tables).
+ newdb will be initialized automatic, if no database exists.
--gitupdate Updates and force a hard reset.
--initplugin Create plugin skeleton inside tmp/
Compile options:
- -d:rc Recompile. NinmWC is using a launcher, it is therefore
- needed to force a recompile.
- -d:adminnotify Send error logs (ERROR) to the specified admin email
- -d:dev Development (ignore reCaptcha)
- -d:devemailon Send email when `-d:dev` is activated
- -d:demo Used on public test site. Enables a test user.
- This option will override the database each hour with
- the standard data.
- -d:gitupdate Updates and force a hard reset
+ -d:sqlite SQLite Dabatase is enabled. Postgres dabatase is disabled.
+ -d:firejail Firejail is enabled. Runs secure.
+ -d:webp WebP is enabled. Optimize images.
+ -d:rc Force Recompile (good for Troubleshooting).
+ -d:adminnotify Send error logs (ERROR) to the specified Admin email.
+ -d:dev Development (ignore reCaptcha, no emails, more Verbose).
+ -d:devemailon Send email when -d:dev is activated.
+ -d:demo Public demo mode. Enable Test user. 2FA ignored.
+ Force database reset every 1 hour. Some options Disabled.
+ -d:gitupdate Force update from Git and force a hard reset.
+
+ Tips:
+ Always Compile with -d:release for Production. We recommend Firejail too.
+ Learn more: http://nim-lang.org/learn.html http://nim-lang.github.io/Nim/lib.html
"""
compileOptions = ["",
when defined(adminnotify): " -d:adminnotify",
- when defined(dev): " -d:dev",
- when defined(devemailon): " -d:devemailon",
- when defined(demo): " -d:demo",
- when defined(ssl): " -d:ssl",
+ when defined(dev): " -d:dev",
+ when defined(devemailon): " -d:devemailon",
+ when defined(demo): " -d:demo",
+ when defined(ssl): " -d:ssl",
+ when defined(postgres): " -d:postgres",
+ when defined(webp): " -d:webp",
+ when defined(firejail): " -d:firejail",
+ when defined(release): " -d:release"
].join ## Checking for known compile options and returning them as a space separated string at Compile-Time. See README.md for explanation of the options.
nimwc_version =
try:
filter_it("nimwc.nimble".readFile.splitLines, it.substr(0, 6) == "version")[0].split("=")[1].normalize ## Get NimWC Version at Compile-Time.
except:
- "4.0.12" ## Set NimWC Version at Compile-Time, if ready from file failed.
+ "5.0.0" ## Set NimWC Version at Compile-Time, if ready from file failed.
var
@@ -113,7 +130,7 @@ proc handler() {.noconv.} =
## Catch ctrl+c from user
runInLoop = false
kill(nimhaMain)
- styledEcho(fgYellow, bgBlack, "CTRL+C Pressed, NimWC is shutting down.")
+ styledEcho(fgYellow, bgBlack, "CTRL+C Pressed, NimWC is shutting down, Bye.")
quit()
setControlCHook(handler)
@@ -123,9 +140,64 @@ proc launcherActivated() =
## 1) Executing the main-program in a loop.
## 2) Each time a new compiled file is available,
## the program exits the running process and starts a new
- styledEcho(fgGreen, bgBlack, $now() & ": Nim Website Creator: Launcher initialized")
-
- nimhaMain = startProcess(getAppDir() & "/nimwcpkg/nimwc_main" & userArgsRun, options = {poParentStreams, poEvalCommand})
+ styledEcho(fgGreen, bgBlack, $now() & ": Nim Website Creator: Launcher starting.")
+ var nimwcCommand: string
+
+ when not defined(firejail):
+ nimwcCommand = getAppDir() & "/nimwcpkg/nimwc_main" & userArgsRun
+ else:
+ let
+ dict = loadConfig(getAppDir() & "/config/config.cfg")
+ cpuCores = dict.getSectionValue("firejail", "cpuCoresByNumber").parseInt
+ corez = if cpuCores != 0: toSeq(0..cpuCores) else: @[]
+ hostz = dict.getSectionValue("firejail", "hostsFile").strip
+ dnsz = [dict.getSectionValue("firejail", "dns0").strip, dict.getSectionValue("firejail", "dns1").strip,
+ dict.getSectionValue("firejail", "dns2").strip, dict.getSectionValue("firejail", "dns3").strip]
+ assert countProcessors() > cpuCores, "Dedicated CPU Cores must be less or equal than the actual CPU Cores: " & $cpuCores
+ assert hostz.existsFile, "Hosts file not found: " & hostz
+ let myjail = Firejail(
+ noDvd: dict.getSectionValue("firejail", "noDvd").parseBool,
+ noSound: dict.getSectionValue("firejail", "noSound").parseBool,
+ noAutoPulse: dict.getSectionValue("firejail", "noAutoPulse").parseBool,
+ no3d: dict.getSectionValue("firejail", "no3d").parseBool,
+ noX: dict.getSectionValue("firejail", "noX").parseBool,
+ noVideo: dict.getSectionValue("firejail", "noVideo").parseBool,
+ noDbus: dict.getSectionValue("firejail", "noDbus").parseBool,
+ noShell: dict.getSectionValue("firejail", "noShell").parseBool,
+ noDebuggers: dict.getSectionValue("firejail", "noDebuggers").parseBool,
+ noMachineId: dict.getSectionValue("firejail", "noMachineId").parseBool,
+ noRoot: dict.getSectionValue("firejail", "noRoot").parseBool,
+ noAllusers: dict.getSectionValue("firejail", "noAllusers").parseBool,
+ noU2f: dict.getSectionValue("firejail", "noU2f").parseBool,
+ privateTmp: dict.getSectionValue("firejail", "privateTmp").parseBool,
+ privateCache: dict.getSectionValue("firejail", "privateCache").parseBool,
+ privateDev: dict.getSectionValue("firejail", "privateDev").parseBool,
+ forceEnUsUtf8: dict.getSectionValue("firejail", "forceEnUsUtf8").parseBool,
+ caps: dict.getSectionValue("firejail", "caps").parseBool,
+ seccomp: dict.getSectionValue("firejail", "seccomp").parseBool,
+ noTv: dict.getSectionValue("firejail", "noTv").parseBool,
+ writables: dict.getSectionValue("firejail", "writables").parseBool,
+ noMnt: dict.getSectionValue("firejail", "noMnt").parseBool,
+ )
+ nimwcCommand = myjail.makeCommand(
+ command=getAppDir() & "/nimwcpkg/nimwc_main" & userArgsRun,
+ name="nimwc_main", # whitelist= @[getAppDir(), getCurrentDir()],
+ maxSubProcesses = dict.getSectionValue("firejail", "maxSubProcesses").parseInt * 1_000_000, # 1 is Ok, 0 is Disabled, int.high max.
+ maxOpenFiles = dict.getSectionValue("firejail", "maxOpenFiles").parseInt * 1_000, # Below 1000 NimWC may not start.
+ maxFileSize = dict.getSectionValue("firejail", "maxFileSize").parseInt * 1_000_000_000, # Below 1Mb NimWC may not start.
+ maxPendingSignals = dict.getSectionValue("firejail", "maxPendingSignals").parseInt * 10, # 1 is Ok, 0 is Disabled, int.high max.
+ timeout = dict.getSectionValue("firejail", "timeout").parseInt, # 1 is Ok, 0 is Disabled, 255 max. It will actually Restart instead of Stopping.
+ maxRam = dict.getSectionValue("firejail", "maxRam").parseInt * 1_000_000_000, # Below 1Gb NimWC may fail.
+ maxCpu = dict.getSectionValue("firejail", "maxCpu").parseInt, # 1 is Ok, 0 is Disabled, 255 max.
+ cpuCoresByNumber = corez, # 0 is Disabled, else toSeq(0..corez)
+ hostsFile = hostz, # Optional Alternative/Fake /etc/hosts
+ dnsServers = dnsz, # Optional Alternative/Fake DNS, 4 Servers must be provided
+ )
+
+ const processOpts =
+ when defined(release): {poParentStreams, poEvalCommand}
+ else: {poParentStreams, poEvalCommand, poEchoCmd}
+ nimhaMain = startProcess(nimwcCommand, options = processOpts)
while runInLoop:
if fileExists(getAppDir() & "/nimwcpkg/nimwc_main_new"):
@@ -133,7 +205,7 @@ proc launcherActivated() =
moveFile(getAppDir() & "/nimwcpkg/nimwc_main_new", getAppDir() & "/nimwcpkg/nimwc_main")
if not running(nimhaMain):
- styledEcho(fgYellow, bgBlack, $now() & ": Restarting program in 1 second")
+ styledEcho(fgYellow, bgBlack, $now() & ": Restarting in 1 second.")
discard execCmd("pkill nimwc_main")
sleep(1000)
@@ -141,11 +213,11 @@ proc launcherActivated() =
if userArgsRun != "":
styledEcho(fgGreen, bgBlack, " Using args: " & userArgsRun)
- nimhaMain = startProcess(getAppDir() & "/nimwcpkg/nimwc_main" & userArgsRun, options = {poParentStreams, poEvalCommand})
+ nimhaMain = startProcess(nimwcCommand, options = processOpts)
sleep(2000)
- styledEcho(fgYellow, bgBlack, $now() & ": Nim Website Creator: Quitted")
+ styledEcho(fgYellow, bgBlack, $now() & ": Nim Website Creator: Stopping.")
quit()
@@ -168,7 +240,7 @@ proc updateNimwc() =
if "gitupdate" in commandLineParams() or defined(gitupdate):
discard existsOrCreateDir("tmp")
for comand in update_cmds:
- discard execCmd(comand)
+ discard execCmd(comand)
styledEcho(fgGreen, bgBlack, "\n\nNimWC has been updated\n\n")
quit()
diff --git a/nimwc.nim.cfg b/nimwc.nim.cfg
index 521e21de4..bf4a9fce1 100644
--- a/nimwc.nim.cfg
+++ b/nimwc.nim.cfg
@@ -1 +1,3 @@
-d:ssl
+-d:firejail
+-d:webp
diff --git a/nimwc.nimble b/nimwc.nimble
index d06fbbea1..dbe0d7fec 100644
--- a/nimwc.nimble
+++ b/nimwc.nimble
@@ -1,19 +1,23 @@
# Package
-version = "4.0.12"
-author = "Thomas T. Jarløv (https://github.com/ThomasTJdev)"
+version = "5.0.0"
+author = "Thomas T. Jarløv (https://github.com/ThomasTJdev) & Juan Carlos (https://github.com/juancarlospaco)"
description = "Generate and host a website. Run the package and access your new webpage."
license = "GPLv3"
bin = @["nimwc"]
-skipDirs = @["private", "tmp"]
+skipDirs = @["private", "tmp", "devops"]
installDirs = @["config", "nimwcpkg", "plugins", "public"]
# Dependencies
-requires "nim >= 0.19.2"
+requires "nim >= 0.19.4"
requires "jester >= 0.4.1"
requires "recaptcha >= 1.0.2"
requires "bcrypt >= 0.2.1"
+requires "datetime2human >= 0.2.2"
+requires "otp >= 0.1.1"
+requires "firejail >= 0.5.0"
+requires "webp >= 0.2.0"
import distros
diff --git a/nimwcpkg/nimwc_main.nim b/nimwcpkg/nimwc_main.nim
index f59807b4a..0fb49351d 100644
--- a/nimwcpkg/nimwc_main.nim
+++ b/nimwcpkg/nimwc_main.nim
@@ -1,15 +1,17 @@
-#
-#
# TTJ
-# (c) Copyright 2018 Thomas Toftgaard Jarløv
+# (c) Copyright 2019 Thomas Toftgaard Jarløv
# Look at LICENSE for more info.
# All rights reserved.
-#
+when defined(windows):
+ {.fatal: "Cannot run on Windows, but you can try Docker for Windows: http://docs.docker.com/docker-for-windows".}
{.passL: "-s".} # Force strip all on the resulting Binary, so its smaller.
+# when defined(demo): {.passC: "-flto -ffast-math -march=native".}
import
- asyncdispatch, bcrypt, cgi, db_sqlite, jester, json, macros, os, osproc, logging,
- parsecfg, random, re, recaptcha, sequtils, strutils, times, oswalkdir as oc,
+ asyncdispatch, bcrypt, cgi, jester, json, macros, os, osproc, logging, otp,
+ parsecfg, random, re, recaptcha, sequtils, strutils, times, datetime2human,
+ base32, streams, encodings, nativesockets,
+ oswalkdir as oc,
resources/administration/create_adminuser,
resources/administration/create_standarddata,
@@ -21,37 +23,48 @@ import
resources/password/password_generate,
resources/password/salt_generate,
resources/session/user_data,
- resources/utils/dates,
resources/utils/logging_nimwc,
resources/utils/plugins,
- resources/utils/random_generator,
resources/web/google_recaptcha
-when defined(windows): quit("\n Windows is not supported \n")
+when defined(postgres): import db_postgres
+else: import db_sqlite
+
+when not defined(webp): {. warning: "WebP is Disabled, No Image Optimizations." .}
+else: from webp import cwebp
+
+when not defined(firejail): {. warning: "Firejail is Disabled, Running Unsecure." .}
+else: from firejail import firejailVersion, firejailFeatures
+
const
config_not_found_msg = """
- ERROR: Config file (config.cfg) could not be found.
- A copy of the template (config_default.cfg) has been copied to config/config.cfg.
-
- The program will now quit. Please configure it and restart the program.
- """
+ 🐛 ERROR: Config file (config.cfg) could not be found. 🐛
+ A template (config_default.cfg) is copied to "config/config.cfg".
+ Please configure it and restart Nim Website Creator. Bye. """
startup_msg = """
- Package: Nim Website Creator
- Description: Website creator build with Nim
- Author name: Thomas Toftgaard Jarløv (TTJ)
- Current time: """
+ Package: Nim Website Creator - https://NimWC.org
+ Description: Self-Firejailing Nim Web Framework thats simple to use.
+ Author name: Thomas Toftgaard Jarløv (TTJ) & Juan Carlos (http://github.com/juancarlospaco)"""
checkCompileOptions* = ["",
when defined(adminnotify): " -d:adminnotify",
- when defined(dev): " -d:dev",
- when defined(devemailon): " -d:devemailon",
- when defined(demo): " -d:demo",
- when defined(ssl): " -d:ssl",
+ when defined(dev): " -d:dev",
+ when defined(devemailon): " -d:devemailon",
+ when defined(demo): " -d:demo",
+ when defined(ssl): " -d:ssl",
+ when defined(postgres): " -d:postgres",
+ when defined(webp): " -d:webp",
+ when defined(firejail): " -d:firejail",
+ when defined(release): " -d:release"
].join ## Checking for known compile options and returning them as a space separated string.
# Used within plugin route, where a recompile is required to include/exclude a plugin.
+ sql_now =
+ when defined(postgres): "(extract(epoch from now()))" # Postgres epoch.
+ else: "(strftime('%s', 'now'))" # SQLite 3 epoch.
+
macro configExists(): untyped =
## Macro to check if the config file is present
@@ -62,23 +75,26 @@ macro configExists(): untyped =
quit()
configExists()
+randomize()
+
+#
+# Macros
+#
-#[
- Macros
-__________________________________________________]#
proc getPluginsPath*(): seq[string] {.compileTime.} =
## Get all plugins path
##
## Generates a seq[string] with the path to the plugins
+ let
+ dir = parentDir(currentSourcePath())
+ realPath = replace(dir, "/nimwcpkg", "")
- let dir = parentDir(currentSourcePath())
- let realPath = replace(dir, "/nimwcpkg", "")
-
- var plugins = (staticRead(realPath & "/plugins/plugin_import.txt").split("\n"))
+ var
+ plugins = (staticRead(realPath & "/plugins/plugin_import.txt").split("\n"))
+ extensions: seq[string]
# Loop through all files and folders
- var extensions: seq[string]
for plugin in oc.walkDir("plugins/"):
let (pd, ppath) = plugin
discard pd
@@ -101,15 +117,13 @@ macro extensionImport(): untyped =
## Generate code for importing modules from extensions.
## The extensions main module needs to be in plugins/plugin_import.txt
## to be activated. Only 1 module will be imported.
-
var extensions = ""
for ppath in pluginsPath:
let splitted = split(ppath, "/")
extensions.add("import " & ppath & "/" & splitted[splitted.len-1] & "\n")
when defined(dev):
- echo "Plugins - imports:"
- echo extensions
+ echo "Plugins - imports:\n" & $extensions
result = parseStmt(extensions)
@@ -122,7 +136,6 @@ macro extensionUpdateDatabase(): untyped =
## Generate proc for updating the database with new tables etc.
## The extensions main module shall contain a proc named 'proc Start(db: DbConn) ='
## The proc will be executed when the program is executed.
-
var extensions = ""
extensions.add("proc extensionUpdateDB*(db: DbConn) =\n")
@@ -137,8 +150,7 @@ macro extensionUpdateDatabase(): untyped =
extensions.add(" echo \" \"")
when defined(dev):
- echo "Plugins - required proc:"
- echo extensions
+ echo "Plugins - required proc:\n" & $extensions
result = parseStmt(extensions)
@@ -152,26 +164,22 @@ macro extensionCss(): string =
## renaming to .css
##
## 2) Insert
+
Frontpage
Login to edit
"""
@@ -509,12 +512,11 @@ const
"""
+
proc standardDataSettings*(db: DbConn, dataStyle: string) =
## Settings
- echo " - Standard data: Inserting settings-data"
- let settingsExists = getValue(db, sql"SELECT id FROM settings WHERE id = ?", "1")
- if settingsExists != "":
- exec(db, sql"DELETE FROM settings WHERE id = ?", "1")
+ info"Standard data: Inserting settings-data."
+ exec(db, sql"DELETE FROM settings")
if dataStyle == "bootstrap":
discard insertID(db, sql"INSERT INTO settings (title, head, navbar, footer) VALUES (?, ?, ?, ?)", title, headBootstrap, navbarBootstrap, footer)
@@ -526,7 +528,7 @@ proc standardDataSettings*(db: DbConn, dataStyle: string) =
proc standardDataFrontpage*(db: DbConn, dataStyle = "") =
## Frontpage
- echo " - Standard data: Inserting frontpage-data"
+ info"Standard data: Inserting frontpage-data."
let frontpageExists = getValue(db, sql"SELECT id FROM pages WHERE url = ?", "frontpage")
if frontpageExists != "":
exec(db, sql"DELETE FROM pages WHERE id = ?", frontpageExists)
@@ -539,7 +541,7 @@ proc standardDataFrontpage*(db: DbConn, dataStyle = "") =
proc standardDataAbout*(db: DbConn) =
## About
- echo " - Standard data: Inserting about-data"
+ info"Standard data: Inserting about-data."
let aboutExists = getValue(db, sql"SELECT id FROM pages WHERE url = ?", "about")
if aboutExists != "":
exec(db, sql"DELETE FROM pages WHERE id = ?", aboutExists)
@@ -549,34 +551,37 @@ proc standardDataAbout*(db: DbConn) =
proc standardDataBlogpost1*(db: DbConn) =
## Blog post
- echo " - Standard data: Inserting blog post-data"
+ info"Standard data: Inserting blog post-data"
let blogExists = getValue(db, sql"SELECT id FROM blog WHERE url = ?", "standardpost")
if blogExists != "":
exec(db, sql"DELETE FROM blog WHERE id = ?", blogExists)
discard insertID(db, sql"INSERT INTO blog (author_id, status, url, name, description, standardhead, standardnavbar, standardfooter, title, metadescription, metakeywords) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", "1", "2", "standardpost", "Standard blogpost", blogpost1, "1", "1", "1", "NimWC Example blogpost", "This is an example blogpost using the default styling.", "website,blog,nim,nimwc")
+
proc standardDataBlogpost2*(db: DbConn) =
## Blog post
- echo " - Standard data: Inserting blog post-data"
+ info"Standard data: Inserting blog post-data."
let blogExists = getValue(db, sql"SELECT id FROM blog WHERE url = ?", "standardpostv2")
if blogExists != "":
exec(db, sql"DELETE FROM blog WHERE id = ?", blogExists)
discard insertID(db, sql"INSERT INTO blog (author_id, status, url, name, description, standardhead, standardnavbar, standardfooter, title, metadescription, metakeywords) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", "1", "2", "standardpostv2", "Parallax post v2", blogpost2, "1", "1", "1", "NimWC Example blogpost parallax", "This is an example blogpost using parallax created with NimWC.", "website,blog,nim,nimwc,parallax")
+
proc standardDataBlogpost3*(db: DbConn) =
## Blog post
- echo " - Standard data: Inserting blog post-data"
+ info"Standard data: Inserting blog post-data."
let blogExists = getValue(db, sql"SELECT id FROM blog WHERE url = ?", "standardpostv3")
if blogExists != "":
exec(db, sql"DELETE FROM blog WHERE id = ?", blogExists)
discard insertID(db, sql"INSERT INTO blog (author_id, status, url, name, description, standardhead, standardnavbar, standardfooter, title, metadescription, metakeywords) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", "1", "2", "standardpostv3", "Custom styling", blogpost3, "1", "1", "1", "NimWC Example blogpost custom", "This is an example blogpost using custom styling.", "website,blog,nim,nimwc")
+
proc createStandardData*(db: DbConn, dataStyle = "bulma") =
## Insert basic data
- echo "Standard data: Inserting standard data"
+ info"Standard data: Inserting standard data."
standardDataSettings(db, dataStyle)
standardDataFrontpage(db, dataStyle)
if dataStyle != "clean":
diff --git a/nimwcpkg/resources/administration/createdb.nim b/nimwcpkg/resources/administration/createdb.nim
index efb74ac18..cbe2bd00e 100644
--- a/nimwcpkg/resources/administration/createdb.nim
+++ b/nimwcpkg/resources/administration/createdb.nim
@@ -1,181 +1,202 @@
-#
-#
-# Hubanize / Cx Manager
-# (c) Copyright 2017 Thomas Toftgaard Jarløv
-# All rights reserved.
-#
-#
+import
+ os, parsecfg, strutils, logging,
+ ../administration/create_standarddata,
+ ../utils/logging_nimwc
-import db_sqlite, os, parsecfg, strutils
+when defined(postgres): import db_postgres
+else: import db_sqlite
-import ../administration/create_standarddata
setCurrentDir(getAppDir().replace("/nimwcpkg", "") & "/")
const
- TUserName = "varchar(20)"
- TPassword = "varchar(32)"
- TEmail = "varchar(30)"
+ sql_now =
+ when defined(postgres): "(extract(epoch from now()))" # Postgres epoch.
+ else: "(strftime('%s', 'now'))" # SQLite 3 epoch.
+
+ sql_timestamp =
+ when defined(postgres): "integer" # is internally Hardcoded to UTC anyways
+ else: "timestamp" # SQLite 3 Timestamp.
+
+ sql_id = # http://blog.2ndquadrant.com/postgresql-10-identity-columns
+ when defined(postgres): "integer generated by default as identity"
+ else: "integer" # SQLite 3 integer ID.
+
+ personTable = sql("""
+ create table if not exists person(
+ id $3 primary key,
+ name varchar(60) not null,
+ password varchar(300) not null,
+ twofa varchar(60),
+ email varchar(254) not null unique,
+ creation $2 not null default $1,
+ modified $2 not null default $1,
+ salt varchar(128) not null,
+ status varchar(30) not null,
+ timezone varchar(100),
+ secretUrl varchar(250),
+ lastOnline $2 not null default $1
+ );""".format(sql_now, sql_timestamp, sql_id))
+
+ sessionTable = sql("""
+ create table if not exists session(
+ id $3 primary key,
+ ip inet not null,
+ key varchar(300) not null,
+ userid integer not null,
+ lastModified $2 not null default $1,
+ foreign key (userid) references person(id)
+ );""".format(sql_now, sql_timestamp, sql_id))
+
+ historyTable = sql("""
+ create table if not exists history(
+ id $3 primary key,
+ user_id integer not null,
+ item_id integer,
+ element varchar(100),
+ choice varchar(100),
+ text varchar(1000),
+ creation $2 not null default $1
+ );""".format(sql_now, sql_timestamp, sql_id))
+
+ settingsTable = sql("""
+ create table if not exists settings(
+ id $1 primary key,
+ analytics text,
+ head text,
+ footer text,
+ navbar text,
+ title text,
+ disabled integer,
+ blogorder text,
+ blogsort text
+ );""".format(sql_id))
+
+ pagesTable = sql("""
+ create table if not exists pages(
+ id $3 primary key,
+ author_id INTEGER NOT NULL,
+ status INTEGER NOT NULL,
+ name VARCHAR(200) NOT NULL,
+ url VARCHAR(200) NOT NULL UNIQUE,
+ title TEXT,
+ metadescription TEXT,
+ metakeywords TEXT,
+ description TEXT,
+ head TEXT,
+ navbar TEXT,
+ footer TEXT,
+ standardhead INTEGER,
+ standardnavbar INTEGER,
+ standardfooter INTEGER,
+ tags VARCHAR(1000),
+ category VARCHAR(1000),
+ date_start VARCHAR(100),
+ date_end VARCHAR(100),
+ views INTEGER,
+ public INTEGER,
+ changes INTEGER,
+ modified $2 not null default $1,
+ creation $2 not null default $1,
+ foreign key (author_id) references person(id)
+ );""".format(sql_now, sql_timestamp, sql_id))
+
+ blogTable = sql("""
+ create table if not exists blog(
+ id $3 primary key,
+ author_id INTEGER NOT NULL,
+ status INTEGER NOT NULL,
+ name VARCHAR(200) NOT NULL,
+ url VARCHAR(200) NOT NULL UNIQUE,
+ title TEXT,
+ metadescription TEXT,
+ metakeywords TEXT,
+ description TEXT,
+ head TEXT,
+ navbar TEXT,
+ footer TEXT,
+ standardhead INTEGER,
+ standardnavbar INTEGER,
+ standardfooter INTEGER,
+ tags VARCHAR(1000),
+ category VARCHAR(1000),
+ date_start VARCHAR(100),
+ date_end VARCHAR(100),
+ views INTEGER,
+ public INTEGER,
+ changes INTEGER,
+ pubDate VARCHAR(100),
+ modified $2 not null default $1,
+ creation $2 not null default $1,
+ viewCount INTEGER NOT NULL default 1,
+ foreign key (author_id) references person(id)
+ );""".format(sql_now, sql_timestamp, sql_id))
+
+ filesTable = sql("""
+ create table if not exists files(
+ id $3 primary key,
+ url VARCHAR(1000) NOT NULL UNIQUE,
+ downloadCount integer NOT NULL default 1,
+ lastModified $2 NOT NULL default $1
+ );""".format(sql_now, sql_timestamp, sql_id))
+
proc generateDB*() =
- echo "Generating database"
+ info("Database: Generating database")
let
dict = loadConfig("config/config.cfg")
- db_user = dict.getSectionValue("Database","user")
- db_pass = dict.getSectionValue("Database","pass")
- db_name = dict.getSectionValue("Database","name")
- db_host = dict.getSectionValue("Database","host")
- db_folder = dict.getSectionValue("Database","folder")
- dbexists = if fileExists(db_host): true else: false
+ db_user = dict.getSectionValue("Database", "user")
+ db_pass = dict.getSectionValue("Database", "pass")
+ db_name = dict.getSectionValue("Database", "name")
+ db_host = dict.getSectionValue("Database", "host")
+ db_folder = dict.getSectionValue("Database", "folder")
+ dbexists =
+ when defined(postgres): db_host.len > 2
+ else: fileExists(db_host)
if dbexists:
- echo " - Database already exists. Inserting standard tables if they do not exist."
-
- # Creating folder
- discard existsOrCreateDir(db_folder)
-
- # Open DB
- echo " - Opening database"
- var db = open(connection=db_host, user=db_user, password=db_pass, database=db_name)
-
- if not db.tryExec(sql("""
- create table if not exists person(
- id integer primary key,
- name varchar(60) not null,
- password varchar(300) not null,
- email varchar(60) not null,
- creation timestamp not null default (STRFTIME('%s', 'now')),
- modified timestamp not null default (STRFTIME('%s', 'now')),
- salt varbin(128) not null,
- status varchar(30) not null,
- timezone VARCHAR(100),
- secretUrl VARCHAR(250),
- lastOnline timestamp not null default (STRFTIME('%s', 'now'))
- );""" % [TUserName, TPassword, TEmail]), []):
- echo " - Database: person table already exists"
-
-
-
-
- # -------------------- Session -------------------------------------------------
-
- if not db.tryExec(sql("""
- create table if not exists session(
- id integer primary key,
- ip inet not null,
- key $# not null,
- userid integer not null,
- lastModified timestamp not null default (STRFTIME('%s', 'now')),
- foreign key (userid) references person(id)
- );""" % [TPassword]), []):
- echo " - Database: session table already exists"
-
-
-
- # ----------------------- History -----------------------------------
-
- if not db.tryExec(sql"""
- create table if not exists history(
- id INTEGER primary key,
- user_id INTEGER NOT NULL,
- item_id INTEGER,
- element VARCHAR(100),
- choice VARCHAR(100),
- text VARCHAR(1000),
- creation timestamp not null default (STRFTIME('%s', 'now'))
- );""", []):
- echo " - Database: history table already exists"
-
-
-
- # ----------------------- Settings -----------------------------------
-
- if not db.tryExec(sql"""
- create table if not exists settings(
- id INTEGER primary key,
- analytics TEXT,
- head TEXT,
- footer TEXT,
- navbar TEXT,
- title TEXT,
- disabled INTEGER,
- blogorder TEXT,
- blogsort TEXT
- );""", []):
- echo " - Database: settings table already exists"
-
- # ----------------------- Pages ----------------------------------------------
-
- if not db.tryExec(sql"""
- create table if not exists pages(
- id INTEGER primary key,
- author_id INTEGER NOT NULL,
- status INTEGER NOT NULL,
- name VARCHAR(200) NOT NULL,
- url VARCHAR(200) NOT NULL UNIQUE,
- title TEXT,
- metadescription TEXT,
- metakeywords TEXT,
- description TEXT,
- head TEXT,
- navbar TEXT,
- footer TEXT,
- standardhead INTEGER,
- standardnavbar INTEGER,
- standardfooter INTEGER,
- tags VARCHAR(1000),
- category VARCHAR(1000),
- date_start VARCHAR(100) ,
- date_end VARCHAR(100) ,
- views INTEGER,
- public INTEGER,
- changes INTEGER,
- modified timestamp not null default (STRFTIME('%s', 'now')),
- creation timestamp not null default (STRFTIME('%s', 'now')),
-
- foreign key (author_id) references person(id)
- );""", []):
- echo " - Database: pages table already exists"
-
-
-
- # ----------------------- Blog ----------------------------------------------
-
- if not db.tryExec(sql"""
- create table if not exists blog(
- id INTEGER primary key,
- author_id INTEGER NOT NULL,
- status INTEGER NOT NULL,
- name VARCHAR(200) NOT NULL,
- url VARCHAR(200) NOT NULL UNIQUE,
- title TEXT,
- metadescription TEXT,
- metakeywords TEXT,
- description TEXT,
- head TEXT,
- navbar TEXT,
- footer TEXT,
- standardhead INTEGER,
- standardnavbar INTEGER,
- standardfooter INTEGER,
- tags VARCHAR(1000),
- category VARCHAR(1000),
- date_start VARCHAR(100) ,
- date_end VARCHAR(100) ,
- views INTEGER,
- public INTEGER,
- changes INTEGER,
- modified timestamp not null default (STRFTIME('%s', 'now')),
- creation timestamp not null default (STRFTIME('%s', 'now')),
-
- foreign key (author_id) references person(id)
- );""", []):
- echo " - Database:blog table already exists"
+ info("Database: Database already exists. Inserting standard tables if they do not exist.")
+
+ when not defined(postgres): discard existsOrCreateDir(db_folder) # Creating folder
+
+ info("Database: Opening database") # Open DB
+ var db =
+ when defined(postgres):
+ db_postgres.open(connection=db_host, user=db_user, password=db_pass, database=db_name)
+ else:
+ db_sqlite.open(db_host, "", "", "")
+
+ # User
+ if not db.tryExec(personTable):
+ info("Database: Person table already exists")
+
+ # Session
+ if not db.tryExec(sessionTable):
+ info("Database: Session table already exists")
+
+ # History
+ if not db.tryExec(historyTable):
+ info("Database: History table already exists")
+
+ # Settings
+ if not db.tryExec(settingsTable):
+ info("Database: Settings table already exists")
+
+ # Pages
+ if not db.tryExec(pagesTable):
+ info("Database: Pages table already exists")
+
+ # Blog
+ if not db.tryExec(blogTable):
+ info("Database: Blog table already exists")
+ # Files
+ if not db.tryExec(filesTable):
+ info("Database: Files table already exists")
if not dbexists:
- echo "Inserting standard elements"
+ info("Database: Inserting standard elements")
createStandardData(db)
- echo " - Database: Closing database"
+ info("Database: Closing database")
close(db)
diff --git a/nimwcpkg/resources/administration/help.nim b/nimwcpkg/resources/administration/help.nim
index 430d19b54..d395bfd5f 100644
--- a/nimwcpkg/resources/administration/help.nim
+++ b/nimwcpkg/resources/administration/help.nim
@@ -1,16 +1,18 @@
-# Copyright 2018 - Thomas T. Jarløv
-
-func commandLineHelp*(): string =
+func commandLineHelp*(): string {.inline.} =
return """
- _____________________________________
+ ∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽
- Nim Website Creator
- A quick website tool. Run the file and access your webpage.
+ Nim Website Creator 👑 https://NimWC.org
+ 2-Factor-Auth Self-Firejailing C-Speed Web Framework thats simple to use.
+ Run it, access your web, customize, add plugins, deploy today anywhere.
Commandline arguments:
- - newdb = Generates the database with standard tables (does **not** override or delete tables). `newdb` will be initialized automatic, if the no database exists.
- - newuser = Add the Admin user
- - insertdata = Insert standard data (this will override existing data)
- - help
- _____________________________________
+ 🔹 newdb = Generate the database with the standard tables.
+ Does not override or delete any tables.
+ Will be initialized automatically, if no database exists.
+ 🔹 newuser = Add 1 new Admin user to database.
+ 🔹 insertdata = Insert standard data to database (overrides existing data)
+ 🔹 help = Help and info for users.
+
+ ∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽∿∽
"""
diff --git a/nimwcpkg/resources/email/email_admin.nim b/nimwcpkg/resources/email/email_admin.nim
index 5b8d5fbe8..d990693d2 100644
--- a/nimwcpkg/resources/email/email_admin.nim
+++ b/nimwcpkg/resources/email/email_admin.nim
@@ -1,19 +1,18 @@
-import asyncdispatch, smtp, strutils, os, htmlparser, asyncnet, parsecfg
+import
+ asyncdispatch, smtp, strutils, os, htmlparser, asyncnet, parsecfg,
+ ../email/email_connection,
+ ../email/email_generate_message
-
-import ../email/email_connection
-import ../email/email_generate_message
+const AdminErrorMsg = """
+ Hi Admin
+
+ An error occurred.
+
+ $1
+
"""
proc sendEmailAdminError*(msg: string) {.async.} =
## Send email - user removed
-
- let message = """Hi Admin
-
-An error occurred.
-
-$1
-
-""" % [msg]
-
- await sendAdminMailNow("Admin: Error occurred", genEmailMessage(message))
+ await sendAdminMailNow("Admin: Error occurred",
+ genEmailMessage(AdminErrorMsg.format(msg)))
diff --git a/nimwcpkg/resources/email/email_connection.nim b/nimwcpkg/resources/email/email_connection.nim
index 9e2862083..06e7fa18d 100644
--- a/nimwcpkg/resources/email/email_connection.nim
+++ b/nimwcpkg/resources/email/email_connection.nim
@@ -1,85 +1,79 @@
-import asyncdispatch, smtp, strutils, os, htmlparser, asyncnet, parsecfg, times
+import
+ asyncdispatch, smtp, strutils, os, htmlparser, asyncnet, parsecfg, times, logging,
+ ../utils/logging_nimwc
# Changing app dir due to, that module is not imported from main module
setCurrentDir(getAppDir())
-var dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg")
+const otherHeaders = @[("Content-Type", "text/html; charset=\"UTF-8\"")]
-let smtpAddress = dict.getSectionValue("SMTP","SMTPAddress")
-let smtpPort = dict.getSectionValue("SMTP","SMTPPort")
-let smtpFrom = dict.getSectionValue("SMTP","SMTPFrom")
-let smtpUser = dict.getSectionValue("SMTP","SMTPUser")
-let smtpPassword = dict.getSectionValue("SMTP","SMTPPassword")
-let adminEmail = dict.getSectionValue("SMTP","SMTPEmailAdmin")
+let
+ dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg")
+ smtpAddress = dict.getSectionValue("SMTP", "SMTPAddress")
+ smtpPort = dict.getSectionValue("SMTP", "SMTPPort")
+ smtpFrom = dict.getSectionValue("SMTP", "SMTPFrom")
+ smtpUser = dict.getSectionValue("SMTP", "SMTPUser")
+ smtpPassword = dict.getSectionValue("SMTP", "SMTPPassword")
+ adminEmail = dict.getSectionValue("SMTP", "SMTPEmailAdmin")
proc sendMailNow*(subject, message, recipient: string) {.async.} =
## Send the email through smtp
-
when defined(demo):
- echo "Demo is true, email is not send"
-
+ info("Demo is true, email is not send")
when defined(dev) and not defined(devemailon):
- echo "Dev is true, email is not send"
+ info("Dev is true, email is not send")
return
- const otherHeaders = @[("Content-Type", "text/html; charset=\"UTF-8\"")]
-
- # Go Cx Manager
- var client = newAsyncSmtp(useSsl = true, debug = false)
- await client.connect(smtpAddress, Port(parseInt(smtpPort)))
- await client.auth(smtpUser, smtpPassword)
+ let
+ from_addr = smtpFrom
+ toList = @[recipient]
- let from_addr = smtpFrom
- let toList = @[recipient]
-
- var headers = otherHeaders
+ var
+ client = newAsyncSmtp(useSsl = true, debug = false)
+ headers = otherHeaders
headers.add(("From", from_addr))
let encoded = createMessage(subject, message, toList, @[], headers)
try:
+ await client.connect(smtpAddress, Port(parseInt(smtpPort)))
+ await client.auth(smtpUser, smtpPassword)
await client.sendMail(from_addr, toList, $encoded)
-
except:
- echo "Error in sending mail: " & recipient
+ info("Error in sending mail: " & recipient)
when defined(dev):
- echo "Email send"
-
+ info("Email sent")
proc sendAdminMailNow*(subject, message: string) {.async.} =
- ## Send the email through smtp
- ## Clean admin mailing
-
+ ## Send email only to Admin.
when defined(dev):
- echo "Dev is true, email is not send"
+ info("Dev is true, email is not sent")
return
-
if adminEmail == "":
- echo "No admin email specified"
+ info("No admin email specified")
return
- let recipient = adminEmail
let from_addr = adminEmail
- const otherHeaders = @[("Content-Type", "text/html; charset=\"UTF-8\"")]
- var client = newAsyncSmtp(useSsl = true, debug = false)
-
- await client.connect(smtpAddress, Port(parseInt(smtpPort)))
-
- await client.auth(smtpUser, smtpPassword)
-
- let toList = @[recipient]
-
- var headers = otherHeaders
+ var
+ headers = otherHeaders
+ client = newAsyncSmtp(useSsl = true, debug = false)
headers.add(("From", from_addr))
- let encoded = createMessage("Admin - " & subject, message,
- toList, @[], headers)
+ let
+ recipient = adminEmail
+ toList = @[recipient]
+ encoded = createMessage("Admin - " & subject, message, toList, @[], headers)
- await client.sendMail(from_addr, toList, $encoded)
+ try:
+ await client.connect(smtpAddress, Port(parseInt(smtpPort)))
+ await client.auth(smtpUser, smtpPassword)
+ await client.sendMail(from_addr, toList, $encoded)
+ except:
+ info("Error in sending mail: " & recipient)
when defined(dev):
- echo "Admin email send"
\ No newline at end of file
+ info("Admin email sent")
diff --git a/nimwcpkg/resources/email/email_generate_message.nim b/nimwcpkg/resources/email/email_generate_message.nim
index 5e0804213..a16ba2c8d 100644
--- a/nimwcpkg/resources/email/email_generate_message.nim
+++ b/nimwcpkg/resources/email/email_generate_message.nim
@@ -1,19 +1,14 @@
+import parsecfg, strutils, os
-import parsecfg
+let
+ dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg")
+ title = dict.getSectionValue("Server","title")
+ website = dict.getSectionValue("Server","website")
+ mailStyleHeader = """
+ As the final step in your registration, we require that you confirm your email
+ via the following link:
+
+ $5
+
+ To login use the details below. On your first login, please navigate to your settings and change your password!
+
+
Email: $3
+
+ Password:
+
+
+
+ Please do not hesitate to contact us at $8, if you have any questions.
+
+ Thank you for registering and becoming a part of $6!"""
+
+ registrationMsg = """
+
Hello $1
+
+ We are looking forward to see you at $3!
+ We have sent you an activation email with your password.
+ You just need to click on the link become a part of $3.
+ Get FreeOTP App at https://freeotp.github.io
+
+ Please do not hesitate to contact us at $5, if you have any questions.
+
+ Thank you for registering and becoming a part of $2!"""
+
+let
+ dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg")
+ title = dict.getSectionValue("Server","title")
+ website = dict.getSectionValue("Server","website")
+ supportEmail = dict.getSectionValue("SMTP","SMTPEmailSupport")
proc sendEmailActivationManual*(email, userName, password, activateUrl, invitorName: string) {.async.} =
## Send the activation email, when admin added a new user
-
- let message = """Hello $1,
-
-$2 has created a user account for you on $7.
-
-As the final step in your registration, we require that you confirm your email
-via the following link:
-
- $5
-
-To login use the details below. On your first login, please navigate to your settings and change your password!
-
-Email: $3
-
-Password: $4
-
-Please do not hesitate to contact us at $8, if you have any questions.
-
-Thank you for registering and becoming a part of $6!""" % [userName, invitorName, email, password, (website & activateUrl), title, website, supportEmail]
-
+ let message = activationMsg.format(
+ userName, invitorName, email, password,
+ (website & activateUrl), title, website, supportEmail)
await sendMailNow(title & " - Email Confirmation", genEmailMessage(message), email)
-
-
proc sendEmailRegistrationFollowup*(email, userName: string) {.async.} =
## Send a follow up mail, if user
## has not used their activation link
-
- let message = """Hello $1,
-
-We are looking forward to see you at $3! We have sent you an activation email with your password. You just need to click on the link become a part of $3.
-
-Please do not hesitate to contact us at $5, if you have any questions.
-
-Thank you for registering and becoming a part of $2!""" % [userName, title, website, supportEmail]
-
+ let message = registrationMsg.format(userName, title, website, supportEmail)
await sendMailNow(title & "- Reminder: Email Confirmation", genEmailMessage(message), email)
diff --git a/nimwcpkg/resources/files/files_efs.nim b/nimwcpkg/resources/files/files_efs.nim
index 807e87dd2..edd64313d 100644
--- a/nimwcpkg/resources/files/files_efs.nim
+++ b/nimwcpkg/resources/files/files_efs.nim
@@ -1,7 +1,4 @@
-import parsecfg, os, strutils, osproc, os, logging
-
-
-import ../utils/logging_nimwc
+import parsecfg, os, strutils, osproc, os, logging, ../utils/logging_nimwc
setCurrentDir(getAppDir().replace("/nimwcpkg", ""))
@@ -15,8 +12,9 @@ let
dict = loadConfig("config/config.cfg")
tempDir = dict.getSectionValue("Storage", section)
paths2create = [
- "files", "files/efs", "fileslocal", tempDir, tempDir & "/tmp", tempDir & "/files",
- tempDir & "/files/private", tempDir & "/files/public", tempDir & "/users",
+ "files", "files/efs", "fileslocal", tempDir, tempDir & "/tmp",
+ tempDir & "/files", tempDir & "/files/private",
+ tempDir & "/files/public", tempDir & "/users",
]
# Create folders
diff --git a/nimwcpkg/resources/files/files_utils.nim b/nimwcpkg/resources/files/files_utils.nim
index ba9cf3fe9..de745a14d 100644
--- a/nimwcpkg/resources/files/files_utils.nim
+++ b/nimwcpkg/resources/files/files_utils.nim
@@ -1,33 +1,23 @@
-import os, strutils, sequtils, asyncdispatch
+import os, strutils, sequtils, asyncdispatch, ../files/files_efs
-
-import ../files/files_efs
+const
+ filesListPrivatePath = storageEFS & "/files/private/*.*"
+ filesListPublicPath = storageEFS & "/files/public/*.*"
proc filesListPrivate*(): seq[string] =
## Get all filenames for project files
- result = @[]
-
- for file in walkFiles(storageEFS & "/files/private/*.*"):
+ for file in walkFiles(filesListPrivatePath):
result.add(file)
+
proc filesListPublic*(): seq[string] =
## Get all filenames for project files
- result = @[]
-
- for file in walkFiles(storageEFS & "/files/public/*.*"):
+ for file in walkFiles(filesListPublicPath):
result.add(file)
-proc filesListPublicFolderFiles*(): seq[string] =
- ## Get all filenames for project files
- result = @[]
-
- for file in walkFiles("public/files/*.*"):
- result.add(file)
-proc filesListPublicFolderImages*(): seq[string] =
+proc filesListPublicFolderFiles*(): seq[string] =
## Get all filenames for project files
- result = @[]
-
for file in walkFiles("public/images/*.*"):
result.add(file)
diff --git a/nimwcpkg/resources/password/password_generate.nim b/nimwcpkg/resources/password/password_generate.nim
index 287498e98..6c6a5acc3 100644
--- a/nimwcpkg/resources/password/password_generate.nim
+++ b/nimwcpkg/resources/password/password_generate.nim
@@ -1,16 +1,11 @@
-import md5, bcrypt
+import md5, bcrypt, ../password/salt_generate
-import ../password/salt_generate
-
-
-proc makeSessionKey*(): string =
+proc makeSessionKey*(): string {.inline.} =
## Creates a random key to be used to authorize a session.
- let random = makeSalt()
- return bcrypt.hash(random, genSalt(8))
+ bcrypt.hash(makeSalt(), genSalt(8))
-proc makePassword*(password, salt: string, comparingTo = ""): string =
- ## Creates an MD5 hash by combining password and salt
- let bcryptSalt = if comparingTo != "": comparingTo else: genSalt(8)
- result = hash(getMD5(salt & getMD5(password)), bcryptSalt)
\ No newline at end of file
+proc makePassword*(password, salt: string, comparingTo = ""): string {.inline.} =
+ ## Creates an MD5 hash by combining password and salt.
+ hash(getMD5(salt & getMD5(password)), if comparingTo != "": comparingTo else: genSalt(8))
diff --git a/nimwcpkg/resources/password/salt_generate.nim b/nimwcpkg/resources/password/salt_generate.nim
index 4799a0d09..b5f484d76 100644
--- a/nimwcpkg/resources/password/salt_generate.nim
+++ b/nimwcpkg/resources/password/salt_generate.nim
@@ -7,13 +7,12 @@ let useUrandom = urandom.open("/dev/urandom")
proc makeSalt*(): string =
## Generate random salt. Uses cryptographically secure /dev/urandom
## on platforms where it is available, and Nim's random module in other cases.
- result = ""
- if useUrandom:
+ if likely(useUrandom):
var randomBytes: array[0..127, char]
discard urandom.readBuffer(addr(randomBytes), 128)
for ch in randomBytes:
if ord(ch) in {32..126}:
result.add(ch)
- else:
+ else: # Fallback to Nim random when no /dev/urandom
for i in 0..127:
result.add(chr(rand(94) + 32)) # Generate numbers from 32 to 94 + 32 = 126
diff --git a/nimwcpkg/resources/session/user_data.nim b/nimwcpkg/resources/session/user_data.nim
index 3784b900f..7d4f69d8c 100644
--- a/nimwcpkg/resources/session/user_data.nim
+++ b/nimwcpkg/resources/session/user_data.nim
@@ -1,22 +1,20 @@
from jester import Request
-
type
- Rank* = enum
+ Rank* = enum ## Rank for the User.
User
Moderator
Admin
Deactivated
NotLoggedin
-type
Session* = object of RootObj
loggedIn*: bool
username*, userpass*, email*: string
-
+
TData* = ref object of Session
req*: Request
- userid*: string # User ID
- timezone*: string # User timezone
- rank*: Rank # User status (rank)
\ No newline at end of file
+ userid*: string ## User ID
+ timezone*: string ## User timezone
+ rank*: Rank ## User status (rank)
diff --git a/nimwcpkg/resources/utils/dates.nim b/nimwcpkg/resources/utils/dates.nim
deleted file mode 100644
index 522bca29d..000000000
--- a/nimwcpkg/resources/utils/dates.nim
+++ /dev/null
@@ -1,132 +0,0 @@
-import strutils, times, logging
-
-
-import ../utils/logging_nimwc
-
-
-const monthNames = ["", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
-
-
-proc currentDatetime*(formatting: string): string=
- ## Getting the current local time
-
- if formatting == "full":
- result = format(local(getTime()), "yyyy-MM-dd HH:mm:ss")
- elif formatting == "date":
- result = format(local(getTime()), "yyyy-MM-dd")
- elif formatting == "compact":
- result = format(local(getTime()), "yyyyMMdd")
- elif formatting == "year":
- result = format(local(getTime()), "yyyy")
- elif formatting == "month":
- result = format(local(getTime()), "MM")
- elif formatting == "day":
- result = format(local(getTime()), "dd")
- elif formatting == "time":
- result = format(local(getTime()), "HH:mm:ss")
-
-
-
-proc getDaysInMonthU*(month, year: int): int =
- ## Gets the number of days in the month and year
- ##
- ## Examples:
- ##
- runnableExamples:
- doAssert getDaysInMonthU(02, 2018) == 28
- doAssert getDaysInMonthU(10, 2020) == 31
- if month notin {1..12}:
- warn("getDaysInMonthU() wrong format input.")
- else:
- result = getDaysInMonth(Month(month), year)
-
-
-
-
-proc dateEpoch*(date, format: string): int64 =
- ## Transform a date in user format to epoch
- ## Does not utilize timezone
- ##
- ## Examples:
- ##
- runnableExamples:
- doAssert dateEpoch("2018-02-18", "YYYY-MM-DD") == "1518908400"
-
- try:
- case format
- of "YYYYMMDD":
- return toUnix(toTime(parse(date, "yyyyMMdd")))
- of "YYYY-MM-DD":
- return toUnix(toTime(parse(date, "yyyy-MM-dd")))
- of "YYYY-MM-DD HH:mm":
- return toUnix(toTime(parse(date, "yyyy-MM-dd HH:mm")))
- of "DD-MM-YYYY":
- return toUnix(toTime(parse(date, "dd-MM-yyyy")))
- else:
- warn("dateEpoch() wrong format input.")
- return 0
- except:
- warn("dateEpoch() failed.")
-
- return 0
-
-
-
-proc epochDate*(epochTime, format: string, timeZone = "0"): string =
- ## Transform epoch to user formatted date
- ##
- ## Examples:
- ##
- runnableExamples:
- doAssert epochDate("1522995050", "YYYY-MM-DD HH:mm", "2") == "2018-04-06 - 08:10"
-
-
- if epochTime == "":
- return ""
-
- try:
- case format
- of "YYYY":
- let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone)))
- return toTime.substr(0, 3)
-
- of "YYYY_MM_DD-HH_mm":
- let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone)))
- return toTime.substr(0, 3) & "_" & toTime.substr(5, 6) & "_" & toTime.substr(8, 9) & "-" & toTime.substr(11, 12) & "_" & toTime.substr(14, 15)
-
- of "YYYY MM DD":
- let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone)))
- return toTime.substr(0, 3) & " " & toTime.substr(5, 6) & " " & toTime.substr(8, 9)
-
- of "YYYY-MM-DD":
- let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone)))
- return toTime.substr(0, 9)
-
- of "YYYY-MM-DD HH:mm":
- let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone)))
- return toTime.substr(0, 9) & " - " & toTime.substr(11, 15)
-
- of "DD MM YYYY":
- let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone)))
- return toTime.substr(8, 9) & " " & toTime.substr(5, 6) & " " & toTime.substr(0, 3)
-
- of "DD":
- let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone)))
- return toTime.substr(8, 9)
-
- of "MMM DD":
- let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone)))
- return monthNames[parseInt(toTime.substr(5, 6))] & " " & toTime.substr(8, 9)
-
- of "MMM":
- let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone)))
- return monthNames[parseInt(toTime.substr(5, 6))]
-
- else:
- let toTime = $(utc(fromUnix(parseInt(epochTime))) + initTimeInterval(hours=parseInt(timeZone)))
- warn("epochDate() no input specified.")
- return toTime.substr(0, 9)
-
- except:
- error("epochDate() failed.")
- return ""
diff --git a/nimwcpkg/resources/utils/logging_nimwc.nim b/nimwcpkg/resources/utils/logging_nimwc.nim
index 2933451ac..f64e1d5b1 100644
--- a/nimwcpkg/resources/utils/logging_nimwc.nim
+++ b/nimwcpkg/resources/utils/logging_nimwc.nim
@@ -6,8 +6,8 @@ discard existsOrCreateDir("log")
let
dict = loadConfig(replace(getAppDir(), "/nimwcpkg", "") & "/config/config.cfg")
- fileDebug = dict.getSectionValue("Logging","logfiledev")
- fileProd = dict.getSectionValue("Logging","logfile")
+ fileDebug = dict.getSectionValue("Logging", "logfiledev")
+ fileProd = dict.getSectionValue("Logging", "logfile")
var
console_logger = newConsoleLogger(fmtStr = verboseFmtStr) # Logs to terminal.
diff --git a/nimwcpkg/resources/utils/plugins.nim b/nimwcpkg/resources/utils/plugins.nim
index ea53e300c..0c2ad9719 100644
--- a/nimwcpkg/resources/utils/plugins.nim
+++ b/nimwcpkg/resources/utils/plugins.nim
@@ -1,93 +1,67 @@
-# Copyright 2018 - Thomas T. Jarløv
-
import strutils, osproc, os, json
+const
+ pluginRepo = "https://github.com/ThomasTJdev/nimwc_plugins.git"
+ pluginRepoName = "nimwc_plugins"
+ pluginHtmlListItem = """
+
+
+
+
+
+
diff --git a/nimwcpkg/tmpl/main.tmpl b/nimwcpkg/tmpl/main.tmpl
index 9a038a386..f43138bbd 100644
--- a/nimwcpkg/tmpl/main.tmpl
+++ b/nimwcpkg/tmpl/main.tmpl
@@ -4,7 +4,7 @@
#proc genMainAdmin(c: var TData, data: string, pageAction = ""): string =
# result = ""
#
-# let title = getValue(db, sql"SELECT title FROM settings WHERE id = ?", "1")
+# let title = getValue(db, sql"SELECT title FROM settings")
@@ -93,7 +93,7 @@
#proc genMain(c: var TData, data: string, pageAction = ""): string =
# result = ""
#
-# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings WHERE id = ?", "1")
+# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings")
# let loggedIn = if c.loggedIn == true: "true" else: "false"
@@ -159,7 +159,7 @@ ${extensionCss()}
#proc genPage(c: var TData, pageid: string): string =
# result = ""
#
-# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings WHERE id = ?", "1")
+# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings")
#
#
#
@@ -236,7 +236,7 @@ ${extensionCss()}
#proc genPageBlog(c: var TData, blogid: string): string =
# result = ""
#
-# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings WHERE id = ?", "1")
+# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings")
#
#
# var status = "2"
@@ -245,7 +245,18 @@ ${extensionCss()}
# end if
#
# let pageData = getRow(db, sql("SELECT standardhead, head, standardnavbar, navbar, description, standardfooter, footer, name, status, title, metadescription, metakeywords FROM blog WHERE id = ? AND status IN (" & status & ")"), blogid)
+#
+# var viewCount: int
+# try:
+# viewCount = parseInt(getValue(db, sql"SELECT viewCount FROM blog WHERE id = ?", blogid))
+# except:
+# viewCount = 0
+# end try
+# inc viewCount
+# exec(db, sql"UPDATE blog SET viewCount = ? WHERE id = ?", viewCount, blogid)
+#
# let loggedIn = if c.loggedIn == true: "true" else: "false"
+#
diff --git a/nimwcpkg/tmpl/page.tmpl b/nimwcpkg/tmpl/page.tmpl
index 036d08fd2..2bc953a94 100644
--- a/nimwcpkg/tmpl/page.tmpl
+++ b/nimwcpkg/tmpl/page.tmpl
@@ -41,4 +41,4 @@
# end if
-#end proc
\ No newline at end of file
+#end proc
diff --git a/nimwcpkg/tmpl/pageedit.tmpl b/nimwcpkg/tmpl/pageedit.tmpl
index b2066c0a9..9d00b23f1 100644
--- a/nimwcpkg/tmpl/pageedit.tmpl
+++ b/nimwcpkg/tmpl/pageedit.tmpl
@@ -51,8 +51,8 @@
+ Plugins can do everything you want, HTML, CSS, JS, Nim, Canvas, WebGL, WASM, JavaScript Frameworks, use Dabatase etc.
+
+ The Store only needs a Git URL so it can be Open Source or Private or Payed Plugins,
+ let NimWC be part of your Bussiness and Entrepreneurships.
+
#end proc
diff --git a/nimwcpkg/tmpl/serverinfo.tmpl b/nimwcpkg/tmpl/serverinfo.tmpl
index b1734fce4..1451a7a2a 100644
--- a/nimwcpkg/tmpl/serverinfo.tmpl
+++ b/nimwcpkg/tmpl/serverinfo.tmpl
@@ -1,40 +1,83 @@
#? stdtmpl | standard
#
-#import encodings, httpclient, nativesockets
+#import httpclient #HACK: Do NOT move to main,leave it here.
#
#proc genServerInfo(): string =
# result = ""
-
-
Server Info
-
-
+#
+#
+# when defined(demo):
+# const uname = " Not available on Demo "
+# const distr = " Not available on Demo "
+# const uptim = " Not available on Demo "
+# const pubip = " Not available on Demo "
+# const disks = " Not available on Demo "
+# const hostn = " Not available on Demo "
+# const jailv = " Not available on Demo "
+# const jailf = " Not available on Demo "
+# else:
+# let hostn = getHostname()
+# let uptim = execCmdEx("uptime --pretty").output.strip
+# let disks = execCmdEx("df --human-readable --local --output=avail " & getCurrentDir()).output.strip
+# let jailf = when defined(firejail): $firejailFeatures.pretty.strip else: " Firejail is Disabled "
+# const uname = staticExec("uname -a").strip
+# const distr = staticExec("lsb_release -a").strip
+# const jailv = when defined(firejail): $firejailVersion else: " Firejail is Disabled "
+# let pubip = newHttpClient().getContent("http://api.ipify.org").strip
+# end when
+#
+#
+
+
+ # end when
+
# end if
+ # when defined(demo):
+
+
+ Some options are disabled on Demo!.
+
+
+ # end when
+
@@ -113,24 +155,20 @@
-
-
HTML <head>
-
${xmlEncode(head)}
+
HTML <head>
-
HTML <header> + <navbar>
-
${xmlEncode(navbar)}
+
HTML <header> & <navbar>
-
HTML <footer>
-
${xmlEncode(footer)}
+
HTML <footer>
diff --git a/nimwcpkg/tmpl/tos.html b/nimwcpkg/tmpl/tos.html
new file mode 100644
index 000000000..baaa72013
--- /dev/null
+++ b/nimwcpkg/tmpl/tos.html
@@ -0,0 +1,40 @@
+
+
Terms Of Service
+
+
These terms and conditions outline the rules and regulations for the use of This Website.
+
+
+ By accessing this website we assume you accept these terms and conditions in full.
+
+
+ Do not continue to use this web if you do not accept all of the terms and conditions stated on this page.
+
+
+
Cookies
+
+
We may or may not use Cookies. By using this web you consent to the use of cookies.
+
+
License
+
+
You must not Re-License material from this web.
+
+
User Comments
+
+
This Website reserves the right to remove any Comments which it considers inappropriate.
+
+
Approved organizations may hyperlink to our Web.
+
+
Content Liability
+
+
We shall have no responsibility or liability for any content appearing on this Web.
+
+
Disclaimer
+
+
This web is not liable for any loss or damage of any nature under any circunstance.
+
+
Thank you for reading.
+
+
+
+
+
diff --git a/nimwcpkg/tmpl/user.tmpl b/nimwcpkg/tmpl/user.tmpl
index a7d6fc272..401b35196 100644
--- a/nimwcpkg/tmpl/user.tmpl
+++ b/nimwcpkg/tmpl/user.tmpl
@@ -9,7 +9,7 @@
# result = ""
# if not c.loggedIn:
#
-# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings WHERE id = ?", "1")
+# let standardElements = getRow(db, sql"SELECT head, navbar, footer, title FROM settings")
${standardElements[0]}
@@ -22,8 +22,9 @@
# when defined(demo):
-
User: test@test.com
-
Pass: test
+
User: test@test.com
+
Pass: test
+
2FA: 123456
# end when
@@ -44,22 +45,47 @@
-
+
+
+
+
+
+
-
-
#if useCaptcha:
#end if
+
+
+
+
+
+
+
+ ## DONT TOUCH, HoneyPot: https://github.com/ThomasTJdev/nim_websitecreator/issues/43#issue-403507393
+
+ ## DONT TOUCH, HoneyPot: https://stackoverflow.com/questions/36227376/better-honeypot-implementation-form-anti-spam/36227377
@@ -82,7 +108,7 @@
#proc genUsers(c: var TData): string =
# result = ""
#
-# let allUsers = getAllRows(db, sql"SELECT id, name, email, status, lastOnline, secretUrl FROM person")
+# let allUsers = getAllRows(db, sql"SELECT id, name, email, status, lastOnline, secretUrl, twofa FROM person")
@@ -124,20 +150,24 @@
#
+
ID
User
Mail
Last online
Rank
+
2FA
Delete
#
+
ID
User
Mail
Last online
Rank
+
2FA
Delete
@@ -152,6 +182,7 @@
# counter += 1
$counter
+
${user[0]}
${user[1]}
${user[2]}
# if user[5] == "":
@@ -161,6 +192,11 @@
Mail unconfirmed
Mail unconfirmed
# end if
+
+ # if c.rank == Admin:
+ ${toUpperAscii($(user[6].len > 6))}
+ # end if
+
# end for
@@ -180,7 +216,7 @@
#proc genUsersProfile(c: var TData): string =
# result = ""
#
-# let userData = getAllRows(db, sql"SELECT id, name, email, status, lastOnline FROM person WHERE id = ?", c.userid)
+# let userData = getAllRows(db, sql"SELECT id, name, email, status, lastOnline, twofa FROM person WHERE id = ?", c.userid)
@@ -209,12 +245,62 @@
Open your 2FA App and insert the code below. Test the code in input field below - on successful result, press "Save 2FA". You can Enable, Disable and Reset it at any time.
diff --git a/nimwcpkg/tmpl/utils.tmpl b/nimwcpkg/tmpl/utils.tmpl
index 4ccdcf932..5496aa68a 100644
--- a/nimwcpkg/tmpl/utils.tmpl
+++ b/nimwcpkg/tmpl/utils.tmpl
@@ -100,9 +100,6 @@
# result = ""
-
-
-
@@ -135,8 +132,23 @@
# var metakeywords = ""
# var category = ""
# var tags = ""
+# var pubDate = currentDatetime("date")
+# var viewCount = "0"
#
-# if edit:
+# if edit and blog:
+# let pageOrBlog = if page == true: "pages" else: "blog"
+# let details = getRow(db, sql("SELECT title, metadescription, metakeywords, category, tags, pubDate, creation, viewCount FROM " & pageOrBlog & " WHERE id = ?"), pageid)
+#
+# title = details[0]
+# metadescription = details[1]
+# metakeywords = details[2]
+# category = details[3]
+# tags = details[4]
+# pubDate = if details[5] != "": details[5] else: epochDate(details[6], "YYYY-MM-DD")
+# viewCount = details[7]
+# end if
+#
+# if edit and page:
# let pageOrBlog = if page == true: "pages" else: "blog"
# let details = getRow(db, sql("SELECT title, metadescription, metakeywords, category, tags FROM " & pageOrBlog & " WHERE id = ?"), pageid)
#
@@ -151,18 +163,42 @@
Change editor
-
+
-
+
-
+
# end if
+# if blog:
+
Customize blog
+
+
+
+
+
+
+ If no date is specified, the creation date will be used. The date has no effect and will only be shown on the blog overview page. Format the date: YYYY-MM-DD
+
Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.
Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.