initial commit in fresh repo

This commit is contained in:
adueck 2024-08-14 15:30:10 -04:00
commit 8b188ce088
267 changed files with 125555 additions and 0 deletions

5
.firebaserc Normal file
View File

@ -0,0 +1,5 @@
{
"projects": {
"default": "lingdocs"
}
}

14
.github/FUNDING.yml vendored Normal file
View File

@ -0,0 +1,14 @@
# These are supported funding model platforms
github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry
polar: # Replace with a single Polar username
buy_me_a_coffee: lingdocsdev
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']

58
.github/workflows/deploy-account.yml vendored Normal file
View File

@ -0,0 +1,58 @@
name: deploy account
on:
push:
branches:
- master
- dev
paths:
- "account/**"
- ".github/workflows/deploy-account.yml"
workflow_dispatch:
jobs:
new-deploy-account:
name: Deploy
runs-on: ubuntu-latest
env:
LINGDOCS_NPM_TOKEN: ${{ secrets.LINGDOCS_NPM_TOKEN }}
steps:
- uses: actions/checkout@v3
- name: Cache NPM deps
uses: actions/cache@v3
# TODO: for some reason this cache is not helping
with:
key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }}
path: ~/.npm
- run: |
npm install
# TODO: could save a bunch of install time by not requiring ps-react in the website/account-types
cd website
npm install
cd ..
cd account
npm install
npm run build
npm prune --production
cd ..
tar --exclude-vcs -czf account.tar.gz account
- name: copy tarball to server
uses: appleboy/scp-action@v0.1.4
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
port: ${{ secrets.PORT }}
key: ${{ secrets.KEY }}
source: "account.tar.gz"
target: "."
- name: unpack tarball and restart app
uses: appleboy/ssh-action@v1.0.0
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.KEY }}
port: ${{ secrets.PORT }}
script: |
rm -rf apps/live/account
tar -xzf account.tar.gz -C ~/apps/live
rm account.tar.gz
pm2 restart account

34
.github/workflows/deploy-functions.yml vendored Normal file
View File

@ -0,0 +1,34 @@
name: Deploy Functions
on:
push:
branches:
- master
paths:
- "functions/**"
- ".github/workflows/deploy-functions.yml"
workflow_dispatch:
jobs:
deploy-functions:
runs-on: ubuntu-latest
env:
LINGDOCS_NPM_TOKEN: ${{ secrets.LINGDOCS_NPM_TOKEN }}
FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
- run: npm install -g firebase-tools
- run: |
cp .npmrc functions
cd website
npm install
cd ..
cd functions
npm install
- name: deploy functions and hosting routes
run: firebase deploy -f --token ${FIREBASE_TOKEN}

43
.github/workflows/functions-ci.yml vendored Normal file
View File

@ -0,0 +1,43 @@
name: Functions CI
on:
push:
branches:
- master
paths:
- "functions/**"
- ".github/workflows/functions-ci.yml"
workflow_dispatch:
jobs:
build-and-serve-functions:
runs-on: ubuntu-latest
env:
LINGDOCS_NPM_TOKEN: ${{ secrets.LINGDOCS_NPM_TOKEN }}
FIREBASE_TOKEN: ${{ secrets.FIREBASE_TOKEN }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
- run: npm install -g firebase-tools
- name: build functions
run: |
cp .npmrc functions
cd website
npm install
cd ..
cd functions
npm install
npm run build
- name: start up emulator once
run: |
cd functions
firebase functions:config:get --token ${FIREBASE_TOKEN} > .runtimeconfig.json
echo '#!/bin/bash' > empty.sh
chmod +x empty.sh
firebase emulators:exec ./empty.sh --only functions --token ${FIREBASE_TOKEN}
rm .runtimeconfig.json
rm empty.sh

31
.github/workflows/publish-types.yml vendored Normal file
View File

@ -0,0 +1,31 @@
name: Publish Types
on:
push:
branches: ["master"]
workflow_dispatch:
jobs:
publish:
runs-on: ubuntu-latest
env:
LINGDOCS_NPM_TOKEN: ${{ secrets.LINGDOCS_NPM_TOKEN }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
- name: Check if version has been updated
id: check
uses: EndBug/version-check@v2
with:
diff-search: true
token: ${{ secrets.GITHUB_TOKEN }}
- name: Publish when version changed
if: steps.check.outputs.changed == 'true'
run: |
npm install
npm run build
npm publish

35
.github/workflows/website-ci.yml vendored Normal file
View File

@ -0,0 +1,35 @@
name: Website CI
on:
push:
branches:
- master
paths:
- "website/**"
- ".github/workflows/website-ci.yml"
pull_request:
branches: ["*"]
paths:
- "website/**"
- ".github/workflows/website-ci.yml"
workflow_dispatch:
jobs:
build-and-test:
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./website
env:
LINGDOCS_NPM_TOKEN: ${{ secrets.LINGDOCS_NPM_TOKEN }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: "npm"
- run: |
npm install
npm run build
npm run test

99
.gitignore vendored Normal file
View File

@ -0,0 +1,99 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
firebase-debug.log*
firebase-debug.*.log*
# Firebase cache
.firebase/
# Types Dist
dist
# Firebase config
# Uncomment this if you'd like others to create their own Firebase project.
# For a team working on the same Firebase project(s), it is recommended to leave
# it commented so all members can deploy to the same project(s) in .firebaserc.
# .firebaserc
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
# nyc test coverage
.nyc_output
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (http://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
# Firebase functions config/env for running functions locally
.runtimeconfig.json
# General
.DS_Store
.AppleDouble
.LSOverride
# Icon must end with two \r
Icon
# Thumbnails
._*
# Files that might appear in the root of a volume
.DocumentRevisions-V100
.fseventsd
.Spotlight-V100
.TemporaryItems
.Trashes
.VolumeIcon.icns
.com.apple.timemachine.donotpresent
# Directories potentially created on remote AFP share
.AppleDB
.AppleDesktop
Network Trash Folder
Temporary Items
.apdisk

2
.npmrc Normal file
View File

@ -0,0 +1,2 @@
@lingdocs:registry=https://npm.lingdocs.com
//npm.lingdocs.com/:_authToken=${LINGDOCS_NPM_TOKEN}

673
LICENSE Normal file
View File

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

BIN
LingDocsLogo-Complex.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 MiB

BIN
LingDocsLogoSimple.pxd Normal file

Binary file not shown.

239
README.md Normal file
View File

@ -0,0 +1,239 @@
# LingDocs Dictionary Monorepo
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
[![Netlify Status](https://api.netlify.com/api/v1/badges/65b633a2-f123-4fcd-91bc-5e6acda43256/deploy-status)](https://app.netlify.com/sites/lingdocs-dictionary/deploys)
![Website CI](https://github.com/lingdocs/lingdocs-main/actions/workflows/website-ci.yml/badge.svg)
![Functions CI](https://github.com/lingdocs/lingdocs-main/actions/workflows/functions-ci.yml/badge.svg)
![Account Deploy](https://github.com/lingdocs/lingdocs-main/actions/workflows/deploy-account.yml/badge.svg)
![Functions Deploy](https://github.com/lingdocs/lingdocs-main/actions/workflows/deploy-functions.yml/badge.svg)
![LingDocs Logo](./website/public/icons/icon-w-name.png)
## Contents
This monorepo contains:
- `/dictionary-client` the frontend of the dictionary, a React SPA
- `/account` a backend authentication server
- `/functions` backend Firebase functions for use with the dictionary
To update the `@lingdocs/pashto-inflector` dependency accross the project you can use the shell script included:
```sh
./update-inflector.sh [version]
```
### Dictionary Client
SPA Dictionary Frontend
Use [Yarn](https://yarnpkg.com/).
```sh
cd website
yarn install
```
#### Development
```sh
yarn start
```
### Account
Backend authentication server build on express / passport
#### Development
Use [npm](https://www.npmjs.com/).
```sh
cd account
npm install
npm run dev
```
### Functions
Backend Firebase functions
Use [npm](https://www.npmjs.com/).
```sh
cd functions
npm install
```
#### Development
```sh
firebase login
# get envars locally
firebase functions:config:get > .runtimeconfig.json
# start functions emulator
npm run serve
```
## Architecture
![LingDocs Pashto Dictioanry App Architecture](./architecture.svg)
### Source Layer
#### GitHub Git Repo
The monorepo contains both a `website` folder for the frontend PWA and a `functions` folder for the backend functions. Both parts are written in TypeScript and are tied together using the types found in the `@lingdocs/pashto-inflector` package used by both as well as the types found in `./website/src/lib/backend-types.ts`
##### `./website` frontend
The front-end website code in `./website` is made with `create-react-app` and written in typescript with `jest` testing. It is a SPA and PWA.
The deployment is done automatically by netlify upon pushing to the `master` branch.
##### `./functions` backend
The backend code found in `./functions` and is written in TypeScript.
It is compiled and deployed automatically by the repo's GitHub Actions to Firebase Cloud Functions upon pushing to the `master` branch.
#### Google Sheets Dictionary Source
The content of the dictionary is based on a Google Sheets documents containing rows with the information for each dictionary entry. This can be edited by an editor directly, or through the website frontend with editor priveledges.
A cloud function in the backend compiles the dictionary into binary form (protobuf) then uploads it into a Google Cloud Storage bucket. The deployment is triggered from the website by an editor.
### Backend Layer
#### Firebase Functions
Serverless functions are used in conjungtion with Firebase Authentication to:
- check if a user has elevated priveledges
- receive edits or suggestions for the dictionary
- compile and publish the dictionary
- create and clean up elevated users in the CouchDB database
#### Account Server
Deployed through a self-hosted actions runner. It runs on an Ubuntu 20.04 machine and it requries `node` and `redis`.
The runner is launched by this line in a crontab
```
@reboot ./actions-runner/run.sh
```
Process managed by pm2 using this `ecosystem.config.js`
```
module.exports = {
apps : [{
name : "account",
cwd : "./actions-runner/_work/lingdocs-main/lingdocs-main/account",
script: "npm",
args: "start",
env: {
NODE_ENVIRONMENT: "************",
LINGDOCS_EMAIL_HOST: "**************",
LINGDOCS_EMAIL_USER: "**************",
LINGDOCS_EMAIL_PASS: "*****************",
LINGDOCS_COUCHDB: "****************",
LINGDOCS_ACCOUNT_COOKIE_SECRET: "******************",
LINGDOCS_ACCOUNT_GOOGLE_CLIENT_SECRET: "******************",
LINGDOCS_ACCOUNT_TWITTER_CLIENT_SECRET: "******************",
LINGDOCS_ACCOUNT_GITHUB_CLIENT_SECRET: "******************",
LINGDOCS_ACCOUNT_RECAPTCHA_SECRET: "6LcVjAUcAAAAAPWUK-******************",
}
}]
}
```
```sh
pm2 start ecosystem.config.js
pm2 save
```
Put behind a NGINX reverse proxy with this config (encryption by LetsEncrypt)
```
server {
server_name account.lingdocs.com;
location / {
proxy_pass http://localhost:4000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Access-Control-Allow-Origin *;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
error_page 500 /500.json;
location /500.json {
return 500 '{"ok":false,"error":"500 Internal Server Error"}';
}
error_page 502 /502.json;
location /502.json {
return 502 '{"ok":false,"error":"502 Bad Gateway"}';
}
error_page 503 /503.json;
location /503.json {
return 503 '{"ok":false,"error":"503 Service Temporarily Unavailable"}';
}
error_page 504 /504.json;
location /504.json {
return 504 '{"ok":false,"error":"504 Gateway Timeout"}';
}
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/account.lingdocs.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/account.lingdocs.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = account.lingdocs.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
server_name account.lingdocs.com;
listen 80;
listen [::]:80;
return 404; # managed by Certbot
}
```
#### CouchDB
When a user upgrades their account level to `student` or `editor`:
1. A doc in the `_users` db is created with their Firebase Authentication info, account level, and a password they can use for syncing their personal wordlistdb
2. A user database is created which they use to sync their personal wordlist.
There is also a `review-tasks` database which is used to store all the review tasks for editors and syncs with the review tasks in the app for the editor(s).
#### Google Cloud Storage
Contains:
- `dict` - the dictionary content in protobuf format
- `dict-info` - information about the version of the currently available dictionary in protobuf format
The website fetches `dict-info` and `dict` as needed to check for the latest dictionary version and download it into memory/`lokijs`.
### Frontend Layer
#### PWA
The frontend is a static-site PWA/SPA built with `create-react-app` (React/TypeScript) and deployed to Netlify.

2
account/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
node_modules
sessions

112
account/check-couchdb.ts Normal file
View File

@ -0,0 +1,112 @@
#!/usr/bin/env tsx
// a script for making edits to the couchdb records - run with tsnode
import Nano from "nano";
import { DocumentInsertResponse } from "nano";
import env from "./src/lib/env-vars";
import * as T from "../website/src/types/account-types";
import {
addCouchDbAuthUser,
generateWordlistDbPassword,
getAllLingdocsUsers,
getLingdocsUser,
insertLingdocsUser,
updateLingdocsUser,
} from "./src/lib/couch-db";
const nano = Nano(env.couchDbURL);
// const usersDb = nano.db.use("lingdocs-users");
// const userDbPrefix = "userdb-";
function processAPIResponse(
user: T.LingdocsUser,
response: DocumentInsertResponse
): T.LingdocsUser | undefined {
if (response.ok !== true) return undefined;
return {
...user,
_id: response.id,
_rev: response.rev,
};
}
async function main() {
const users = await getAllLingdocsUsers();
const usersWDbs = users.filter((x) => x.level !== "basic");
for (let user of usersWDbs) {
// if (!user.docs.length) return;
// const u = user.docs[0];
// await authUsers.destroy(u._id, u._rev);
if (user.level === "basic") {
throw new Error("");
}
process.stdout.write(
`Checking for _user for ${user.name} - ${user.email}...`
);
const uzrs = nano.db.use("_users");
const r = await uzrs.find({
selector: { _id: `org.couchdb.user:${user.userId}` },
});
console.log(r.docs.length ? "✅" : "❌");
if (!r.docs.length) {
console.log(`Creating wordlist db for ${user.name} - ${user.email}...`);
const { password, userDbName } = await addCouchDbAuthUser(user.userId);
await updateLingdocsUser(user.userId, {
couchDbPassword: password,
wordlistDbName: userDbName,
});
}
process.stdout.write(`Checking for db for ${user.name} - ${user.email}...`);
const userDb = nano.db.use(user.wordlistDbName);
try {
// await userDb.insert(
// {
// admins: {
// names: [user.userId],
// roles: ["_admin"],
// },
// members: {
// names: [user.userId],
// roles: ["_admin"],
// },
// },
// "_security"
// );
const { admins, members } = await userDb.get("_security");
if (
admins?.names?.[0] === user.userId &&
members?.names?.[0] === user.userId
) {
console.log("✅");
} else {
console.log("check", user.wordlistDbName);
console.log("uid", user.userId);
console.log("RR");
}
} catch (e) {
// console.log(e);
console.log("❌");
console.log(`needs ${user.wordlistDbName} - ${user.userId}`);
}
}
const allDbs = await nano.db.list();
const strayDbs = allDbs.reduce<string[]>((acc, curr) => {
if (!curr.startsWith("userdb-")) {
return acc;
}
if (
!usersWDbs.some((x) => x.level !== "basic" && x.wordlistDbName === curr)
) {
return [...acc, curr];
}
return acc;
}, []);
console.log("STRAY USERDBS");
console.log(strayDbs);
return "done";
}
main().then((res) => {
console.log(res);
});

5968
account/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

63
account/package.json Normal file
View File

@ -0,0 +1,63 @@
{
"name": "lingdocs-account",
"version": "1.0.0",
"description": "",
"main": "dist/account/src/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "ts-node-dev --files src/index.ts",
"build": "tsc",
"start": "NODE_ENV=production node ."
},
"author": "lingdocs.com",
"license": "ISC",
"dependencies": {
"@lingdocs/inflect": "7.6.5",
"base64url": "^3.0.1",
"bcryptjs": "^2.4.3",
"connect-redis": "^6.0.0",
"cors": "^2.8.5",
"cron": "^2.1.0",
"crypto": "^1.0.1",
"ejs": "^3.1.6",
"express": "^4.17.2",
"express-session": "^1.17.2",
"lokijs": "^1.5.12",
"nano": "^9.0.3",
"next": "^13.4.12",
"node-fetch": "^2.6.7",
"nodemailer": "^6.6.3",
"passport": "^0.4.1",
"passport-github2": "^0.1.12",
"passport-google-oauth": "^2.0.0",
"passport-local": "^1.0.0",
"passport-twitter": "^1.0.4",
"pug": "^3.0.2",
"redis": "^3.1.2",
"session-file-store": "^1.5.0",
"stripe": "^10.13.0",
"uuid": "^8.3.2"
},
"devDependencies": {
"@types/base64url": "^2.0.0",
"@types/bcryptjs": "^2.4.2",
"@types/cors": "^2.8.12",
"@types/cron": "^2.0.0",
"@types/express": "^4.17.13",
"@types/express-session": "^1.17.4",
"@types/lokijs": "^1.5.8",
"@types/node": "^16.6.0",
"@types/node-fetch": "^2.5.12",
"@types/nodemailer": "^6.4.4",
"@types/passport-github2": "^1.2.5",
"@types/passport-google-oauth": "^1.0.42",
"@types/passport-local": "^1.0.34",
"@types/passport-twitter": "^1.0.37",
"@types/redis": "^2.8.31",
"@types/uuid": "^8.3.1",
"ts-node": "^10.1.0",
"ts-node-dev": "^2.0.0",
"tsx": "^4.17.0",
"typescript": "^5.3.2"
}
}

4997
account/public/css/bootstrap-grid.css vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

4996
account/public/css/bootstrap-grid.rtl.css vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

427
account/public/css/bootstrap-reboot.css vendored Normal file
View File

@ -0,0 +1,427 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
@media (prefers-reduced-motion: no-preference) {
:root {
scroll-behavior: smooth;
}
}
body {
margin: 0;
font-family: var(--bs-body-font-family);
font-size: var(--bs-body-font-size);
font-weight: var(--bs-body-font-weight);
line-height: var(--bs-body-line-height);
color: var(--bs-body-color);
text-align: var(--bs-body-text-align);
background-color: var(--bs-body-bg);
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
hr {
margin: 1rem 0;
color: inherit;
background-color: currentColor;
border: 0;
opacity: 0.25;
}
hr:not([size]) {
height: 1px;
}
h6, h5, h4, h3, h2, h1 {
margin-top: 0;
margin-bottom: 0.5rem;
font-weight: 500;
line-height: 1.2;
}
h1 {
font-size: calc(1.375rem + 1.5vw);
}
@media (min-width: 1200px) {
h1 {
font-size: 2.5rem;
}
}
h2 {
font-size: calc(1.325rem + 0.9vw);
}
@media (min-width: 1200px) {
h2 {
font-size: 2rem;
}
}
h3 {
font-size: calc(1.3rem + 0.6vw);
}
@media (min-width: 1200px) {
h3 {
font-size: 1.75rem;
}
}
h4 {
font-size: calc(1.275rem + 0.3vw);
}
@media (min-width: 1200px) {
h4 {
font-size: 1.5rem;
}
}
h5 {
font-size: 1.25rem;
}
h6 {
font-size: 1rem;
}
p {
margin-top: 0;
margin-bottom: 1rem;
}
abbr[title],
abbr[data-bs-original-title] {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
cursor: help;
-webkit-text-decoration-skip-ink: none;
text-decoration-skip-ink: none;
}
address {
margin-bottom: 1rem;
font-style: normal;
line-height: inherit;
}
ol,
ul {
padding-left: 2rem;
}
ol,
ul,
dl {
margin-top: 0;
margin-bottom: 1rem;
}
ol ol,
ul ul,
ol ul,
ul ol {
margin-bottom: 0;
}
dt {
font-weight: 700;
}
dd {
margin-bottom: 0.5rem;
margin-left: 0;
}
blockquote {
margin: 0 0 1rem;
}
b,
strong {
font-weight: bolder;
}
small {
font-size: 0.875em;
}
mark {
padding: 0.2em;
background-color: #fcf8e3;
}
sub,
sup {
position: relative;
font-size: 0.75em;
line-height: 0;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
a {
color: #0d6efd;
text-decoration: underline;
}
a:hover {
color: #0a58ca;
}
a:not([href]):not([class]), a:not([href]):not([class]):hover {
color: inherit;
text-decoration: none;
}
pre,
code,
kbd,
samp {
font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
font-size: 1em;
direction: ltr /* rtl:ignore */;
unicode-bidi: bidi-override;
}
pre {
display: block;
margin-top: 0;
margin-bottom: 1rem;
overflow: auto;
font-size: 0.875em;
}
pre code {
font-size: inherit;
color: inherit;
word-break: normal;
}
code {
font-size: 0.875em;
color: #d63384;
word-wrap: break-word;
}
a > code {
color: inherit;
}
kbd {
padding: 0.2rem 0.4rem;
font-size: 0.875em;
color: #fff;
background-color: #212529;
border-radius: 0.2rem;
}
kbd kbd {
padding: 0;
font-size: 1em;
font-weight: 700;
}
figure {
margin: 0 0 1rem;
}
img,
svg {
vertical-align: middle;
}
table {
caption-side: bottom;
border-collapse: collapse;
}
caption {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
color: #6c757d;
text-align: left;
}
th {
text-align: inherit;
text-align: -webkit-match-parent;
}
thead,
tbody,
tfoot,
tr,
td,
th {
border-color: inherit;
border-style: solid;
border-width: 0;
}
label {
display: inline-block;
}
button {
border-radius: 0;
}
button:focus:not(:focus-visible) {
outline: 0;
}
input,
button,
select,
optgroup,
textarea {
margin: 0;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
button,
select {
text-transform: none;
}
[role=button] {
cursor: pointer;
}
select {
word-wrap: normal;
}
select:disabled {
opacity: 1;
}
[list]::-webkit-calendar-picker-indicator {
display: none;
}
button,
[type=button],
[type=reset],
[type=submit] {
-webkit-appearance: button;
}
button:not(:disabled),
[type=button]:not(:disabled),
[type=reset]:not(:disabled),
[type=submit]:not(:disabled) {
cursor: pointer;
}
::-moz-focus-inner {
padding: 0;
border-style: none;
}
textarea {
resize: vertical;
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
float: left;
width: 100%;
padding: 0;
margin-bottom: 0.5rem;
font-size: calc(1.275rem + 0.3vw);
line-height: inherit;
}
@media (min-width: 1200px) {
legend {
font-size: 1.5rem;
}
}
legend + * {
clear: left;
}
::-webkit-datetime-edit-fields-wrapper,
::-webkit-datetime-edit-text,
::-webkit-datetime-edit-minute,
::-webkit-datetime-edit-hour-field,
::-webkit-datetime-edit-day-field,
::-webkit-datetime-edit-month-field,
::-webkit-datetime-edit-year-field {
padding: 0;
}
::-webkit-inner-spin-button {
height: auto;
}
[type=search] {
outline-offset: -2px;
-webkit-appearance: textfield;
}
/* rtl:raw:
[type="tel"],
[type="url"],
[type="email"],
[type="number"] {
direction: ltr;
}
*/
::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-color-swatch-wrapper {
padding: 0;
}
::file-selector-button {
font: inherit;
}
::-webkit-file-upload-button {
font: inherit;
-webkit-appearance: button;
}
output {
display: inline-block;
}
iframe {
border: 0;
}
summary {
display: list-item;
cursor: pointer;
}
progress {
vertical-align: baseline;
}
[hidden] {
display: none !important;
}
/*# sourceMappingURL=bootstrap-reboot.css.map */

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,8 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/*,::after,::before{box-sizing:border-box}@media (prefers-reduced-motion:no-preference){:root{scroll-behavior:smooth}}body{margin:0;font-family:var(--bs-body-font-family);font-size:var(--bs-body-font-size);font-weight:var(--bs-body-font-weight);line-height:var(--bs-body-line-height);color:var(--bs-body-color);text-align:var(--bs-body-text-align);background-color:var(--bs-body-bg);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}hr{margin:1rem 0;color:inherit;background-color:currentColor;border:0;opacity:.25}hr:not([size]){height:1px}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem;font-weight:500;line-height:1.2}h1{font-size:calc(1.375rem + 1.5vw)}@media (min-width:1200px){h1{font-size:2.5rem}}h2{font-size:calc(1.325rem + .9vw)}@media (min-width:1200px){h2{font-size:2rem}}h3{font-size:calc(1.3rem + .6vw)}@media (min-width:1200px){h3{font-size:1.75rem}}h4{font-size:calc(1.275rem + .3vw)}@media (min-width:1200px){h4{font-size:1.5rem}}h5{font-size:1.25rem}h6{font-size:1rem}p{margin-top:0;margin-bottom:1rem}abbr[data-bs-original-title],abbr[title]{-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}ol,ul{padding-left:2rem}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:.875em}mark{padding:.2em;background-color:#fcf8e3}sub,sup{position:relative;font-size:.75em;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#0d6efd;text-decoration:underline}a:hover{color:#0a58ca}a:not([href]):not([class]),a:not([href]):not([class]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em;direction:ltr;unicode-bidi:bidi-override}pre{display:block;margin-top:0;margin-bottom:1rem;overflow:auto;font-size:.875em}pre code{font-size:inherit;color:inherit;word-break:normal}code{font-size:.875em;color:#d63384;word-wrap:break-word}a>code{color:inherit}kbd{padding:.2rem .4rem;font-size:.875em;color:#fff;background-color:#212529;border-radius:.2rem}kbd kbd{padding:0;font-size:1em;font-weight:700}figure{margin:0 0 1rem}img,svg{vertical-align:middle}table{caption-side:bottom;border-collapse:collapse}caption{padding-top:.5rem;padding-bottom:.5rem;color:#6c757d;text-align:left}th{text-align:inherit;text-align:-webkit-match-parent}tbody,td,tfoot,th,thead,tr{border-color:inherit;border-style:solid;border-width:0}label{display:inline-block}button{border-radius:0}button:focus:not(:focus-visible){outline:0}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,select{text-transform:none}[role=button]{cursor:pointer}select{word-wrap:normal}select:disabled{opacity:1}[list]::-webkit-calendar-picker-indicator{display:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}::-moz-focus-inner{padding:0;border-style:none}textarea{resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{float:left;width:100%;padding:0;margin-bottom:.5rem;font-size:calc(1.275rem + .3vw);line-height:inherit}@media (min-width:1200px){legend{font-size:1.5rem}}legend+*{clear:left}::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-fields-wrapper,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-text,::-webkit-datetime-edit-year-field{padding:0}::-webkit-inner-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:textfield}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-color-swatch-wrapper{padding:0}::file-selector-button{font:inherit}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}iframe{border:0}summary{display:list-item;cursor:pointer}progress{vertical-align:baseline}[hidden]{display:none!important}
/*# sourceMappingURL=bootstrap-reboot.min.css.map */

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,424 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/
*,
*::before,
*::after {
box-sizing: border-box;
}
@media (prefers-reduced-motion: no-preference) {
:root {
scroll-behavior: smooth;
}
}
body {
margin: 0;
font-family: var(--bs-body-font-family);
font-size: var(--bs-body-font-size);
font-weight: var(--bs-body-font-weight);
line-height: var(--bs-body-line-height);
color: var(--bs-body-color);
text-align: var(--bs-body-text-align);
background-color: var(--bs-body-bg);
-webkit-text-size-adjust: 100%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
hr {
margin: 1rem 0;
color: inherit;
background-color: currentColor;
border: 0;
opacity: 0.25;
}
hr:not([size]) {
height: 1px;
}
h6, h5, h4, h3, h2, h1 {
margin-top: 0;
margin-bottom: 0.5rem;
font-weight: 500;
line-height: 1.2;
}
h1 {
font-size: calc(1.375rem + 1.5vw);
}
@media (min-width: 1200px) {
h1 {
font-size: 2.5rem;
}
}
h2 {
font-size: calc(1.325rem + 0.9vw);
}
@media (min-width: 1200px) {
h2 {
font-size: 2rem;
}
}
h3 {
font-size: calc(1.3rem + 0.6vw);
}
@media (min-width: 1200px) {
h3 {
font-size: 1.75rem;
}
}
h4 {
font-size: calc(1.275rem + 0.3vw);
}
@media (min-width: 1200px) {
h4 {
font-size: 1.5rem;
}
}
h5 {
font-size: 1.25rem;
}
h6 {
font-size: 1rem;
}
p {
margin-top: 0;
margin-bottom: 1rem;
}
abbr[title],
abbr[data-bs-original-title] {
-webkit-text-decoration: underline dotted;
text-decoration: underline dotted;
cursor: help;
-webkit-text-decoration-skip-ink: none;
text-decoration-skip-ink: none;
}
address {
margin-bottom: 1rem;
font-style: normal;
line-height: inherit;
}
ol,
ul {
padding-right: 2rem;
}
ol,
ul,
dl {
margin-top: 0;
margin-bottom: 1rem;
}
ol ol,
ul ul,
ol ul,
ul ol {
margin-bottom: 0;
}
dt {
font-weight: 700;
}
dd {
margin-bottom: 0.5rem;
margin-right: 0;
}
blockquote {
margin: 0 0 1rem;
}
b,
strong {
font-weight: bolder;
}
small {
font-size: 0.875em;
}
mark {
padding: 0.2em;
background-color: #fcf8e3;
}
sub,
sup {
position: relative;
font-size: 0.75em;
line-height: 0;
vertical-align: baseline;
}
sub {
bottom: -0.25em;
}
sup {
top: -0.5em;
}
a {
color: #0d6efd;
text-decoration: underline;
}
a:hover {
color: #0a58ca;
}
a:not([href]):not([class]), a:not([href]):not([class]):hover {
color: inherit;
text-decoration: none;
}
pre,
code,
kbd,
samp {
font-family: SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
font-size: 1em;
direction: ltr ;
unicode-bidi: bidi-override;
}
pre {
display: block;
margin-top: 0;
margin-bottom: 1rem;
overflow: auto;
font-size: 0.875em;
}
pre code {
font-size: inherit;
color: inherit;
word-break: normal;
}
code {
font-size: 0.875em;
color: #d63384;
word-wrap: break-word;
}
a > code {
color: inherit;
}
kbd {
padding: 0.2rem 0.4rem;
font-size: 0.875em;
color: #fff;
background-color: #212529;
border-radius: 0.2rem;
}
kbd kbd {
padding: 0;
font-size: 1em;
font-weight: 700;
}
figure {
margin: 0 0 1rem;
}
img,
svg {
vertical-align: middle;
}
table {
caption-side: bottom;
border-collapse: collapse;
}
caption {
padding-top: 0.5rem;
padding-bottom: 0.5rem;
color: #6c757d;
text-align: right;
}
th {
text-align: inherit;
text-align: -webkit-match-parent;
}
thead,
tbody,
tfoot,
tr,
td,
th {
border-color: inherit;
border-style: solid;
border-width: 0;
}
label {
display: inline-block;
}
button {
border-radius: 0;
}
button:focus:not(:focus-visible) {
outline: 0;
}
input,
button,
select,
optgroup,
textarea {
margin: 0;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
button,
select {
text-transform: none;
}
[role=button] {
cursor: pointer;
}
select {
word-wrap: normal;
}
select:disabled {
opacity: 1;
}
[list]::-webkit-calendar-picker-indicator {
display: none;
}
button,
[type=button],
[type=reset],
[type=submit] {
-webkit-appearance: button;
}
button:not(:disabled),
[type=button]:not(:disabled),
[type=reset]:not(:disabled),
[type=submit]:not(:disabled) {
cursor: pointer;
}
::-moz-focus-inner {
padding: 0;
border-style: none;
}
textarea {
resize: vertical;
}
fieldset {
min-width: 0;
padding: 0;
margin: 0;
border: 0;
}
legend {
float: right;
width: 100%;
padding: 0;
margin-bottom: 0.5rem;
font-size: calc(1.275rem + 0.3vw);
line-height: inherit;
}
@media (min-width: 1200px) {
legend {
font-size: 1.5rem;
}
}
legend + * {
clear: right;
}
::-webkit-datetime-edit-fields-wrapper,
::-webkit-datetime-edit-text,
::-webkit-datetime-edit-minute,
::-webkit-datetime-edit-hour-field,
::-webkit-datetime-edit-day-field,
::-webkit-datetime-edit-month-field,
::-webkit-datetime-edit-year-field {
padding: 0;
}
::-webkit-inner-spin-button {
height: auto;
}
[type=search] {
outline-offset: -2px;
-webkit-appearance: textfield;
}
[type="tel"],
[type="url"],
[type="email"],
[type="number"] {
direction: ltr;
}
::-webkit-search-decoration {
-webkit-appearance: none;
}
::-webkit-color-swatch-wrapper {
padding: 0;
}
::file-selector-button {
font: inherit;
}
::-webkit-file-upload-button {
font: inherit;
-webkit-appearance: button;
}
output {
display: inline-block;
}
iframe {
border: 0;
}
summary {
display: list-item;
cursor: pointer;
}
progress {
vertical-align: baseline;
}
[hidden] {
display: none !important;
}
/*# sourceMappingURL=bootstrap-reboot.rtl.css.map */

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,8 @@
/*!
* Bootstrap Reboot v5.1.0 (https://getbootstrap.com/)
* Copyright 2011-2021 The Bootstrap Authors
* Copyright 2011-2021 Twitter, Inc.
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
*/*,::after,::before{box-sizing:border-box}@media (prefers-reduced-motion:no-preference){:root{scroll-behavior:smooth}}body{margin:0;font-family:var(--bs-body-font-family);font-size:var(--bs-body-font-size);font-weight:var(--bs-body-font-weight);line-height:var(--bs-body-line-height);color:var(--bs-body-color);text-align:var(--bs-body-text-align);background-color:var(--bs-body-bg);-webkit-text-size-adjust:100%;-webkit-tap-highlight-color:transparent}hr{margin:1rem 0;color:inherit;background-color:currentColor;border:0;opacity:.25}hr:not([size]){height:1px}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem;font-weight:500;line-height:1.2}h1{font-size:calc(1.375rem + 1.5vw)}@media (min-width:1200px){h1{font-size:2.5rem}}h2{font-size:calc(1.325rem + .9vw)}@media (min-width:1200px){h2{font-size:2rem}}h3{font-size:calc(1.3rem + .6vw)}@media (min-width:1200px){h3{font-size:1.75rem}}h4{font-size:calc(1.275rem + .3vw)}@media (min-width:1200px){h4{font-size:1.5rem}}h5{font-size:1.25rem}h6{font-size:1rem}p{margin-top:0;margin-bottom:1rem}abbr[data-bs-original-title],abbr[title]{-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;-webkit-text-decoration-skip-ink:none;text-decoration-skip-ink:none}address{margin-bottom:1rem;font-style:normal;line-height:inherit}ol,ul{padding-right:2rem}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-right:0}blockquote{margin:0 0 1rem}b,strong{font-weight:bolder}small{font-size:.875em}mark{padding:.2em;background-color:#fcf8e3}sub,sup{position:relative;font-size:.75em;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#0d6efd;text-decoration:underline}a:hover{color:#0a58ca}a:not([href]):not([class]),a:not([href]):not([class]):hover{color:inherit;text-decoration:none}code,kbd,pre,samp{font-family:SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-size:1em;direction:ltr;unicode-bidi:bidi-override}pre{display:block;margin-top:0;margin-bottom:1rem;overflow:auto;font-size:.875em}pre code{font-size:inherit;color:inherit;word-break:normal}code{font-size:.875em;color:#d63384;word-wrap:break-word}a>code{color:inherit}kbd{padding:.2rem .4rem;font-size:.875em;color:#fff;background-color:#212529;border-radius:.2rem}kbd kbd{padding:0;font-size:1em;font-weight:700}figure{margin:0 0 1rem}img,svg{vertical-align:middle}table{caption-side:bottom;border-collapse:collapse}caption{padding-top:.5rem;padding-bottom:.5rem;color:#6c757d;text-align:right}th{text-align:inherit;text-align:-webkit-match-parent}tbody,td,tfoot,th,thead,tr{border-color:inherit;border-style:solid;border-width:0}label{display:inline-block}button{border-radius:0}button:focus:not(:focus-visible){outline:0}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,select{text-transform:none}[role=button]{cursor:pointer}select{word-wrap:normal}select:disabled{opacity:1}[list]::-webkit-calendar-picker-indicator{display:none}[type=button],[type=reset],[type=submit],button{-webkit-appearance:button}[type=button]:not(:disabled),[type=reset]:not(:disabled),[type=submit]:not(:disabled),button:not(:disabled){cursor:pointer}::-moz-focus-inner{padding:0;border-style:none}textarea{resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{float:right;width:100%;padding:0;margin-bottom:.5rem;font-size:calc(1.275rem + .3vw);line-height:inherit}@media (min-width:1200px){legend{font-size:1.5rem}}legend+*{clear:right}::-webkit-datetime-edit-day-field,::-webkit-datetime-edit-fields-wrapper,::-webkit-datetime-edit-hour-field,::-webkit-datetime-edit-minute,::-webkit-datetime-edit-month-field,::-webkit-datetime-edit-text,::-webkit-datetime-edit-year-field{padding:0}::-webkit-inner-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:textfield}[type=email],[type=number],[type=tel],[type=url]{direction:ltr}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-color-swatch-wrapper{padding:0}::file-selector-button{font:inherit}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}iframe{border:0}summary{display:list-item;cursor:pointer}progress{vertical-align:baseline}[hidden]{display:none!important}
/*# sourceMappingURL=bootstrap-reboot.rtl.min.css.map */

File diff suppressed because one or more lines are too long

4866
account/public/css/bootstrap-utilities.css vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

11221
account/public/css/bootstrap.css vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

7
account/public/css/bootstrap.min.css vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

11197
account/public/css/bootstrap.rtl.css vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,39 @@
html,
body {
height: 100%;
}
body {
display: flex;
align-items: center;
padding-top: 40px;
padding-bottom: 40px;
background-color: #f5f5f5;
}
.form-signin {
width: 100%;
max-width: 330px;
padding: 15px;
margin: auto;
}
.form-signin .checkbox {
font-weight: 400;
}
.form-signin .form-floating:focus-within {
z-index: 2;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

6780
account/public/js/bootstrap.bundle.js vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

4977
account/public/js/bootstrap.esm.js vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

5026
account/public/js/bootstrap.js vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

7
account/public/js/bootstrap.min.js vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

6
account/src/extend-express.d.ts vendored Normal file
View File

@ -0,0 +1,6 @@
declare namespace Express {
export interface Request {
// TODO: this will be brought in with an import
user?: LingdocsUser
}
}

50
account/src/index.ts Normal file
View File

@ -0,0 +1,50 @@
import express from "express";
import cors from "cors";
import passport from "passport";
import setupPassport from "./middleware/setup-passport";
import setupSession from "./middleware/setup-session";
import authRouter from "./routers/auth-router";
import apiRouter from "./routers/api-router";
import inProd from "./lib/inProd";
import feedbackRouter from "./routers/feedback-router";
import paymentRouter from "./routers/payment-router";
import dictionaryRouter from "./routers/dictionary-router";
const sameOriginCorsOpts = {
origin: inProd ? /\.lingdocs\.com$/ : "*",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true,
};
const app = express();
// MIDDLEWARE AND SETUP 🔧 //
app.set("view engine", "ejs");
app.use("/payment/webhook", express.raw({ type: "*/*" }));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));
if (inProd) app.set("trust proxy", 1);
setupSession(app);
app.use(passport.initialize());
app.use(passport.session());
setupPassport(passport);
app.get("/test", cors(), (req, res) => {
res.send({ ok: true });
});
// Dictionary API
app.options("/dictionary", cors());
app.use("/dictionary", cors(), dictionaryRouter);
// Web Interface - returning html (mostly)
app.use("/", cors(sameOriginCorsOpts), authRouter(passport));
// REST API - returning json
app.use("/api", cors(sameOriginCorsOpts), apiRouter);
app.use("/feedback", cors(sameOriginCorsOpts), feedbackRouter);
// TODO: check - does this work with the cors ?
app.use("/payment", cors(sameOriginCorsOpts), paymentRouter);
// START 💨 //
app.listen(4000, () => console.log("Server Has Started on 4000"));

288
account/src/lib/couch-db.ts Normal file
View File

@ -0,0 +1,288 @@
import Nano from "nano";
import { DocumentInsertResponse } from "nano";
import { getTimestamp } from "./time-utils";
import env from "./env-vars";
import * as T from "../../../website/src/types/account-types";
const nano = Nano(env.couchDbURL);
const usersDb = nano.db.use("lingdocs-users");
const feedbackDb = nano.db.use("feedback");
const paymentsDb = nano.db.use("payments");
const userDbPrefix = "userdb-";
export async function addFeedback(feedback: any) {
await feedbackDb.insert(feedback);
}
export async function addToPaymentsDb(payment: any) {
await paymentsDb.insert(payment);
}
export function updateLastLogin(user: T.LingdocsUser): T.LingdocsUser {
return {
...user,
lastLogin: getTimestamp(),
};
}
function processAPIResponse(
user: T.LingdocsUser,
response: DocumentInsertResponse
): T.LingdocsUser | undefined {
if (response.ok !== true) return undefined;
return {
...user,
_id: response.id,
_rev: response.rev,
};
}
export async function getLingdocsUser(
field: "email" | "userId" | "githubId" | "googleId" | "twitterId",
value: string
): Promise<undefined | T.LingdocsUser> {
const user = await usersDb.find({
selector:
field === "githubId"
? { github: { id: value } }
: field === "googleId"
? { google: { id: value } }
: field === "twitterId"
? { twitter: { id: value } }
: { [field]: value },
});
if (!user.docs.length) {
return undefined;
}
return user.docs[0] as T.LingdocsUser;
}
export async function getAllLingdocsUsers(): Promise<T.LingdocsUser[]> {
const users = await usersDb.find({
selector: { userId: { $exists: true } },
limit: 5000,
});
return users.docs as T.LingdocsUser[];
}
export async function getAllFeedback(): Promise<any[]> {
const res = await feedbackDb.find({
selector: {
feedback: { $exists: true },
},
limit: 5000,
});
const docs = res.docs;
// @ts-ignore
docs.sort((a, b) => b.feedback.ts - a.feedback.ts);
return docs as any[];
}
export async function insertLingdocsUser(
user: T.LingdocsUser
): Promise<T.LingdocsUser> {
try {
const res = await usersDb.insert(user);
const newUser = processAPIResponse(user, res);
if (!newUser) {
throw new Error("error inserting user");
}
return newUser;
} catch (e) {
console.log("ERROR on insertLingdocsUser", user);
throw new Error("error inserting user - on update");
}
}
export async function deleteLingdocsUser(uuid: T.UUID): Promise<void> {
const user = await getLingdocsUser("userId", uuid);
await deleteCouchDbAuthUser(uuid);
if (!user) return;
// TODO: cleanup userdbs etc
// TODO: Better type certainty here... obviously there is an _id and _rev here
await usersDb.destroy(user._id as string, user._rev as string);
}
export async function deleteCouchDbAuthUser(uuid: T.UUID): Promise<void> {
const authUsers = nano.db.use("_users");
const user = await authUsers.find({ selector: { name: uuid } });
if (!user.docs.length) return;
const u = user.docs[0];
await authUsers.destroy(u._id, u._rev);
await nano.db.destroy(getWordlistDbName(uuid));
}
export async function updateLingdocsUser(
uuid: T.UUID,
toUpdate: // TODO: OR USE REDUCER??
| { name: string }
| { name?: string; email: string; emailVerified: T.Hash }
| { email: string; emailVerified: true }
| { emailVerified: T.Hash }
| { emailVerified: true }
| { password: T.Hash }
| { google: T.GoogleProfile | undefined }
| { github: T.GitHubProfile | undefined }
| { twitter: T.TwitterProfile | undefined }
| {
passwordReset: {
tokenHash: T.Hash;
requestedOn: T.TimeStamp;
};
}
| {
level: "student";
wordlistDbName: T.WordlistDbName;
couchDbPassword: T.UserDbPassword;
upgradeToStudentRequest: undefined;
subscription?: T.StripeSubscription;
}
| {
level: "basic";
wordlistDbName: undefined;
couchDbPassword: undefined;
upgradeToStudentRequest: undefined;
subscription: undefined;
}
| { upgradeToStudentRequest: "waiting" }
| { upgradeToStudentRequest: "denied" }
| { tests: T.TestResult[] }
| { wordlistDbName: T.WordlistDbName; couchDbPassword: T.UserDbPassword }
): Promise<T.LingdocsUser> {
const user = await getLingdocsUser("userId", uuid);
if (!user) throw new Error("unable to update - user not found " + uuid);
if ("tests" in toUpdate) {
return await insertLingdocsUser({
...user,
tests: addNewTests(user.tests, toUpdate.tests, 2),
});
}
if ("password" in toUpdate) {
const { passwordReset, ...u } = user;
return await insertLingdocsUser({
...u,
...toUpdate,
});
}
return await insertLingdocsUser({
...user,
...toUpdate,
});
}
export async function addCouchDbAuthUser(
uuid: T.UUID
): Promise<{ password: T.UserDbPassword; userDbName: T.WordlistDbName }> {
const password = generateWordlistDbPassword();
const userDbName = getWordlistDbName(uuid);
const usersDb = nano.db.use("_users");
// TODO: prevent conflict if adding an existing user for some reason
const authUser: T.CouchDbAuthUser = {
_id: `org.couchdb.user:${uuid}`,
type: "user",
roles: [],
name: uuid,
password,
};
await usersDb.insert(authUser);
await nano.db.create(userDbName);
const userDb = nano.db.use(userDbName);
await userDb.insert(
{
// @ts-ignore
admins: {
names: [uuid],
roles: ["_admin"],
},
members: {
names: [uuid],
roles: ["_admin"],
},
},
"_security"
);
return { password, userDbName };
}
// Instead of these functions, I'm using couch_peruser
// export async function createWordlistDatabase(uuid: T.UUID, password: T.UserDbPassword): Promise<{ name: T.WordlistDbName, password: T.UserDbPassword }> {
// const name = getWordlistDbName(uuid);
// // create wordlist database for user
// await nano.db.create(name);
// const securityInfo = {
// admins: {
// names: [uuid],
// roles: ["_admin"]
// },
// members: {
// names: [uuid],
// roles: ["_admin"],
// },
// };
// const userDb = nano.db.use(name);
// await userDb.insert(securityInfo as any, "_security");
// return { password, name };
// }
// export async function deleteWordlistDatabase(uuid: T.UUID): Promise<void> {
// const name = getWordlistDbName(uuid);
// try {
// await nano.db.destroy(name);
// } catch (e) {
// // allow the error to pass if we're just trying to delete a database that never existed
// if (e.message !== "Database does not exist.") {
// throw new Error("error deleting database");
// }
// }
// }
export function getWordlistDbName(uid: T.UUID): T.WordlistDbName {
return `${userDbPrefix}${stringToHex(uid)}` as T.WordlistDbName;
}
export function generateWordlistDbPassword(): T.UserDbPassword {
function makeChunk(): string {
return Math.random().toString(36).slice(2);
}
const password = new Array(4)
.fill(0)
.reduce((acc: string): string => acc + makeChunk(), "");
return password as T.UserDbPassword;
}
function stringToHex(str: string) {
const arr1 = [];
for (let n = 0, l = str.length; n < l; n++) {
const hex = Number(str.charCodeAt(n)).toString(16);
arr1.push(hex);
}
return arr1.join("");
}
/**
* Adds new tests to a users record, only keeping up to amountToKeep records of the most
* recent repeat passes/fails
*
* @param existing - the existing tests in a users record
* @param newResults - the tests to be added to a users record
* @param amountToKeep - the amount of repeat tests to keep (defaults to 2)
*/
function addNewTests(
existing: Readonly<T.TestResult[]>,
toAdd: T.TestResult[],
amountToKeep = 2
): T.TestResult[] {
const tests = [...existing];
// check to make sure that we're only adding test results that are not already added
const newTests = toAdd.filter((t) => !tests.some((x) => x.time === t.time));
newTests.forEach((nt) => {
const repeats = tests.filter((x) => x.id === nt.id && x.done === nt.done);
if (repeats.length > amountToKeep - 1) {
// already have enough repeat passes saved, remove the oldest one
const i = tests.findIndex((x) => x.time === repeats[0].time);
if (i > -1) tests.splice(i, 1);
}
tests.push(nt);
});
return tests;
}

View File

@ -0,0 +1,155 @@
import loki, { Collection, LokiMemoryAdapter } from "lokijs";
import fetch from "node-fetch";
import { CronJob } from "cron";
const collectionName = "ps-dictionary";
const allWordsCollectionName = "all-words";
import {
Types as T,
typePredicates as tp,
entryOfFull,
standardizePashto,
} from "@lingdocs/inflect";
export let collection: Collection<T.DictionaryEntry> | undefined = undefined;
export let allWordsCollection: Collection<T.PsString> | undefined = undefined;
const adapter = new LokiMemoryAdapter();
const lokidb = new loki("", {
adapter,
autoload: false,
autosave: false,
env: "NODEJS",
});
const updateJob = new CronJob("* * * * *", updateDictionary, null, false);
let version: number = 0;
async function fetchDictionary(): Promise<T.Dictionary> {
const res = await fetch(process.env.LINGDOCS_DICTIONARY_URL + ".json" || "");
return await res.json();
}
async function fetchAllWords(): Promise<T.AllWordsWithInflections> {
// TODO: this is really ugly
const res = await fetch(
process.env.LINGDOCS_DICTIONARY_URL?.slice(0, -10) +
"all-words-dictionary.json"
);
return await res.json();
}
async function fetchDictionaryInfo(): Promise<T.DictionaryInfo> {
const res = await fetch(
process.env.LINGDOCS_DICTIONARY_URL + "-info.json" || ""
);
return await res.json();
}
export async function updateDictionary(): Promise<"no update" | "updated"> {
try {
const info = await fetchDictionaryInfo();
if (info.release === version) {
return "no update";
}
const dictionary = await fetchDictionary();
version = dictionary.info.release;
collection?.clear();
lokidb.removeCollection(collectionName);
collection?.insert(dictionary.entries);
const allWords = await fetchAllWords();
allWordsCollection?.clear();
lokidb.removeCollection(allWordsCollectionName);
allWordsCollection?.insert(allWords.words);
return "updated";
} catch (e) {
console.error(e);
return "no update";
}
}
function getOneByTs(ts: number): T.DictionaryEntry {
if (!collection) {
throw new Error("dictionary not initialized");
}
const r = collection.by("ts", ts);
// @ts-ignore
const { $loki, meta, ...entry } = r;
return entry;
}
export function findInAllWords(p: string | RegExp): T.PsWord[] | undefined {
if (!allWordsCollection) {
throw new Error("allWords not initialized");
}
return allWordsCollection.find({
p: typeof p === "string" ? p : { $regex: p },
});
}
export async function getEntries(ids: (number | string)[]): Promise<{
results: (T.DictionaryEntry | T.VerbEntry)[];
notFound: (number | string)[];
}> {
if (!collection) {
throw new Error("dictionary not initialized");
}
const idsP = ids.map((x) =>
typeof x === "number" ? x : standardizePashto(x)
);
const results: (T.DictionaryEntry | T.VerbEntry)[] = collection
.find({
$or: [{ ts: { $in: idsP } }, { p: { $in: idsP } }],
})
.map((x) => {
const { $loki, meta, ...entry } = x;
return entry;
})
.map((entry): T.DictionaryEntry | T.VerbEntry => {
if (tp.isVerbDictionaryEntry(entry)) {
if (entry.c?.includes("comp.") && entry.l) {
const complement = getOneByTs(entry.l);
if (!complement)
throw new Error("Error getting complement " + entry.l);
return {
entry,
complement,
};
}
return { entry };
} else {
return entry;
}
});
return {
results,
notFound: ids.filter(
(id) =>
!results.find((x) => {
const entry = entryOfFull(x);
return entry.p === id || entry.ts === id;
})
),
};
}
lokidb.loadDatabase({}, (err: Error) => {
lokidb.removeCollection(collectionName);
lokidb.removeCollection(allWordsCollectionName);
fetchDictionary()
.then((dictionary) => {
collection = lokidb.addCollection(collectionName, {
indices: ["i", "p"],
unique: ["ts"],
});
version = dictionary.info.release;
collection?.insert(dictionary.entries);
updateJob.start();
})
.catch(console.error);
fetchAllWords().then((allWords) => {
allWordsCollection = lokidb.addCollection(allWordsCollectionName, {
indices: ["p"],
});
allWordsCollection?.insert(allWords.words);
});
});

View File

@ -0,0 +1,45 @@
const names = [
"LINGDOCS_EMAIL_HOST",
"LINGDOCS_EMAIL_USER",
"LINGDOCS_EMAIL_PASS",
"LINGDOCS_COUCHDB",
"LINGDOCS_ACCOUNT_COOKIE_SECRET",
"LINGDOCS_ACCOUNT_GOOGLE_CLIENT_SECRET",
"LINGDOCS_ACCOUNT_TWITTER_CLIENT_SECRET",
"LINGDOCS_ACCOUNT_GITHUB_CLIENT_SECRET",
"LINGDOCS_ACCOUNT_RECAPTCHA_SECRET",
"LINGDOCS_ACCOUNT_UPGRADE_PASSWORD",
"STRIPE_SECRET_KEY",
"STRIPE_WEBHOOK_SECRET",
"NTFY_TOPIC",
];
const values = names.map((name) => ({
name,
value: process.env[name] || "",
}));
const missing = values.filter((v) => !v.value);
if (missing.length) {
console.error(
"Missing evironment variable(s):",
missing.map((m) => m.name).join(", ")
);
process.exit(1);
}
export default {
emailHost: values[0].value,
emailUser: values[1].value,
emailPass: values[2].value,
couchDbURL: values[3].value,
cookieSecret: values[4].value,
googleClientSecret: values[5].value,
twitterClientSecret: values[6].value,
githubClientSecret: values[7].value,
recaptchaSecret: values[8].value,
upgradePassword: values[9].value,
stripeSecretKey: values[10].value,
stripeWebhookSecret: values[11].value,
ntfyTopic: values[12].value,
};

View File

@ -0,0 +1,271 @@
const arabicNumsRegex = /[۰-۹]/g;
const pRegex = /اً|أ|ا|آ|ٱ|ٲ|ٳ|ئی|ئي|ئے|یٰ|ی|ي|ې|ۍ|ئ|ے|س|ص|ث|څ|ج|چ|هٔ|ه|ۀ|غز|زغ|کش|شک|ښک|ښک|پښ|ښپ|ہ|ع|و|ؤ|ښ|غ|خ|ح|ش|ز|ض|ذ|ځ|ظ|ژ|ر|ړ|ڑ|ت|ټ|ٹ|ط|د|ډ|ڈ|مب|م|نب|ن|ڼ|ک|ګ|گ|ل|ق|ږ|ب|پ|ف/g;
// [\u0621-\u065f\u0670-\u06d3\u06d5]/g;
const pTable: ({
chars: string[],
beg: string,
mid: string,
end: string,
} | {
chars: string[],
sound: string,
})[] = [
{
chars: ["ءع"],
sound: "",
},
{
chars: ["آ"],
sound: "a",
},
{
chars: ["أ"],
sound: "U",
},
{
chars: ["ؤ"],
sound: "o/w",
},
{
chars: ["إ"],
sound: "i",
},
{
chars: ["ئ"],
beg: "y",
mid: "y",
end: "eyy",
},
{
chars: ["ا"],
beg: "aa/a/i/u/U",
mid: "aa",
end: "aa",
},
{
chars: ["ب"],
sound: "b",
},
{
chars: ["ة"],
sound: "a/u",
},
{
chars: ["ت", "ط"],
sound: "t",
},
{
chars: ["ټ"],
sound: "T",
},
{
chars: ["ث", "س", "ص"],
sound: "s",
},
{
chars: ["ج"],
sound: "j",
},
{
chars: ["ح"],
sound: "h",
},
{
chars: ["اه"],
sound: "aah",
},
{
chars: ["ه"],
beg: "h",
mid: "h",
end: "a/i/u/h",
},
{
chars: ["خ"],
sound: "kh",
},
{
chars: ["د"],
sound: "d",
},
{
chars: ["ذ", "ز", "ض", "ظ"],
sound: "z",
},
{
chars: ["ډ"],
sound: "D",
},
{
chars: ["ر"],
sound: "r",
},
{
chars: ["ړ"],
sound: "R",
},
{
chars: ["ش"],
sound: "sh",
},
{
chars: ["غ"],
sound: "gh",
},
{
chars: ["ف"],
sound: "f",
},
{
chars: ["ق"],
sound: "q",
},
{
chars: ["ك", "ک"],
sound: "k",
},
{
chars: ["ل"],
sound: "l",
},
{
chars: ["م"],
sound: "m",
},
{
chars: ["ن"],
sound: "n",
},
{
chars: ["ڼ"],
sound: "N",
},
{
chars: ["و"],
beg: "w",
mid: "w/o/oo",
end: "w/o/oo",
},
{
chars: ["ای"],
sound: "aay",
},
{
chars: ["وی"],
sound: "ooy",
},
{
chars: ["ی", "ے"],
beg: "y",
mid: "ey/ee/y",
end: "ey",
},
{
chars: ["ي"],
beg: "y",
mid: "ey/ee/y",
end: "ee",
},
{
chars: ["اً"],
sound: "an",
},
{
chars: ["ځ"],
sound: "dz",
},
{
chars: ["څ"],
sound: "ts",
},
{
chars: ["چ"],
sound: "ch",
},
{
chars: ["ږ"],
sound: "G",
},
{
chars: ["ژ"],
sound: "jz",
},
{
chars: ["ښ"],
sound: "x",
},
{
chars: ["ۍ"],
sound: "uy",
},
{
chars: ["ې"],
sound: "e",
},
{
chars: ["ګ", "گ"],
sound: "g",
},
{
chars: ["یٰ"],
sound: "aa",
},
];
// "ء": "",
// "آ": "",
// "أ": "",
// "ؤ": "",
// "إ": "",
// "ئ": "",
// "ا": "",
// "": "",
// "": "",
// "": "",
// "": "",
// "": "",
// "": "",
// "": "",
// "": "",
// "": "",
// }
const numsTable = {
"۰": "0",
"۱": "1",
"۲": "2",
"۳": "3",
"۴": "4",
"۵": "5",
"۶": "6",
"۷": "7",
"۸": "8",
"۹": "9",
};
export function handlePunctuationAndNums(s: string): string {
return s.replace(/؟/g, "?")
.replace(/،/g, ",")
.replace(/«/g, '"')
.replace(/»/g, '"')
.replace(arabicNumsRegex, (mtch) => {
// @ts-ignore
return numsTable[mtch];
});
}
export function handleUnmatched(s: string): string {
const g = s.replace(pRegex, (mtch, i) => {
const pos: "beg" | "mid" | "end" = i === 0
? "beg"
: i === s.length-1
? "end"
: "mid";
const m = pTable.find(x => x.chars.includes(mtch));
if (!m) return "";
const sound = "sound" in m ? m.sound : m[pos];
return sound.includes("/") ? `(${sound})` : sound;
})
return `?*${g}*?`;
}

View File

@ -0,0 +1 @@
export default process.env.NODE_ENV === "production";

View File

@ -0,0 +1,99 @@
import nodemailer from "nodemailer";
import inProd from "./inProd";
import env from "./env-vars";
import * as T from "../../../website/src/types/account-types";
type Address = string | { name: string; address: string };
const adminAddress: Address = {
name: "LingDocs Admin",
address: "admin@lingdocs.com",
};
export function getAddress(user: T.LingdocsUser): Address {
// TODO: Guard against ""
if (!user.name) return user.email || "";
return {
name: user.name,
address: user.email || "",
};
}
const transporter = nodemailer.createTransport({
host: env.emailHost,
port: 465,
secure: true,
auth: {
user: env.emailUser,
pass: env.emailPass,
},
});
async function sendEmail(to: Address, subject: string, text: string) {
return await transporter.sendMail({
from: adminAddress,
to,
subject,
text,
});
}
// TODO: MAKE THIS A URL ACROSS PROJECT
const baseURL = inProd
? "https://account.lingdocs.com"
: "http://localhost:4000";
export async function sendVerificationEmail({
name,
uid,
email,
token,
}: {
name: string;
uid: T.UUID;
email: string;
token: T.URLToken;
}) {
const subject = "Please Verify Your E-mail";
const content = `Hello ${name},
Please verify your email by visiting this link: ${baseURL}/email-verification/${uid}/${token}
LingDocs Admin`;
await sendEmail(email, subject, content);
}
export async function sendPasswordResetEmail(
user: T.LingdocsUser,
token: T.URLToken
) {
const subject = "Reset Your Password";
const content = `Hello ${user.name},
Please visit this link to reset your password: ${baseURL}/password-reset/${user.userId}/${token}
LingDocs Admin`;
await sendEmail(getAddress(user), subject, content);
}
export async function sendAccountUpgradeMessage(user: T.LingdocsUser) {
const subject = "You're Upgraded to Student";
const content = `Hello ${user.name},
Congratulations on your upgrade to a LingDocs Student account! 👨🎓
Now you can start using your wordlist in the dictionary. It will automatically sync across any devices you're signed in to.
LingDocs Admin`;
await sendEmail(getAddress(user), subject, content);
}
export async function sendUpgradeRequestToAdmin(
userWantingToUpgrade: T.LingdocsUser
) {
const subject = "Account Upgrade Request";
const content = `${userWantingToUpgrade.name} - ${userWantingToUpgrade.email} - ${userWantingToUpgrade.userId} is requesting to upgrade to student.`;
await sendEmail(adminAddress, subject, content);
}

9
account/src/lib/ntfy.ts Normal file
View File

@ -0,0 +1,9 @@
import fetch from "node-fetch";
import envVars from "./env-vars";
export async function ntfy(message: string) {
fetch(`https://ntfy.sh/${envVars.ntfyTopic}`, {
method: "POST",
body: message,
}).catch(console.error);
}

View File

@ -0,0 +1,27 @@
import { hash, compare } from "bcryptjs";
import { randomBytes } from "crypto";
import base64url from "base64url";
import * as T from "../../../website/src/types/account-types";
const tokenSize = 24;
export async function getHash(p: string): Promise<T.Hash> {
return (await hash(p, 10)) as T.Hash;
}
export async function getEmailTokenAndHash(): Promise<{
token: T.URLToken;
hash: T.Hash;
}> {
const token = getURLToken();
const h = await getHash(token);
return { token, hash: h };
}
export function getURLToken(): T.URLToken {
return base64url(randomBytes(tokenSize)) as T.URLToken;
}
export function compareToHash(s: string, hash: T.Hash): Promise<boolean> {
return compare(s, hash);
}

View File

@ -0,0 +1,11 @@
import env from "./env-vars";
import fetch from "node-fetch";
const secret = env.recaptchaSecret;
export async function validateReCaptcha(response: string): Promise<boolean> {
const initial = await fetch(
encodeURI(`https://www.google.com/recaptcha/api/siteverify?secret=${secret}&response=${response}`)
);
const answer = await initial.json();
return !!answer.success;
}

View File

@ -0,0 +1,77 @@
import * as AT from "../../../website/src/types/account-types";
const basic: AT.LingdocsUser = {
"_id":"5e8dd381-950f-4641-922d-c63c6bf0f8e9",
"_rev":"1713-1a299e0d66da62fe4c8d059f0f068cb7",
"userId":"5e8dd381-950f-4641-922d-c63c6bf0f8e9" as AT.UUID,
"email":"bob@example.com",
"emailVerified":true,
"name":"Bob Smith",
"password":"12345" as AT.Hash,
"level":"basic",
"tests":[],
"lastLogin":1629893763810 as AT.TimeStamp,
"lastActive":1630414108552 as AT.TimeStamp,
};
const student: AT.LingdocsUser = {
"_id":"5e8dd381-950f-4641-922d-c63c6bf0f8e8",
"_rev":"1713-1a299e0d66da62fe4c8d059f0f068cb6",
"userId":"5e8dd381-950f-4641-922d-c63c6bf0f8e9" as AT.UUID,
"email":"jim@example.com",
"emailVerified":true,
"name":"Jim Weston",
"password":"12345" as AT.Hash,
"level":"student",
"tests":[],
"lastLogin":1629893763810 as AT.TimeStamp,
"lastActive":1630414108552 as AT.TimeStamp,
"couchDbPassword": "12345" as AT.UserDbPassword,
"wordlistDbName": "jim-db" as AT.WordlistDbName,
subscription: undefined,
};
const admin: AT.LingdocsUser = {
"_id":"5e8dd381-950f-4641-922d-c63c6bf0f8e8",
"_rev":"1713-1a299e0d66da62fe4c8d059f0f068cb6",
"userId":"5e8dd381-950f-4641-922d-c63c6bf0f8e9" as AT.UUID,
"email":"jim@example.com",
"emailVerified":true,
"name":"Frank Weston",
"password":"12345" as AT.Hash,
"level":"editor",
"admin":true,
"tests":[],
"lastLogin":1629893763810 as AT.TimeStamp,
"lastActive":1630414108552 as AT.TimeStamp,
"couchDbPassword": "12345" as AT.UserDbPassword,
"wordlistDbName": "jim-db" as AT.WordlistDbName,
subscription: undefined,
};
const editor: AT.LingdocsUser = {
"_id":"5e8dd381-950f-4641-922d-c63c6bf0f8e8",
"_rev":"1713-1a299e0d66da62fe4c8d059f0f068cb6",
"userId":"5e8dd381-950f-4641-922d-c63c6bf0f8e9" as AT.UUID,
"email":"jim@example.com",
"emailVerified":true,
"name":"Frank Weston",
"password":"12345" as AT.Hash,
"level":"editor",
"tests":[],
"lastLogin":1629893763810 as AT.TimeStamp,
"lastActive":1630414108552 as AT.TimeStamp,
"couchDbPassword": "12345" as AT.UserDbPassword,
"wordlistDbName": "jim-db" as AT.WordlistDbName,
subscription: undefined,
};
// @ts-ignore
const users: any = {
basic,
student,
editor,
admin,
};
export default users;

View File

@ -0,0 +1,173 @@
import {
Types as T,
standardizePashto,
removeAccents,
} from "@lingdocs/inflect";
import { findInAllWords } from "./dictionary";
import {
handlePunctuationAndNums,
handleUnmatched,
} from "./handle-unmatched";
// TODO: handle و ارزي
// spacing error with کور کې چېرته اوسېږئ
function isP(c: string): boolean {
return !!c.match(/[\u0621-\u065f\u0670-\u06d3\u06d5]/);
}
// TODO: ERRORING WHEN YOU JUST PUT A BUNCH OF ENGLISH CHARS IN THE TEXT
/**
* Converts some Pashto texts to phonetics by looking up each word in the dictionary and finding
* the phonetic equivalent
*
* @param p
* @returns
*/
export function scriptToPhonetics(p: string, accents: boolean): {
phonetics: string,
missing: string[],
} {
const words = splitWords(standardizePashto(p));
if (!words.length) return {
phonetics: "",
missing: [],
}
// TODO: keep going with the hyphens etc
// also و ارزي
const converted: string[] = [];
const missing = new Set<string>();
let i = 0;
function handleAccents(f: string): string {
return accents ? f : removeAccents(f);
}
function checkHyphenMatch(psw: T.PsWord): {
match: boolean,
words: number,
f: string,
} {
if (!psw.hyphen) {
throw new Error("checking a match without a hyphen content");
}
let match = false;
let f = psw.f;
let k = 1;
for (let j = 0; j < psw.hyphen.length; j++) {
const h = psw.hyphen[j];
const w = words[i+k];
if (h.type === "unwritten" && w === " ") {
match = true;
f += `-${h.f}`;
k += 1;
} else if (h.type === "written" && w === h.p) {
match = true;
f += `-${h.f}`;
k += 1;
} else if (h.type === "written" && w === " " && words[i+1+k] === h.p) {
match = true;
f += `-${h.f}`;
k += 2;
} else {
match = false;
break;
}
}
return {
match,
f,
words: k,
}
}
function handleMatches(matches: T.PsWord[]): string[] {
const hyphens = matches.filter(x => x.hyphen);
const plain = matches.filter(x => !x.hyphen);
const processed = new Set<string>();
if (hyphens.length) {
for (let h of hyphens) {
const res = checkHyphenMatch(h);
if (res.match) {
i += res.words;
processed.add(handleAccents(res.f));
break;
}
}
} else if (hyphens.length && !plain.length) {
processed.add("ERR");
i++;
} {
plain.forEach((x) => {
processed.add(handleAccents(x.f));
});
i++;
}
return Array.from(processed);
}
while (i < words.length) {
const word = words[i];
const p = isP(word);
if (p) {
const matches = findInAllWords(possibleFuzzify(word));
if (!matches) {
throw new Error("not initialized");
}
if (matches.length > 0) {
const possibilities = handleMatches(matches);
converted.push(possibilities.join("/"));
} else {
missing.add(word);
converted.push(handleUnmatched(word));
i++;
}
} else {
converted.push(handlePunctuationAndNums(word));
i++;
}
}
return {
phonetics: converted.join(""),
missing: Array.from(missing),
};
}
function splitWords(p: string): string[] {
const words: string[] = [];
let current = "";
let onP: boolean = true;
const chars = p.split("");
for (let char of chars) {
const p = isP(char);
if (p) {
if (onP) {
current += char;
} else {
words.push(current);
current = char;
onP = true;
}
} else {
if (onP) {
words.push(current);
current = char;
onP = false;
} else {
current += char;
}
}
}
words.push(current);
return words;
}
function possibleFuzzify(s: string): string | RegExp {
if (s.length < 3) {
return s;
}
const middle = s.slice(1, -1);
if (middle.includes("ې") || middle.includes("ی")) {
return new RegExp(`^${s[0]}${middle.replace(/[ی|ې]/g, "[ې|ی]")}${s.slice(-1)}$`);
} else {
return s;
}
}

View File

@ -0,0 +1,5 @@
import * as T from "../../../website/src/types/account-types";
export function getTimestamp(): T.TimeStamp {
return Date.now() as T.TimeStamp;
}

View File

@ -0,0 +1,230 @@
import { v4 as uuidv4 } from "uuid";
import {
insertLingdocsUser,
addCouchDbAuthUser,
updateLingdocsUser,
deleteCouchDbAuthUser,
} from "../lib/couch-db";
import { getHash, getEmailTokenAndHash } from "../lib/password-utils";
import { getTimestamp } from "../lib/time-utils";
import {
sendVerificationEmail,
sendAccountUpgradeMessage,
} from "../lib/mail-utils";
import { outsideProviders } from "../middleware/setup-passport";
import * as T from "../../../website/src/types/account-types";
import env from "../lib/env-vars";
import Stripe from "stripe";
import { ntfy } from "./ntfy";
const stripe = new Stripe(env.stripeSecretKey, {
apiVersion: "2022-08-01",
});
function getUUID(): T.UUID {
return uuidv4() as T.UUID;
}
export function canRemoveOneOutsideProvider(user: T.LingdocsUser): boolean {
if (user.email && user.password) {
return true;
}
const providersPresent = outsideProviders.filter(
(provider) => !!user[provider]
);
return providersPresent.length > 1;
}
export function getVerifiedEmail({
emails,
}: T.ProviderProfile): string | false {
return emails &&
emails.length &&
// @ts-ignore
emails[0].verified
? emails[0].value
: false;
}
export function getEmailFromGoogleProfile(profile: T.GoogleProfile): {
email: string | undefined;
verified: boolean;
} {
if (!profile.emails || profile.emails.length === 0) {
return { email: undefined, verified: false };
}
const em = profile.emails[0];
// @ts-ignore // but the verified value *is* there - if not it's still safe
const verified = !!em.verified;
return {
email: em.value,
verified,
};
}
export async function upgradeUser(
userId: T.UUID,
subscription?: T.StripeSubscription
): Promise<T.UpgradeUserResponse> {
// add user to couchdb authentication db
const { password, userDbName } = await addCouchDbAuthUser(userId);
// // create user db
// update LingdocsUser
const user = await updateLingdocsUser(userId, {
level: "student",
wordlistDbName: userDbName,
couchDbPassword: password,
upgradeToStudentRequest: undefined,
subscription,
});
if (user.email) {
sendAccountUpgradeMessage(user).catch(console.error);
}
return {
ok: true,
message: "user upgraded to student",
user,
};
}
export async function downgradeUser(
userId: T.UUID,
subscriptionId?: string
): Promise<T.DowngradeUserResponse> {
await deleteCouchDbAuthUser(userId);
if (subscriptionId) {
stripe.subscriptions.del(subscriptionId);
}
const user = await updateLingdocsUser(userId, {
level: "basic",
wordlistDbName: undefined,
couchDbPassword: undefined,
upgradeToStudentRequest: undefined,
subscription: undefined,
});
if (user.email) {
// TODO
// sendAccountDowngradeMessage(user).catch(console.error);
}
return {
ok: true,
message: "user downgraded to basic",
user,
};
}
export async function denyUserUpgradeRequest(userId: T.UUID): Promise<void> {
await updateLingdocsUser(userId, {
upgradeToStudentRequest: "denied",
});
}
export async function createNewUser(
input:
| {
strategy: "local";
email: string;
name: string;
passwordPlainText: string;
}
| {
strategy: "github";
profile: T.GitHubProfile;
}
| {
strategy: "google";
profile: T.GoogleProfile;
}
| {
strategy: "twitter";
profile: T.TwitterProfile;
}
): Promise<T.LingdocsUser> {
const userId = getUUID();
const now = getTimestamp();
if (input.strategy === "local") {
const email = await getEmailTokenAndHash();
const password = await getHash(input.passwordPlainText);
const newUser: T.LingdocsUser = {
_id: userId,
userId,
email: input.email,
emailVerified: email.hash,
name: input.name,
password,
level: "basic",
tests: [],
accountCreated: now,
lastLogin: now,
lastActive: now,
};
await sendVerificationEmail({
name: input.name,
uid: userId,
email: input.email || "",
token: email.token,
});
ntfy(`new LingDocs user ${input.name} - ${input.email}`);
const user = await insertLingdocsUser(newUser);
return user;
}
// GitHub || Twitter
if (input.strategy === "github" || input.strategy === "twitter") {
const newUser: T.LingdocsUser = {
_id: userId,
userId,
emailVerified: false,
name: input.profile.displayName || input.profile.username || "",
[input.strategy]: input.profile,
level: "basic",
tests: [],
accountCreated: now,
lastLogin: now,
lastActive: now,
};
const user = await insertLingdocsUser(newUser);
return user;
}
// Google
// TODO: Add e-mail in here
const { email, verified } = getEmailFromGoogleProfile(input.profile);
if (email && !verified) {
const em = await getEmailTokenAndHash();
const newUser: T.LingdocsUser = {
_id: userId,
userId,
email,
emailVerified: em.hash,
name: input.profile.displayName,
google: input.profile,
lastLogin: now,
tests: [],
lastActive: now,
accountCreated: now,
level: "basic",
};
const user = await insertLingdocsUser(newUser);
sendVerificationEmail({
name: newUser.name,
uid: newUser.userId,
email: newUser.email || "",
token: em.token,
}).catch(console.error);
return user;
}
const newUser: T.LingdocsUser = {
_id: userId,
userId,
email,
emailVerified: verified,
name: input.profile.displayName,
google: input.profile,
lastLogin: now,
tests: [],
lastActive: now,
accountCreated: now,
level: "basic",
};
const user = await insertLingdocsUser(newUser);
return user;
}

View File

@ -0,0 +1,128 @@
import * as AT from "../../../website/src/types/account-types";
import type { Request, Response, NextFunction } from "express";
import type {
NextApiHandler,
GetServerSidePropsContext,
GetServerSidePropsResult,
} from "next";
import sampleUsers from "./sample-users";
declare module "http" {
interface IncomingMessage {
user: AT.LingdocsUser | undefined;
}
}
const devSampleUser = getSampleUser();
function getSampleUser(): AT.LingdocsUser | "none" | undefined {
const e = process.env.DEV_SAMPLE;
if (e === "basic" || e === "student" || e === "admin") {
return sampleUsers[e];
}
if (e === "none") return e;
return undefined;
}
async function fetchUser(cookies: any): Promise<AT.LingdocsUser | undefined> {
if (!cookies) {
return undefined;
}
const cookie = typeof cookies === "string"
? cookies
: `__session=${cookies.__session}`;
try {
const r = await fetch("https://account.lingdocs.com/api/user", { headers: { cookie }});
const { ok, user } = await r.json();
if (ok === true && user) {
return user as AT.LingdocsUser;
}
} catch(e) { console.error(e) }
return undefined;
}
// functions adapted from https://github.com/vvo/iron-session and used similarily, to inculde
// the LingdocsUser in req when signed in
/**
* express middleware to include the LingdocsUser in req.user if signed in
*
* to get sample users, set the DEV_SAMPLE env var to "basic", "student", "editor", or "admin"
*
* @returns
*/
export async function lingdocsUserExpressMiddleware(req: Request, res: Response, next: NextFunction) {
const user = devSampleUser
? (devSampleUser === "none" ? undefined : devSampleUser)
: await fetchUser(req.headers.cookie);
Object.defineProperty(
req,
"user",
{ value: user, writable: false, enumerable: true },
);
next();
}
/**
* wrapper for a next api route to include the LingdocsUser if logged in
*
* Usage:
*
* in next app: pages/api/thing.ts
*
* export default withLingdocsUserApiRoute(
* async function thingRoute(req, res) {
* ...
*
* to get sample users, set the DEV_SAMPLE env var to "basic", "student", "editor", or "admin"
*
* @param handler
* @returns
*/
export function withLingdocsUserApiRoute(handler: NextApiHandler): NextApiHandler {
return async function nextApiHandlerWrappedWithLingdocsUser(req, res) {
const user = devSampleUser
? (devSampleUser === "none" ? undefined : devSampleUser)
: await fetchUser(req.headers.cookies);
Object.defineProperty(
req,
"user",
{ value: user, writable: false, enumerable: true },
);
return handler(req, res);
};
}
/**
* Wrapper for getServer side props to include the LingdocsUser if logged in
*
* usage:
*
* export const getServerSideProps = withLingdocsUserSsr(
* async function getServerSideProps({ req }) {
* ...
* to get sample users, set the DEV_SAMPLE env var to "basic", "student", "editor", or "admin"
*
* @param handler
* @returns
*/
export function withLingdocsUserSsr<
P extends { [key: string]: unknown } = { [key: string]: unknown },
>(
handler: (
context: GetServerSidePropsContext,
) => GetServerSidePropsResult<P> | Promise<GetServerSidePropsResult<P>>,
) {
return async function nextGetServerSidePropsHandlerWrappedWithLingdocsUser(
context: GetServerSidePropsContext,
) {
const user = devSampleUser
? (devSampleUser === "none" ? undefined : devSampleUser)
: await fetchUser(context.req.cookies);
Object.defineProperty(
context.req,
"user",
{ value: user, writable: false, enumerable: true },
);
return handler(context);
};
}

View File

@ -0,0 +1,180 @@
import { compare } from "bcryptjs";
import { PassportStatic } from "passport";
import { Strategy as LocalStrategy } from "passport-local";
import { OAuth2Strategy as GoogleStrategy } from "passport-google-oauth";
import { Strategy as GitHubStrategy } from "passport-github2";
import { Strategy as TwitterStrategy } from "passport-twitter";
import {
getLingdocsUser,
insertLingdocsUser,
updateLastLogin,
updateLingdocsUser,
} from "../lib/couch-db";
import {
createNewUser,
getVerifiedEmail,
getEmailFromGoogleProfile,
} from "../lib/user-utils";
import env from "../lib/env-vars";
import * as T from "../../../website/src/types/account-types";
export const outsideProviders: ("github" | "google" | "twitter")[] = ["github", "google", "twitter"];
function setupPassport(passport: PassportStatic) {
passport.use(new LocalStrategy({
usernameField: "email",
},
async function(username, password, done) {
try {
const user = await getLingdocsUser("email", username);
if (!user) return done(null, false, { message: "email not found" });
if (!user.password) return done(null, false, { message: "user doesn't have password" });
compare(password, user.password, (err, result) => {
if (err) return done(err);
if (result === true) {
const u = updateLastLogin(user);
insertLingdocsUser(u).then((usr) => {
return done(null, usr);
}).catch(console.error);
} else {
return done(null, false, { message: "incorrect password" });
}
});
} catch (e) {
// error looking up user from database
done(e);
}
}
));
passport.use(new GoogleStrategy({
clientID: "1059009861653-ndh517ctpnats30qlgmihsrol4pdcj12.apps.googleusercontent.com",
clientSecret: env.googleClientSecret,
callbackURL: "https://account.lingdocs.com/google/callback",
passReqToCallback: true,
},
async function(req, accessToken, refreshToken, profileRaw, done) {
const { _json, _raw, ...profile } = profileRaw;
const gProfile = { ...profile, accessToken, refreshToken };
try {
if (req.isAuthenticated()) {
if (!req.user) done(new Error("user lost"));
const otherAccountWSameGoogle = await getLingdocsUser("googleId", profile.id);
if (otherAccountWSameGoogle) {
return done(null, otherAccountWSameGoogle);
}
const u = await updateLingdocsUser(req.user.userId, { google: gProfile });
if (!u.email) {
// if the user is adding a google account and doesn't have a previous email, add the google email
const email = getVerifiedEmail(gProfile)
if (email) {
const emailAdded = await updateLingdocsUser(req.user.userId, { email, emailVerified: true });
return done(null, emailAdded);
}
}
return done(null, u);
}
// if there's a google account matching, log them in
const user = await getLingdocsUser("googleId", profile.id);
if (user) return done (null, user);
// if the person used their google email for a plain signup, add the google provider to it and sign in
const googleMail = getEmailFromGoogleProfile(gProfile);
if (googleMail.email) {
const otherAccountWSameEmail = await getLingdocsUser("email", googleMail.email);
if (otherAccountWSameEmail) {
await updateLingdocsUser(otherAccountWSameEmail.userId, { google: gProfile });
return done(null, otherAccountWSameEmail);
}
}
// otherwise create a brand new user
const u = await createNewUser({ strategy: "google", profile: gProfile });
return done(null, u);
} catch (e) {
done(e);
}
}
));
passport.use(new TwitterStrategy({
consumerKey: "Y6fwSL0BUx7PO8edFgiZMqcLf",
consumerSecret: env.twitterClientSecret,
callbackURL: "https://account.lingdocs.com/twitter/callback",
passReqToCallback: true,
}, async function(req, token, tokenSecret, profileRaw, done) {
const { _json, _raw, ...profile } = profileRaw;
const twitterProfile = { ...profile, token, tokenSecret };
try {
if (req.isAuthenticated()) {
if (!req.user) done(new Error("user lost"));
const otherAccountWSameTwitter = await getLingdocsUser("twitterId", twitterProfile.id);
if (otherAccountWSameTwitter) {
return done(null, otherAccountWSameTwitter);
}
const u = await updateLingdocsUser(req.user.userId, { twitter: twitterProfile });
return done(null, u);
}
const user = await getLingdocsUser("twitterId", profile.id);
if (user) return done (null, user);
const u = await createNewUser({ strategy: "twitter", profile: twitterProfile });
return done(null, u);
} catch (e) {
done(e);
}
}));
passport.use(new GitHubStrategy({
clientID: "37abff09e9baf39aff0a",
clientSecret: env.githubClientSecret,
callbackURL: "https://account.lingdocs.com/github/callback",
passReqToCallback: true,
},
async function(req: any, accessToken: any, refreshToken: any, profileRaw: any, done: any) {
// not getting refresh token
const { _json, _raw, ...profile } = profileRaw;
const ghProfile: T.GitHubProfile = { ...profile, accessToken };
try {
if (req.isAuthenticated()) {
if (!req.user) done(new Error("user lost"));
const otherAccountWSameGithub = await getLingdocsUser("githubId", ghProfile.id);
if (otherAccountWSameGithub) {
return done(null, otherAccountWSameGithub);
}
const u = await updateLingdocsUser(req.user.userId, { github: ghProfile });
return done(null, u);
}
const user = await getLingdocsUser("githubId", ghProfile.id);
if (user) return done (null, user);
const u = await createNewUser({ strategy: "github", profile: ghProfile });
return done(null, u);
} catch (e) {
done(e);
}
}));
// @ts-ignore
passport.serializeUser((user: LingdocsUser, cb) => {
// @ts-ignore
cb(null, user.userId);
});
passport.deserializeUser(async (userId: T.UUID, cb) => {
try {
const user = await getLingdocsUser("userId", userId);
if (!user) {
cb(null, false);
return;
}
// THIS IS ERRORING TOO MUCH!
// try {
// // skip if there's an update conflict
// const newUser = await updateLingdocsUser(userId, { lastActive: getTimestamp() });
// cb(null, newUser);
// } catch (e) {
// console.error(e);
// cb(null, user);
// }
cb(null, user);
} catch (err) {
cb(err, null);
}
});
}
export default setupPassport;

View File

@ -0,0 +1,32 @@
import session from "express-session";
import { Express } from "express";
import redis from "redis";
import inProd from "../lib/inProd";
import env from "../lib/env-vars";
const FileStore = !inProd ? require("session-file-store")(session) : undefined;
const RedisStore = require("connect-redis")(session);
function setupSession(app: Express) {
app.use(
session({
secret: env.cookieSecret,
name: "__session",
resave: true,
saveUninitialized: false,
proxy: inProd,
cookie: {
maxAge: 1000 * 60 * 60 * 24 * 7 * 30 * 6,
secure: inProd,
domain: inProd ? "lingdocs.com" : undefined,
httpOnly: true,
},
store: inProd
? new RedisStore({ client: redis.createClient() })
: new FileStore({}),
})
);
}
export default setupSession;

View File

@ -0,0 +1,210 @@
import express, { Response } from "express";
import {
deleteLingdocsUser,
getLingdocsUser,
updateLingdocsUser,
} from "../lib/couch-db";
import {
getHash,
compareToHash,
getEmailTokenAndHash,
} from "../lib/password-utils";
import {
sendUpgradeRequestToAdmin,
sendVerificationEmail,
} from "../lib/mail-utils";
import { upgradeUser } from "../lib/user-utils";
import * as T from "../../../website/src/types/account-types";
import env from "../lib/env-vars";
// TODO: ADD PROPER ERROR HANDLING THAT WILL RETURN JSON ALWAYS
function sendResponse(res: Response, payload: T.APIResponse) {
return res.send(payload);
}
const apiRouter = express.Router();
// Guard all api with authentication
apiRouter.use((req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
const r: T.APIResponse = { ok: false, error: "401 Unauthorized" };
return res.status(401).send(r);
});
/**
* gets the LingdocsUser object for the user signed in
*/
apiRouter.get("/user", (req, res, next) => {
if (!req.user) return next("user not found");
sendResponse(res, { ok: true, user: req.user });
});
/**
* adds (passed) test results to the record of the user signed in
*/
apiRouter.put("/user/tests", async (req, res, next) => {
if (!req.user) return next("user not found");
try {
const { tests } = req.body as T.PostTestResultsBody;
await updateLingdocsUser(req.user.userId, { tests });
sendResponse(res, {
ok: true,
message: "posted test results",
tests,
});
} catch (e) {
next(e);
}
});
/**
* receives a request to change or add a user's own password
*/
apiRouter.post("/password", async (req, res, next) => {
if (!req.user) return next("user not found");
const { oldPassword, password, passwordConfirmed } = req.body;
const addingFirstPassword = !req.user.password;
if (!oldPassword && !addingFirstPassword) {
return sendResponse(res, {
ok: false,
error: "Please enter your old password",
});
}
if (!password) {
return sendResponse(res, {
ok: false,
error: "Please enter a new password",
});
}
if (!req.user.email) {
return sendResponse(res, {
ok: false,
error: "You need to add an e-mail address first",
});
}
if (req.user.password) {
const matchedOld =
(await compareToHash(oldPassword, req.user.password)) ||
!req.user.password;
if (!matchedOld) {
return sendResponse(res, { ok: false, error: "Incorrect old password" });
}
}
if (password !== passwordConfirmed) {
return sendResponse(res, {
ok: false,
error: "New passwords do not match",
});
}
if (password.length < 6) {
return sendResponse(res, { ok: false, error: "New password too short" });
}
const hash = await getHash(password);
await updateLingdocsUser(req.user.userId, { password: hash });
sendResponse(res, {
ok: true,
message: addingFirstPassword ? "Password added" : "Password changed",
});
});
/**
* receives a request to generate a new e-mail verification token and send e-mail
*/
apiRouter.put("/email-verification", async (req, res, next) => {
try {
if (!req.user) throw new Error("user not found");
const { token, hash } = await getEmailTokenAndHash();
const u = await updateLingdocsUser(req.user.userId, {
emailVerified: hash,
});
sendVerificationEmail({
name: u.name,
uid: u.userId,
email: u.email || "",
token,
})
.then(() => {
sendResponse(res, { ok: true, message: "e-mail verification sent" });
})
.catch((err) => {
sendResponse(res, { ok: false, error: err });
});
} catch (e) {
next(e);
}
});
apiRouter.put("/user/upgrade", async (req, res, next) => {
if (!req.user) throw new Error("user not found");
try {
const givenPassword = (req.body.password || "") as string;
const studentPassword = env.upgradePassword;
if (givenPassword.toLowerCase().trim() !== studentPassword.toLowerCase()) {
const wrongPass: T.UpgradeUserResponse = {
ok: false,
error: "incorrect password",
};
res.send(wrongPass);
return;
}
const { userId } = req.user;
const user = await getLingdocsUser("userId", userId);
if (!user) throw new Error("user lost");
if (user.level !== "basic") {
const alreadyUpgraded: T.UpgradeUserResponse = {
ok: true,
message: "user already upgraded",
user,
};
res.send(alreadyUpgraded);
return;
}
const upgraded: T.UpgradeUserResponse = await upgradeUser(userId);
res.send(upgraded);
} catch (e) {
next(e);
}
});
apiRouter.post("/user/upgradeToStudentRequest", async (req, res, next) => {
if (!req.user) throw new Error("user not found");
try {
if (req.user.level === "student" || req.user.level === "editor") {
res.send({ ok: true, message: "user already upgraded" });
return;
}
sendUpgradeRequestToAdmin(req.user).catch(console.error);
await updateLingdocsUser(req.user.userId, {
upgradeToStudentRequest: "waiting",
});
res.send({ ok: true, message: "request for upgrade sent" });
} catch (e) {
next(e);
}
});
/**
* deletes a users own account
*/
apiRouter.delete("/user", async (req, res, next) => {
try {
if (!req.user) throw new Error("user not found");
await deleteLingdocsUser(req.user.userId);
sendResponse(res, { ok: true, message: "user deleted" });
} catch (e) {
next(e);
}
});
/**
* signs out the user signed in
*/
apiRouter.post("/sign-out", (req, res) => {
req.logOut();
sendResponse(res, { ok: true, message: "signed out" });
});
export default apiRouter;

View File

@ -0,0 +1,455 @@
import { Router } from "express";
import { PassportStatic } from "passport";
import {
deleteLingdocsUser,
getAllFeedback,
getAllLingdocsUsers,
getLingdocsUser,
updateLingdocsUser,
} from "../lib/couch-db";
import {
createNewUser,
canRemoveOneOutsideProvider,
downgradeUser,
} from "../lib/user-utils";
import {
getHash,
getURLToken,
compareToHash,
getEmailTokenAndHash,
} from "../lib/password-utils";
import { upgradeUser, denyUserUpgradeRequest } from "../lib/user-utils";
import { validateReCaptcha } from "../lib/recaptcha";
import { getTimestamp } from "../lib/time-utils";
import {
getAddress,
sendPasswordResetEmail,
sendVerificationEmail,
} from "../lib/mail-utils";
import { outsideProviders } from "../middleware/setup-passport";
import inProd from "../lib/inProd";
import * as T from "../../../website/src/types/account-types";
const authRouter = (passport: PassportStatic) => {
const router = Router();
router.get("/", (req, res) => {
if (req.isAuthenticated()) {
return res.redirect("/user");
}
res.render("login", { recaptcha: "", inProd });
});
router.get("/user", (req, res) => {
if (!req.isAuthenticated()) {
return res.redirect("/");
}
res.render("user", {
user: req.user,
error: null,
removeProviderOption: canRemoveOneOutsideProvider(req.user),
});
});
router.get("/delete-account", (req, res) => {
res.render("delete-account", {
user: req.user,
error: null,
});
});
router.post("/user", async (req, res, next) => {
const page = "user";
if (!req.user) return next("user not found");
const name = req.body.name as string;
const email = req.body.email as string;
if (email !== req.user.email) {
if (name !== req.user.name)
await updateLingdocsUser(req.user.userId, { name });
const withSameEmail =
email !== "" && (await getLingdocsUser("email", email));
if (withSameEmail) {
return res.render(page, {
user: { ...req.user, email },
error: "email taken",
removeProviderOption: canRemoveOneOutsideProvider(req.user),
});
}
// TODO: ABSTRACT THE PROCESS OF GETTING A NEW EMAIL TOKEN AND MAILING!
const { token, hash } = await getEmailTokenAndHash();
const updated = await updateLingdocsUser(req.user.userId, {
name,
email,
emailVerified: hash,
});
// TODO: AWAIT THE E-MAIL SEND TO MAKE SURE THE E-MAIL WORKS!
sendVerificationEmail({
name: updated.name,
uid: updated.userId,
email: updated.email || "",
token,
});
return res.render(page, {
user: updated,
error: null,
removeProviderOption: canRemoveOneOutsideProvider(req.user),
});
}
const updated = await updateLingdocsUser(req.user.userId, { name });
// need to do this because sometimes the update seems slow?
return res.render(page, {
user: updated,
error: null,
removeProviderOption: canRemoveOneOutsideProvider(req.user),
});
});
router.post("/login", async (req, res, next) => {
if (inProd) {
const success = await validateReCaptcha(req.body.token);
if (!success) {
return res.render("login", { recaptcha: "fail", inProd });
}
}
passport.authenticate(
"local",
(err, user: T.LingdocsUser | undefined, info) => {
if (err) throw err;
if (!user && info.message === "email not found") {
return res.send({ ok: false, newSignup: true });
}
if (!user)
res.send({
ok: false,
message: "Incorrect password",
});
else {
req.logIn(user, (err) => {
if (err) return next(err);
res.send({ ok: true, user });
});
}
}
)(req, res, next);
});
router.get(
"/google",
passport.authenticate("google", {
// @ts-ignore - needed for getting refreshToken]
accessType: "offline",
scope: [
"openid",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
],
})
);
router.get(
"/github",
passport.authenticate("github", {
scope: ["read:user", "user:email"],
})
);
router.get("/twitter", passport.authenticate("twitter"));
// all callback and remove routes/functions are the same for each provider
outsideProviders.forEach((provider) => {
router.get(
`/${provider}/callback`,
passport.authenticate(provider, {
successRedirect: "/user",
failureRedirect: "/",
})
);
router.post(`/${provider}/remove`, async (req, res, next) => {
try {
if (!req.user) return next("user not found");
if (!canRemoveOneOutsideProvider(req.user))
return res.redirect("/user");
await updateLingdocsUser(
req.user.userId,
// @ts-ignore - shouldn't need this
{ [provider]: undefined }
);
return res.redirect("/user");
} catch (e) {
next(e);
}
});
});
router.post("/register", async (req, res, next) => {
try {
const { email, password, name } = req.body;
const existingUser = await getLingdocsUser("email", email);
if (existingUser)
return res.send({ ok: false, message: "User Already Exists" });
try {
const user = await createNewUser({
strategy: "local",
email,
passwordPlainText: password,
name,
});
req.logIn(user, (err) => {
if (err) return next(err);
return res.send({ ok: true, user });
});
} catch (e) {
console.error(e);
return res.send({ ok: false, message: "Invalid E-mail" });
}
} catch (e) {
next(e);
}
});
router.get("/admin", async (req, res, next) => {
try {
if (!req.user || !req.user.admin) {
return res.redirect("/");
}
const users = (await getAllLingdocsUsers()).sort(
(a, b) => (a.accountCreated || 0) - (b.accountCreated || 0)
);
const tests = getTestCompletionSummary(users);
res.render("admin", { users, tests });
} catch (e) {
next(e);
}
});
router.get("/grammar-feedback", async (req, res, next) => {
try {
if (!req.user || !req.user.admin) {
return res.redirect("/");
}
const docs = await getAllFeedback();
res.render("grammar-feedback", { docs });
} catch (e) {
next(e);
}
});
router.get("/privacy", (req, res) => {
res.render("privacy");
});
/**
* Grant request for upgrade to student
*/
router.post(
"/admin/upgradeToStudent/:userId/:grantOrDeny",
async (req, res, next) => {
try {
if (!req.user || !req.user.admin) {
return res.redirect("/");
}
const userId = req.params.userId as T.UUID;
const grantOrDeny = req.params.grantOrDeny as "grant" | "deny";
if (grantOrDeny === "grant") {
await upgradeUser(userId);
} else {
await denyUserUpgradeRequest(userId);
}
res.redirect("/admin");
} catch (e) {
next(e);
}
}
);
router.post("/downgradeToBasic", async (req, res, next) => {
try {
if (!req.user) {
return res.send({ ok: false, error: "user not logged in" });
}
const subscription =
"subscription" in req.user ? req.user.subscription : undefined;
await downgradeUser(
req.user.userId,
subscription ? subscription.id : undefined
);
res.send({
ok: true,
message: `account downgraded to basic${
subscription ? " and subscription cancelled" : ""
}`,
});
} catch (e) {
next(e);
}
});
router.delete("/admin/:userId", async (req, res, next) => {
try {
// TODO: MAKE PROPER MIDDLEWARE WITH TYPING
if (!req.user || !req.user.admin) {
return res.redirect("/");
}
const toDelete = req.params.userId as T.UUID;
await deleteLingdocsUser(toDelete);
res.send({ ok: true, message: "user deleted" });
} catch (e) {
next(e);
}
});
router.get("/email-verification/:uuid/:token", async (req, res, next) => {
const page = "email-verification";
const { uuid, token } = req.params;
try {
const user = await getLingdocsUser("userId", uuid);
if (!user) {
return res.render(page, { ok: false, message: "not found" });
}
if (user.emailVerified === true) {
return res.render(page, { ok: true, message: "already verified" });
}
if (user.emailVerified === false) {
return res.render(page, { ok: false, message: "invalid token" });
}
const result = await compareToHash(token, user.emailVerified);
if (result === true) {
await updateLingdocsUser(user.userId, { emailVerified: true });
return res.render(page, { ok: true, message: "verified" });
} else {
res.render(page, { ok: false, message: "invalid token" });
}
} catch (e) {
return res.render(page, { ok: false, message: "error verifying e-mail" });
}
});
router.get("/password-reset", (req, res) => {
const email = req.query.email || "";
res.render("password-reset-request", { email, done: false });
});
router.post("/password-reset", async (req, res, next) => {
const page = "password-reset-request";
const email = req.body.email || "";
try {
const user = await getLingdocsUser("email", email);
if (!user) {
console.log("password reset attempt on non-existant e-mail");
return res.render(page, { email, done: false });
}
if (user.emailVerified !== true) {
console.log("password reset attempt on an unverified e-mail");
return res.render(page, { email, done: false });
}
// TODO: SHOULD THIS BE NOT ALLOWED?
// TODO: PROPER ERROR MESSAGING IN ALL THIS!!
if (!user.password) {
console.log("password reset attempt on an account without a password");
return res.render(page, { email, done: false });
}
const token = getURLToken();
const tokenHash = await getHash(token);
const u = await updateLingdocsUser(user.userId, {
passwordReset: { tokenHash, requestedOn: getTimestamp() },
});
await sendPasswordResetEmail(u, token);
return res.render(page, { email, done: true });
} catch (e) {
next(e);
}
});
router.get("/password-reset/:uuid/:token", async (req, res, next) => {
const page = "password-reset";
const { uuid, token } = req.params;
const user = await getLingdocsUser("userId", uuid);
if (!user || !user.passwordReset) {
return res.render(page, { ok: false, user: null, message: "not found" });
}
// TODO: ALSO CHECK IF THE RESET IS FRESH ENOUGH
const result = await compareToHash(token, user.passwordReset.tokenHash);
if (result === true) {
return res.render(page, { ok: true, user, token, message: "" });
} else {
res.render(page, { ok: false, user: null, message: "invalid token" });
}
});
router.post("/password-reset/:uuid/:token", async (req, res, next) => {
const page = "password-reset";
const { uuid, token } = req.params;
const { password, passwordConfirmed } = req.body;
const user = await getLingdocsUser("userId", uuid);
if (!user || !user.passwordReset) {
return res.render(page, { ok: false, message: "not found" });
}
const result = await compareToHash(token, user.passwordReset.tokenHash);
if (!result)
return res.render(page, {
ok: false,
user: null,
message: "invalid token",
});
const passwordsMatch = password === passwordConfirmed;
if (passwordsMatch) {
const hash = await getHash(password);
await updateLingdocsUser(user.userId, { password: hash });
return res.render(page, { ok: true, user, message: "password reset" });
} else {
return res.render(page, {
ok: false,
user,
message: "passwords don't match",
});
}
});
router.post("/sign-out", (req, res) => {
req.logOut();
res.redirect("/");
});
return router;
};
function getTestCompletionSummary(users: T.LingdocsUser[]) {
const tests: { id: string; passes: number; fails: number }[] = [];
users.forEach((u) => {
const usersTests = removeDuplicateTests(u.tests);
usersTests.forEach((ut) => {
const ti = tests.findIndex((x) => x.id === ut.id);
if (ti === -1) {
tests.push({
id: ut.id,
...(ut.done ? { passes: 1, fails: 0 } : { passes: 0, fails: 1 }),
});
} else tests[ti][ut.done ? "passes" : "fails"]++;
});
});
return tests;
}
function removeDuplicateTests(tests: T.TestResult[]): T.TestResult[] {
return tests.reduceRight(
(acc, curr) => {
const redundant = acc.filter(
(x) => x.id === curr.id && x.done === curr.done
);
return redundant.length ? acc : [...acc, curr];
},
[...tests]
);
}
// function getTestCompletionSummary(users: T.LingdocsUser[]) {
// const tests: { id: string, passes: number }[] = [];
// users.forEach(u => (
// Array.from(new Set(u.tests.map(x => x.id))).forEach(id => {
// const ti = tests.findIndex(x => x.id === id);
// if (ti > -1) tests[ti].passes++;
// else tests.push({ id, passes: 1 });
// })
// ));
// return tests;
// }
export default authRouter;

View File

@ -0,0 +1,54 @@
import express from "express";
import {
allWordsCollection,
collection,
getEntries,
updateDictionary,
} from "../lib/dictionary";
import { scriptToPhonetics } from "../lib/scriptToPhonetics";
const dictionaryRouter = express.Router();
dictionaryRouter.post("/update", async (req, res, next) => {
const result = await updateDictionary();
res.send({ ok: true, result });
});
dictionaryRouter.post("/script-to-phonetics", async (req, res, next) => {
if (!allWordsCollection) {
return res.send({ ok: false, message: "allWords not ready" });
}
const text = req.body.text as unknown;
const accents = req.body.accents as unknown;
if (!text || typeof text !== "string" || typeof accents !== "boolean") {
return res.status(400).send({ ok: false, error: "invalid query" });
}
const results = await scriptToPhonetics(text, accents);
res.send({ ok: true, results });
});
dictionaryRouter.post("/entries", async (req, res, next) => {
if (!collection) {
return res.send({ ok: false, message: "dictionary not ready" });
}
const ids = req.body.ids as (number | string)[];
if (!Array.isArray(ids)) {
return res.status(400).send({ ok: false, error: "invalid query" });
}
const results = await getEntries(ids);
return res.send(results);
});
dictionaryRouter.get("/entries/:id", async (req, res, next) => {
if (!collection) {
return res.send({ ok: false, message: "dictionary not ready" });
}
const ids = req.params.id.split(",").map((x) => {
const n = parseInt(x);
return Number.isNaN(n) ? x : n;
});
const results = await getEntries(ids);
return res.send(results);
});
export default dictionaryRouter;

View File

@ -0,0 +1,41 @@
import express, { Response } from "express";
import * as T from "../../../website/src/types/account-types";
import { addFeedback } from "../lib/couch-db";
import { ntfy } from "../lib/ntfy";
// import env from "../lib/env-vars";
// TODO: ADD PROPER ERROR HANDLING THAT WILL RETURN JSON ALWAYS
function sendResponse(res: Response, payload: T.APIResponse) {
return res.send(payload);
}
const feedbackRouter = express.Router();
/**
* receives a piece of feedback
*/
feedbackRouter.put("/", (req, res, next) => {
const { anonymous, ...feedback } = req.body;
const user = anonymous
? "anonymous"
: req.user
? req.user.name
: "not logged in";
addFeedback({
user,
feedback,
})
.then(() => {
ntfy(JSON.stringify(feedback));
res.send({ ok: true, message: "feedback received" });
})
.catch((e) => {
console.error("error receiving feedback");
console.error("feedback missed", feedback);
console.error(e);
next("error receiving feedback");
});
});
export default feedbackRouter;

View File

@ -0,0 +1,136 @@
import express from "express";
import * as T from "../../../website/src/types/account-types";
import env from "../lib/env-vars";
import Stripe from "stripe";
import { downgradeUser, upgradeUser } from "../lib/user-utils";
import { addToPaymentsDb } from "../lib/couch-db";
const stripe = new Stripe(env.stripeSecretKey, {
apiVersion: "2022-08-01",
});
const paymentRouter = express.Router();
paymentRouter.post(
'/webhook',
express.raw({ type: 'application/json' }),
async (request, response) => {
let event = request.body;
// Replace this endpoint secret with your endpoint's unique secret
// If you are testing with the CLI, find the secret by running 'stripe listen'
// If you are using an endpoint defined with the API or dashboard, look in your webhook settings
// at https://dashboard.stripe.com/webhooks
// Only verify the event if you have an endpoint secret defined.
// Otherwise use the basic event deserialized with JSON.parse
const endpointSecret = env.stripeWebhookSecret;
if (endpointSecret) {
// Get the signature sent by Stripe
const signature = request.headers['stripe-signature'] || "";
try {
event = stripe.webhooks.constructEvent(
request.body,
signature,
endpointSecret
);
} catch (err: any) {
console.log(`⚠️ Webhook signature verification failed.`, err.message);
return response.sendStatus(400);
}
}
let subscription: Stripe.Subscription;
// Handle the event
const userId = event.data.object.metadata.userId as T.UUID;
switch (event.type) {
case 'customer.subscription.deleted':
subscription = event.data.object;
addToPaymentsDb({
action: "deleted",
subscription,
});
await downgradeUser(userId);
// Then define and call a method to handle the subscription deleted.
// handleSubscriptionDeleted(subscriptionDeleted);
break;
case 'customer.subscription.created':
subscription = event.data.object;
addToPaymentsDb({
action: "created",
subscription,
});
await upgradeUser(userId, subscription);
// TODO: save subscription to db
break;
default:
// Unexpected event type
console.log(`Unhandled event type ${event.type}.`);
}
// Return a 200 response to acknowledge receipt of the event
response.send();
}
);
// Guard all api with authentication
paymentRouter.use((req, res, next) => {
if (req.isAuthenticated()) {
return next();
}
const r: T.APIResponse = { ok: false, error: "401 Unauthorized" };
return res.status(401).send(r);
});
paymentRouter.post("/create-checkout-session", async (req, res, next) => {
if (!req.user) {
return next("not logged in");
}
try {
const source = req.query.source;
const returnUrl = source === "account"
? "https://dictionary.lingdocs.com/account"
: source === "wordlist"
? "https://dictionary.lingdocs.com"
: "https://account.lingdocs.com/user";
const price = req.body.priceId;
const session = await stripe.checkout.sessions.create({
billing_address_collection: 'auto',
line_items: [
{
price,
quantity: 1,
},
],
subscription_data: {
metadata: {
userId: req.user.userId,
startTime: Date.now(),
cycle: price === "price_1Lt8NqJnpCQCjf9pN7CQUjjO"
? "monthly" : "yearly",
},
},
mode: 'subscription',
success_url: returnUrl,
cancel_url: returnUrl,
});
if (!session.url) {
return next("error creating session url");
}
res.redirect(303, session.url);
} catch (err) {
console.error(err);
return next("error connection to Stripe");
}
});
paymentRouter.post('/create-portal-session', async (req, res, next) => {
if (!req.user) {
return next("error finding user");
}
const portalSession = await stripe.billingPortal.sessions.create({
customer: req.user.userId,
return_url: "/",
});
res.redirect(303, portalSession.url);
});
export default paymentRouter;

72
account/tsconfig.json Normal file
View File

@ -0,0 +1,72 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ES2022", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": ["ES2023"], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": ["src/**/*"]
}

111
account/views/admin.ejs Normal file
View File

@ -0,0 +1,111 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="LingDocs Signin">
<title>Admin · LingDocs</title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
</head>
<script>
function handleDeleteUser(uid, name) {
const answer = confirm(`Are you sure you want to delete ${name}?`);
if (answer) {
fetch(`/admin/${uid}`, {
method: "DELETE",
}).then((res) => res.json()).then((res) => {
console.log(res);
if (res.ok) {
window.location = "/admin";
}
}).catch(console.error);
}
}
</script>
<body>
<div class="container">
<h1 class="my-4">LingDocs Auth Admin</h1>
<p><%= users.length %> Users</p>
<table class="table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Email</th>
<th scope="col">Providers</th>
<th scope="col">Level</th>
<th scope="col">Joined</th>
<th shope="col"></th>
</tr>
</thead>
<tbody>
<% for(var i=0; i < users.length; i++) { %>
<tr>
<td><%= users[i].name %> <% if (users[i].admin) { %>
<i class="fas fa-id-badge ml-2"></i>
<% } %>
</td>
<td><%= users[i].email %></td>
<td>
<% if (users[i].password && users[i].email) { %>
<i class="fas fa-key mr-2"></i>
<% } %>
<% if (users[i].google) { %>
<i class="fab fa-google mr-2"></i>
<% } %>
<% if (users[i].twitter) { %>
<i class="fab fa-twitter mr-2"></i>
<% } %>
<% if (users[i].github) { %>
<i class="fab fa-github mr-2"></i>
<% } %>
</td>
<td>
<% if (users[i].upgradeToStudentRequest === "waiting") { %>
<div class="d-flex flex-row">
<div>Requested Upgrade </div>
<div>
<form action="/admin/upgradeToStudent/<%= users[i].userId %>/grant" method="POST">
<button class="btn btn-sm btn-success mx-2" type="submit"><i class="fas fa-thumbs-up mr-2"></i> Grant </button>
</form>
</div>
<div>
<form action="/admin/upgradeToStudent/<%= users[i].userId %>/deny" method="POST">
<button class="btn btn-sm btn-danger" type="submit"><i class="fas fa-thumbs-down mr-2"></i> Deny </button>
</form>
</div>
</div>
<% } else if (users[i].upgradeToStudentRequest === "waiting"){ %>
Upgrade Denied
<% } else if (users[i].level === "basic") { %>
<div><%= users[i].level %></div>
<div>
<form action="/admin/upgradeToStudent/<%= users[i].userId %>/grant" method="POST">
<button class="btn btn-sm btn-success mx-2" type="submit"><i class="fas fa-thumbs-up mr-2"></i> Upgrade </button>
</form>
</div>
<% } else { %>
<%= users[i].level %>
<% } %>
</td>
<td>
<% if (users[i].accountCreated) { %>
<%= new Date(users[i].accountCreated).toString().slice(0, 15) %>
<% } %>
</td>
<td>
<button class="btn btn-sm btn-danger" onClick="handleDeleteUser('<%= users[i].userId %>', '<%= users[i].name %>')"><i class="fa fa-trash"></i></button>
</td>
</tr>
<% } %>
</tbody>
</table>
<div>
<h5>Tests Completed: Pass / Fail</h5>
<% for(var i=0; i < tests.length; i++) { %>
<div><%= tests[i].id %>: <%= tests[i].passes %> / <%= tests[i].fails %></div>
<% } %>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,25 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="LingDocs Signin">
<title>Account · LingDocs</title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
<script>
</script>
</head>
<body>
<div class="container" style="max-width: 800px;">
<h2 class="mt-4 mb-4 text-center">How to Delete your LingDocs Account</h2>
<p>To delete your account for the LingDocs Pashto Dictionary and LingDocs Pashto Grammar:</p>
<ul>
<li>Go to <a href="https://account.lingdocs.com/user">https://account.lingdocs.com/user</a></li>
<li>If necessary, log in</li>
<li>Once logged in, scroll down and click on the "Delete Account" button</li>
</ul>
<p>Deleting your account will permanently delete all associated data with your account. All user ID data and personal wordlist data created will also be deleted forever.</p>
</body>
</html>

View File

@ -0,0 +1,31 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="LingDocs Signin">
<title>E-mail Verification · LingDocs</title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="text-center">
<div class="container">
<h2 class="mt-4 mb-4">LingDocs Email Verification</h2>
<% if (message === "not found") { %>
<p>Invalid Verification Link 👎</p>
<% } %>
<% if (message === "already verified") { %>
<p>Your e-mail has already been verified. 👍</p>
<% } %>
<% if (message === "verified") { %>
<p>Thank you. Your e-mail has been verified. 👍</p>
<% } %>
<!-- TODO: DYNAMIC DOMAIN HERE! -->
<% if (message === "invalid token") { %>
<p>That's an older or expired verification code. Please check for the most recent verification email or request another from the <a href="https://account.lingdocs.com/user">account page</a>.</p>
<% } %>
<% if (message === "error verifying e-mail") { %>
<p>Sorry! There was an error verifying your e-mail. Please try again later.</p>
<% } %>
</div>
</body>
</html>

View File

@ -0,0 +1,49 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="LingDocs Signin">
<title>Grammar Feedback · LingDocs</title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h1 class="my-4">LingDocs Grammar Feedback</h1>
<p><%= docs.length %> pieces of feedback</p>
<table class="table">
<thead>
<tr>
<th scope="col">Date</th>
<th scope="col">User</th>
<th scope="col">Chapter</th>
<th scope="col">Feedback</th>
<th scope="col">Rating</th>
</tr>
</thead>
<tbody>
<% for(var i=0; i < docs.length; i++) { %>
<tr>
<td>
<%= new Date(docs[i].feedback.ts).toDateString() %>
</td>
<td>
<%= docs[i].user %>
</td>
<td>
<%= docs[i].feedback.chapter %>
</td>
<td>
<%= docs[i].feedback.feedback %>
</td>
<td>
<%= docs[i].feedback.rating %>
</td>
</tr>
<% } %>
</tbody>
</table>
</div>
</body>
</html>

133
account/views/login.ejs Normal file
View File

@ -0,0 +1,133 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="LingDocs Signin">
<title>Signin · LingDocs</title>
<link rel="canonical" href="https://account.lingdocs.com">
<link href="/css/bootstrap.min.css" rel="stylesheet">
<style>
.bd-placeholder-img {
border-radius: 30px;
}
</style>
<!-- Custom styles for this template -->
<link href="/css/signin.css" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
<% if (inProd) { %>
<script src="https://www.google.com/recaptcha/api.js?render=6LcVjAUcAAAAAD0jviyYjUjuvjTMgdwx4H6kNoHH" async defer></script>
<% } %>
</head>
<body class="text-center">
<main class="form-signin">
<form id="signin-form">
<img class="mb-4" src="/img/lingdocs-logo.png" alt="" height="60" width="60">
<h1 class="h3 mb-4 fw-normal">Sign in to LingDocs</h1>
<!-- <p class="small mb-2">New? Enter an e-mail and password to sign up</p> -->
<div class="form-floating mt-3">
<input type="email" required class="form-control" id="emailInput" placeholder="name@example.com">
<label for="floatingInput">Email address</label>
</div>
<div class="form-floating">
<input type="password" required minlength="6" class="form-control" id="passwordInput" placeholder="Password">
<label for="floatingPassword">Password</label>
</div>
<div class="form-floating" id="name-form" style="display:none">
<input type="text" class="form-control" id="nameInput">
<label for="floatingPassword">Name</label>
</div>
<div class="small text-left">
<a href="/password-reset" tabindex="-1">Forgot Password?</a>
</div>
<div id="response" style="display: none;" class="alert alert-success" role="alert">
</div>
<button class="g-recaptcha mt-3 w-100 btn btn-lg btn-primary" type="submit" id="sign-in-button">Sign In / Up</button>
<button style="display: none;" class="mt-3 w-100 btn btn-lg btn-secondary" type="button" id="cancel-sign-up-button">Cancel Sign Up</button>
<% if (inProd) { %>
<div
class="g-recaptcha"
id="recaptcha-container"
data-sitekey="6LcVjAUcAAAAAD0jviyYjUjuvjTMgdwx4H6kNoHH"
data-callback="captchaCallback"
data-size="invisible">
</div>
<% } %>
</form>
<p class="mt-3">or</p>
<a href="/google" class="mt-1 w-100 btn btn-lg btn-secondary" role="button"><i class="fab fa-google mr-2"></i> Sign In With Google</a>
<a href="/twitter" class="mt-3 w-100 btn btn-lg btn-secondary" role="button"><i class="fab fa-twitter mr-2"></i> Sign In With Twitter</a>
<a href="/github" class="mt-3 w-100 btn btn-lg btn-secondary" role="button"><i class="fab fa-github mr-2"></i> Sign In With GitHub</a>
<p class="mt-5 text-muted">&copy; <script type="text/javascript">document.write(new Date().getFullYear());</script><noscript>2023</noscript> <a href="https://www.lingdocs.com/">LingDocs.com</a></p>
<p class="mt-3 text-muted small"><a href="/privacy">privacy policy</a></p>
</main>
</body>
<% if (recaptcha === "fail") { %>
<script>
alert("reCaptcha failed");
</script>
<% } %>
<script>
const form = document.getElementById("signin-form");
const signInButton = document.getElementById("sign-in-button");
const cancelSignUpButton = document.getElementById("cancel-sign-up-button");
const nameForm = document.getElementById("name-form");
const response = document.getElementById("response");
cancelSignUpButton.addEventListener("click", (e) => {
e.preventDefault();
nameForm.style = "display: none;";
nameForm.innerHTML = "";
response.innerHTML = "";
response.style = "display: none;";
cancelSignUpButton.style = "display: none;";
signInButton.innerHTML = "Sign In";
});
form.addEventListener("submit", handleSubmit, true);
function captchaCallback(token) {
const email = document.getElementById("emailInput").value.trim();
const password = document.getElementById("passwordInput").value.trim();
const name = document.getElementById("nameInput").value.trim();
fetch(name ? "/register" : "/login", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password, name, token }),
}).then((res) => res.json())
.then((res) => {
console.log({ res });
if (res.ok) {
location.reload();
}
if (!res.ok) {
if (res.newSignup) {
nameForm.style = "";
response.className = "alert alert-info mt-3";
response.innerText = "Enter your name to finish signup";
response.style = "";
signInButton.innerHTML = "Sign Up";
cancelSignUpButton.style = "";
} else {
response.className = "alert alert-warning mt-3";
response.innerText = res.message;
response.style = "";
}
}
});
}
<% if (inProd) { %>
function handleSubmit(e) {
e.preventDefault();
grecaptcha.execute();
}
<% } else { %>
function handleSubmit(e) {
e.preventDefault();
captchaCallback("");
}
<% } %>
</script>
</html>

View File

@ -0,0 +1,27 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="LingDocs Signin">
<title>Password Reset · LingDocs</title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h2 class="mt-4 mb-4 text-center">Reset your LingDocs Password</h2>
<% if (!done) { %>
<form method="POST" class="mb-4" style="max-width: 500px; margin: 0 auto;">
<div>
<label for="email" class="form-label">Email:</label>
<input required name="email" type="email" class="form-control" id="email" value="<%= email %>">
</div>
<button type="submit" class="btn btn-primary mt-4">Reset Password</button>
</form>
<% } else { %>
<p>If <strong><%= email %></strong> is a <em>verified</em> e-mail in our system, we sent a password reset email.</p>
<% } %>
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,39 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="LingDocs Signin">
<title>Password Reset · LingDocs</title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h2 class="mt-4 mb-4 text-center">Reset your LingDocs Password</h2>
<% if (user && message === "password reset") { %>
<p>Ok, <%= user.name %>, the password for your account with <strong><%= user.email %></strong> has been reset. 👍</p>
<p><a href="/">Login</a></p>
<% } else if (user) { %>
<form method="POST" class="mb-4" style="max-width: 500px; margin: 0 auto;">
<div>
<label for="password" class="form-label">New Password:</label>
<input required minlength="6" name="password" type="password" class="form-control" id="password" value="">
</div>
<div class="mt-2">
<label for="passwordConfirmed" class="form-label">Confirm New Password:</label>
<input required minlength="6" name="passwordConfirmed" type="password" class="form-control" id="passwordConfirmed" value="">
</div>
<% if (message === "passwords don't match") { %>
<div class="alert alert-warning mt-3" role="alert">
Passwords don't match
</div>
<% } %>
<button type="submit" class="btn btn-primary mt-4">Reset Password</button>
</form>
<% } else { %>
<p>Invalid Password Reset Link</p>
<% } %>
</div>
</div>
</body>
</html>

55
account/views/privacy.ejs Normal file
View File

@ -0,0 +1,55 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="LingDocs Signin">
<title>Privacy · LingDocs</title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
</head>
<body>
<div class="container pb-4">
<h2 class="my-3">LingDocs Privacy Policy</h2>
<h4 class="mb-3">
<a href="/">Login</a>
</h4>
<p>
We are committed to maintaining the accuracy, confidentiality, and security of your personally identifiable information ("Personal Information"). As part of this commitment, our privacy policy governs our actions as they relate to the collection, use and disclosure of Personal Information. Our privacy policy is based upon the values set by the Canadian Standards Association's Model Code for the Protection of Personal Information and Canada's Personal Information Protection and Electronic Documents Act.
</p>
<h4>1. Introduction</h4>
<p>We are responsible for maintaining and protecting the Personal Information under our control. We have designated an individual or individuals who is/are responsible for compliance with our privacy policy.</p>
<h4>2. Identifying Purposes</h4>
<p>We collect, use and disclose Personal Information to provide you with the product or service you have requested and to offer you additional products and services we believe you might be interested in. The purposes for which we collect Personal Information will be identified before or at the time we collect the information. In certain circumstances, the purposes for which information is collected may be clear, and consent may be implied, such as where your name, address and payment information is provided as part of the order process.</p>
<h4>3. Consent</h4>
<p>Knowledge and consent are required for the collection, use or disclosure of Personal Information except where required or permitted by law. Providing us with your Personal Information is always your choice. However, your decision not to provide certain information may limit our ability to provide you with our products or services. We will not require you to consent to the collection, use, or disclosure of information as a condition to the supply of a product or service, except as required to be able to supply the product or service.</p>
<h4>4. Limiting Collection</h4>
<p>The Personal Information collected will be limited to those details necessary for the purposes identified by us. With your consent, we may collect Personal Information from you in person, over the telephone or by corresponding with you via mail, facsimile, or the Internet.</p>
<h4>5. Limiting Use, Disclosure and Retention</h4>
<p>Personal Information may only be used or disclosed for the purpose for which it was collected unless you have otherwise consented, or when it is required or permitted by law. Personal Information will only be retained for the period of time required to fulfill the purpose for which we collected it or as may be required by law.</p>
<h4>6. Accuracy</h4>
<p>Personal Information will be maintained in as accurate, complete and up-to-date form as is necessary to fulfill the purposes for which it is to be used.</p>
<h4>Safeguarding Customer Information</h4>
<p>Personal Information will be protected by security safeguards that are appropriate to the sensitivity level of the information. We take all reasonable precautions to protect your Personal Information from any loss or unauthorized use, access or disclosure.</p>
<h4>8. Openness</h4>
<p>We will make information available to you about our policies and practices with respect to the management of your Personal Information.</p>
<h4>9. Customer Access</h4>
<p>Upon request, you will be informed of the existence, use and disclosure of your Personal Information, and will be given access to it. You may verify the accuracy and completeness of your Personal Information, and may request that it be amended, if appropriate. However, in certain circumstances permitted by law, we will not disclose certain information to you. For example, we may not disclose information relating to you if other individuals are referenced or if there are legal, security or commercial proprietary restrictions.</p>
<h4>10. Handling Customer Complaints and Suggestions</h4>
<p>You may direct any questions or enquiries with respect to our privacy policy or our practices by</p>
<p>contacting: <a href="https://twitter.com/lingdocs">@lingdocs</a> or admin @ lingdocs dot com</p>
<h4>Additional Information</h4>
<h5>Cookies</h5>
<p>A cookie is a small computer file or piece of information that may be stored in your computer's hard drive when you visit our websites. We may use cookies to improve our websites functionality and in some cases, to provide visitors with a customized online experience.</p>
<p>Cookies are widely used and most web browsers are configured initially to accept cookies automatically. You may change your Internet browser settings to prevent your computer from accepting cookies or to notify you when you receive a cookie so that you may decline its acceptance. Please note, however, if you disable cookies, you may not experience optimal performance of our website.</p>
<h5>Analytics</h5>
<p>Usage analytics are sent to Google Analytics. The user's IP address is anonymized, and "Do not track" requests are respected.</p>
<h5>Other Websites</h5>
<p>Our website may contain links to other third party sites that are not governed by this privacy policy. Although we endeavour to only link to sites with high privacy standards, our privacy policy will no longer apply once you leave our website. Additionally, we are not responsible for the privacy practices employed by third party websites. Therefore, we suggest that you examine the privacy statements of those sites to learn how your information may be collected, used, shared and disclosed.</p>
<p>
<a href="/">Back / Login</a>
</p>
</div>
</body>
</html>

326
account/views/user.ejs Normal file
View File

@ -0,0 +1,326 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="LingDocs Signin">
<title>Account · LingDocs</title>
<link href="/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.15.4/css/all.css" integrity="sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm" crossorigin="anonymous">
<script>
</script>
</head>
<body>
<div class="container" style="max-width: 400px;">
<h2 class="mt-4 mb-4 text-center">LingDocs Account</h2>
<% if (user.admin) { %>
<a href="/admin"><h5 class="mb-2">Admin Console</h5></a>
<% } %>
<h4>Profile <i class="fas fa-user ml-2"></i></h4>
<form method="POST" class="mb-4">
<div>
<label for="email" class="form-label">Email:</label>
<% if (user.email) { %>
<input required name="email" type="email" class="form-control" id="email" value="<%= user.email %>" />
<% } else { %>
<input name="email" type="email" class="form-control" id="email" placeholder="add an e-mail here" />
<% } %>
</div>
<div>
<% if (error === "email taken") { %>
<div class="alert alert-danger mt-3" role="alert">
Sorry, that e-mail is already taken 🙄
</div>
<% } else if (typeof user.emailVerified === "string") { %>
<div class="alert alert-info mt-3" role="alert">
<div class="d-flex flex-row justify-content-between align-items-center">
<div>Check your e-mail to verify</div>
<div id="resend-button-container">
<button type="button" class="btn btn-light btn-sm" id="resend-button">Resend</button>
</div>
</div>
</div>
<% } %>
</div>
<div class="mb-4 mt-3">
<label for="name" class="form-label">Name:</label>
<input required name="name" type="text" class="form-control" id="name" value="<%= user.name %>" />
</div>
<div>
<button type="submit" class="btn btn-primary">Update Profile</button>
</div>
</form>
<h5>Account Level: <%= user.level.charAt(0).toUpperCase() + user.level.slice(1) %></h5>
<% if (user.level === "basic") { %>
<p>Upgrade to Student account for Wordlist features</p>
<div class="d-flex flex-row" style="gap: 1rem;">
<form action="/payment/create-checkout-session" method="POST">
<input type="hidden" name="priceId" value="price_1Lt8NqJnpCQCjf9pN7CQUjjO" />
<button class="btn btn-sm btn-outline-secondary" type="submit">$1/month</button>
</form>
<form action="/payment/create-checkout-session" method="POST">
<input type="hidden" name="priceId" value="price_1Lt8NqJnpCQCjf9p4FAEIOMw" />
<button class="btn btn-sm btn-outline-secondary" type="submit">$10/year</button>
</form>
</div>
<% } %>
<% if (user.level === "student" && user.subscription) { %>
<p>Current subscription: <% if (user.subscription.metadata.cycle === "monthly") { %>$1/month<% } else { %>$10/year<% } %></p>
<p><a href="#" onclick="handleDowngrade()">Downgrade</a> to cancel your subscription</p>
<% } %>
<% if (user.email) { %>
<h4 class="mt-3 mb-3">Password <i class="fas fa-key ml-2"></i></h4>
<% if (!user.password) { %>
<p class="small">Add a password to be able to log in with just your e-mail address.</p>
<% } %>
<% } %>
<div id="password-change-form" style="display: none;">
<% if (user.password) { %>
<div id="old-password-form">
<% } else { %>
<div id="old-password-form" style="display: none;">
<% } %>
<div class="mb-3 mt-3">
<label for="oldPassword" class="form-label">Old Password:</label>
<input type="password" class="form-control" id="oldPassword">
</div>
<div class="small text-left" id="forgot-password">
<a href="" tabindex="-1">Forgot Old Password?</a>
</div>
</div>
<div class="mb-3 mt-3">
<label for="password" class="form-label">New Password:</label>
<input type="password" class="form-control" id="password" />
</div>
<div class="mb-4 mt-3">
<label for="confirmPassword" class="form-label">Confirm New Password:</label>
<input type="password" class="form-control" id="confirmPassword">
</div>
</div>
<div id="password-change-result" style="display: none;" class="alert alert-info mt-3 mb-4" role="alert">
</div>
<% if (user.email) { %>
<div class="d-flex flex-row justify-content-between mt-2 mb-1">
<button type="button" id="password-change-button" class="btn btn-secondary">
<% if (user.password) { %>
Change
<% } else { %>
Add
<% } %>
Password
</button>
<button type="button" style="display: none;" id="cancel-password-change-button" class="btn btn-light">Cancel</button>
</div>
<% } %>
<h4 class="mt-3 mb-1">Linked Accounts <i class="fas fa-link ml-2"></i></h4>
<div class="mb-4">
<% if (user.google) { %>
<!-- TODO: MAKE THIS EMAIL THING SAFER! -->
<div class="my-2 w-100 btn btn-secondary"><i class="fab fa-google mr-2"></i> Linked to Google · <%= user.google.emails[0].value %></div>
<form action="/google/remove" method="POST">
<% if (removeProviderOption) { %>
<button type="submit" class="btn btn-sm btn-outline">Unlink from Google</button>
<% } %>
</form>
<% } %>
<% if (user.twitter) { %>
<div class="my-2 w-100 btn btn-secondary"><i class="fab fa-twitter mr-2"></i> Linked to Twitter · @<%= user.twitter.username %></div>
<form action="/twitter/remove" method="POST">
<% if (removeProviderOption) { %>
<button type="submit" class="btn btn-sm btn-outline">Unlink from Twitter</button>
<% } %>
</form>
<% } %>
<% if (user.github) { %>
<div class="my-2 w-100 btn btn-secondary"><i class="fab fa-github mr-2"></i> Linked to GitHub · <%= user.github.username %></div>
<form action="/github/remove" method="POST">
<% if (removeProviderOption) { %>
<button type="submit" class="btn btn-sm btn-outline">Unlink from GitHub</button>
<% } %>
</form>
<% } %>
<% if (!user.google) { %>
<a href="/google" class="my-2 w-100 btn btn-outline-secondary" role="button"><i class="fab fa-google mr-2"></i> Link to Google</a>
<% } %>
<% if (!user.twitter) { %>
<a href="/twitter" class="my-2 w-100 btn btn-outline-secondary" role="button"><i class="fab fa-twitter mr-2"></i> Link to Twitter</a>
<% } %>
<% if (!user.github) { %>
<a href="/github" class="my-2 w-100 btn btn-outline-secondary" role="button"><i class="fab fa-github mr-2"></i> Link to GitHub</a>
<% } %>
</div>
<hr />
<p class="text-muted small">Last Login: <%= new Date(user.lastLogin).toUTCString() %></p>
<form action="/sign-out" method="POST">
<button type="submit" class="btn btn-outline-secondary"><i class="fas fa-sign-out-alt mr-2"></i> Sign Out of LingDocs</button>
</form>
<hr />
<div class="mb-4">
<button onclick="handleDelete()" type="button" class="btn btn-outline-danger my-4"><i class="fas fa-trash-alt mr-2"></i> Delete Account</button>
</div>
<p class="text-muted text-center"><a href="https://www.lingdocs.com/">LingDocs.com</a></p>
</div>
</body>
<script>
if (window.opener) {
const w = window.opener
try {
w.postMessage("signed in", "https://dictionary.lingdocs.com");
} catch (e) {
console.error(e);
}
try {
w.postMessage("signed in", "https://dev.dictionary.lingdocs.com");
} catch (e) {
console.error(e);
}
try {
w.postMessage("signed in", "https://grammar.lingdocs.com");
} catch (e) {
console.error(e);
}
try {
w.postMessage("upgraded", "https://dictionary.lingodocs.com");
} catch (e) {
console.error(e);
}
}
// function handleRequestUpgrade() {
// const btn = document.getElementById("upgrade-request-button");
// btn.innerHTML = "Sending...";
// fetch("/api/user/upgradeToStudentRequest", {
// method: "POST",
// }).then((res) => res.json()).then((res) => {
// console.log(res);
// if (res.ok) {
// btn.innerHTML = "Upgrade request sent";
// } else {
// btn.innerHTML = "Error requesting upgrade";
// }
// }).catch((e) => {
// console.error(e);
// btn.innerHTML = "Error requesting upgrade";
// });
// }
function clearPasswordForm() {
document.getElementById("oldPassword").value = "";
document.getElementById("password").value = "";
document.getElementById("confirmPassword").value = "";
}
function handleDelete() {
const answer = confirm("Are you sure you want to delete your account?");
if (answer) {
fetch("/api/user", { method: "DELETE" }).then((res) => res.json()).then((res) => {
if (res.ok) {
window.location = "/";
}
}).catch((err) => {
alert("Error deleting account - check your connection");
console.error(err);
});
}
}
function handleDowngrade() {
const answer = confirm("Are you sure you want to downgrade your account? Your wordlist will be deleted forever. (Export it to CSV from the dictionary first if you want to keep it.)");
if (answer) {
fetch("/downgradeToBasic", { method: "POST" }).then((res) => res.json()).then((res) => {
if (res.ok) {
window.location = "/";
} else {
alert("Error downgrading account");
}
}).catch((err) => {
alert("Error downgrading account - check your connection");
console.error(err);
});
}
}
window.addEventListener('keydown', (e) => {
// prevent an enter from submitting the form
if (e.keyCode === 13) {
e.preventDefault();
}
});
const passwordChangeForm = document.getElementById("password-change-form");
const passwordChangeButton = document.getElementById("password-change-button");
const passwordChangeResult = document.getElementById("password-change-result");
const forgotPassword = document.getElementById("forgot-password");
if (forgotPassword) {
forgotPassword.addEventListener("click", (e) => {
event.preventDefault();
const email = document.getElementById("email").value;
window.location = encodeURI("/password-reset?email=" + email);
});
}
const cancelPasswordChangeButton = document.getElementById("cancel-password-change-button");
if (passwordChangeButton) {
passwordChangeButton.addEventListener("click", (e) => {
e.preventDefault();
const formClosed = window.getComputedStyle(passwordChangeForm).getPropertyValue("display") === "none";
if (formClosed) {
clearPasswordForm();
passwordChangeResult.innerHTML = "";
passwordChangeResult.style = "display: none;";
passwordChangeForm.style = "";
cancelPasswordChangeButton.style = "";
} else {
const oldPassword = document.getElementById("oldPassword").value;
const password = document.getElementById("password").value;
const passwordConfirmed = document.getElementById("confirmPassword").value;
fetch("/api/password", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ oldPassword, password, passwordConfirmed }),
}).then((res) => res.json()).then((res) => {
if (res.ok) {
passwordChangeResult.innerHTML = res.message;
passwordChangeResult.style = "";
passwordChangeForm.style = "display: none;";
cancelPasswordChangeButton.style = "display: none;";
if (res.message === "Password added") {
document.getElementById("old-password-form").style = "";
passwordChangeButton.innerHTML = "Change Password";
}
} else {
passwordChangeResult.innerHTML = res.error;
passwordChangeResult.style = "";
}
}).catch(console.error);
}
});
}
if (cancelPasswordChangeButton) {
cancelPasswordChangeButton.addEventListener("click", (e) => {
e.preventDefault();
passwordChangeForm.style="display: none;";
cancelPasswordChangeButton.style="display: none;";
passwordChangeResult.innerHTML = "";
passwordChangeResult.style = "display: none;";
clearPasswordForm();
});
}
const resendButton = document.getElementById("resend-button");
if (resendButton) {
resendButton.addEventListener("click", handleResendVerification, true);
}
function handleResendVerification(e) {
e.preventDefault();
const bc = document.getElementById("resend-button-container");
bc.innerHTML = "Sending …";
fetch("/api/email-verification", { method: "PUT" }).then((res) => res.json())
.then((res) => {
if (res.ok) {
bc.innerHTML = "Sent ✔";
} else {
bc.innerHTML = "Send Failed 😔";
}
}).catch((error) => {
console.error(error);
bs.innerHTML = "Send Failed 😔";
});
}
</script>
</html>

1766
architecture-source.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 125 KiB

3151
architecture.svg Normal file

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 340 KiB

19
firebase.json Normal file
View File

@ -0,0 +1,19 @@
{
"functions": {
"predeploy": "cp .npmrc functions && cat .npmrc | envsubst > functions/.npmrc && cd functions && npm --prefix \"$RESOURCE_DIR\" run build",
"postdeploy": "rm functions/.npmrc"
},
"hosting": {
"public": "public",
"rewrites": [
{
"source": "/publishDictionary",
"function": "/publishDictionary"
},
{
"source": "/submissions",
"function": "/submissions"
}
]
}
}

17
functions/.gitignore vendored Normal file
View File

@ -0,0 +1,17 @@
# Debug
ui-debug.log
# Compiled JavaScript files
lib
# TypeScript v1 declaration files
typings/
# Node.js dependency directory
node_modules/
# File with private NPM token(s) inserted for deploying function
.npmrc
# Firebase functions config/env for running functions locally
.runtimeconfig.json

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