Initial commit

This commit is contained in:
i701 2025-01-20 14:33:03 +05:00
commit 4d0eb86478
84 changed files with 4436 additions and 0 deletions

165
.gitignore vendored Normal file
View File

@ -0,0 +1,165 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
#.idea/
#staticfiles
staticfiles/
postgres_data/

7
.pylintrc Normal file
View File

@ -0,0 +1,7 @@
disable=
too-many-instance-attributes,
no-else-return,
too-many-arguments,
no-name-in-module,
no-member,
print-statement,

28
Dockerfile Normal file
View File

@ -0,0 +1,28 @@
# pull official base image
FROM python:3.11.4-slim-buster
# set work directory
WORKDIR /app
# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# install system dependencies
RUN apt-get update && apt-get install -y netcat
# install dependencies
RUN pip install --upgrade pip
COPY ./requirements.txt .
RUN pip install -r requirements.txt
# copy entrypoint.sh
COPY ./entrypoint.sh .
RUN sed -i 's/\r$//g' /app/entrypoint.sh
RUN chmod +x /app/entrypoint.sh
# copy project
COPY . .
# run entrypoint.sh
ENTRYPOINT ["/app/entrypoint.sh"]

71
Dockerfile.prod Normal file
View File

@ -0,0 +1,71 @@
###########
# BUILDER #
###########
# pull official base image
FROM python:3.11.4-slim-buster AS builder
# set work directory
WORKDIR /app
# set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# install system dependencies
RUN apt-get update && \
apt-get install -y --no-install-recommends gcc
# lint
RUN pip install --upgrade pip
COPY . /app/
# install python dependencies
COPY ./requirements.txt .
RUN pip wheel --no-cache-dir --no-deps --wheel-dir /app/wheels -r requirements.txt
#########
# FINAL #
#########
# pull official base image
FROM python:3.11.4-slim-buster
# create directory for the app user
RUN mkdir -p /home/app
# create the app user
RUN addgroup --system app && adduser --system --group app
# create the appropriate directories
ENV HOME=/home/app
ENV APP_HOME=/home/app/api
RUN mkdir $APP_HOME
RUN mkdir $APP_HOME/staticfiles
RUN chmod -R 777 $APP_HOME/staticfiles
WORKDIR $APP_HOME
# install dependencies
RUN apt-get update && apt-get install -y --no-install-recommends netcat
COPY --from=builder /app/wheels /wheels
COPY --from=builder /app/requirements.txt .
RUN pip install --upgrade pip
RUN pip install --no-cache /wheels/*
# copy entrypoint.prod.sh
COPY ./entrypoint.prod.sh .
RUN sed -i 's/\r$//g' $APP_HOME/entrypoint.prod.sh
RUN chmod +x $APP_HOME/entrypoint.prod.sh
# copy project
COPY . $APP_HOME
# chown all the files to the app user
RUN chown -R app:app $APP_HOME
# change to the app user
USER app
# run entrypoint.prod.sh
ENTRYPOINT ["/home/app/api/entrypoint.prod.sh"]

674
LICENSE Normal file
View File

@ -0,0 +1,674 @@
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <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:
<program> Copyright (C) <year> <name of author>
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>.

2
README.md Normal file
View File

@ -0,0 +1,2 @@
# sarlink-portal-api
API for SARLink portal in Django Rest Framework.

0
api/__init__.py Normal file
View File

71
api/admin.py Normal file
View File

@ -0,0 +1,71 @@
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from api.models import User, Atoll, Island
from django.contrib.auth.models import Permission
# Define a new User admin
class UserAdmin(BaseUserAdmin):
list_display = (
"username",
"email",
"first_name",
"last_name",
"is_active",
"is_staff",
"mobile",
"address",
"acc_no",
"id_card",
"dob",
"atoll",
"island",
"terms_accepted",
"policy_accepted",
) # Add custom fields here
fieldsets = (
(None, {"fields": ("username", "password")}),
(
"Personal info",
{
"fields": (
"first_name",
"last_name",
"email",
"mobile",
"address",
"acc_no",
"id_card",
"dob",
"atoll",
"island",
"terms_accepted",
"policy_accepted",
)
},
), # Add custom fields here
(
"Permissions",
{
"fields": (
"is_active",
"is_staff",
"is_superuser",
"groups",
"user_permissions",
)
},
),
("Important dates", {"fields": ("last_login", "date_joined")}),
)
# Re-register UserAdmin
admin.site.register(User, UserAdmin)
admin.site.register(Permission)
admin.site.register(Atoll)
admin.site.register(Island)
# TokenAdmin.raw_id_fields = ["user"]

9
api/apps.py Normal file
View File

@ -0,0 +1,9 @@
from django.apps import AppConfig
class ApiConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "api"
def ready(self):
import api.signals # Add this line to import the signals.py

5
api/authentication.py Normal file
View File

@ -0,0 +1,5 @@
from rest_framework.authentication import TokenAuthentication as BaseTokenAuth
class TokenAuthentication(BaseTokenAuth):
keyword = "Token"

17
api/backends.py Normal file
View File

@ -0,0 +1,17 @@
from django.contrib.auth import get_user_model
from django.contrib.auth.backends import ModelBackend
class EmailBackend(ModelBackend):
def authenticate(self, request, username=None, password=None, **kwargs):
UserModel = get_user_model()
if not password:
return None
try:
user = UserModel.objects.get(email=username)
except UserModel.DoesNotExist:
return None
else:
if user.check_password(password):
return user
return None

18
api/exceptions.py Normal file
View File

@ -0,0 +1,18 @@
from rest_framework.views import exception_handler
from rest_framework.exceptions import Throttled
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
if isinstance(exc, Throttled): # check that a Throttled exception is raised
custom_response_data = { # prepare custom response data
"message": "Too many attemps. Please Try again in %d seconds." % exc.wait,
}
response.data = (
custom_response_data # set the custom response data on response object
)
return response

16
api/filters.py Normal file
View File

@ -0,0 +1,16 @@
import django_filters
from api.models import User
class UserFilter(django_filters.FilterSet):
last_name = django_filters.CharFilter(lookup_expr="icontains")
first_name = django_filters.CharFilter(lookup_expr="icontains")
email = django_filters.CharFilter(lookup_expr="icontains")
class Meta:
model = User
fields = [
"username",
"last_name",
"first_name",
]

20
api/managers.py Normal file
View File

@ -0,0 +1,20 @@
from django.contrib.auth.models import BaseUserManager
class CustomUserManager(BaseUserManager):
def create_user(self, username, password=None, **extra_fields):
"""Create and return a user with an email and password."""
if not username:
raise ValueError("The Username field must be set")
user = self.model(username=username, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, username, password=None, **extra_fields):
"""Create and return a superuser with an email and password."""
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
return self.create_user(username, password, **extra_fields)

View File

@ -0,0 +1,190 @@
# Generated by Django 5.1.2 on 2025-01-20 03:29
import api.managers
import django.contrib.auth.validators
import django.db.models.deletion
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
("auth", "0012_alter_user_first_name_max_length"),
]
operations = [
migrations.CreateModel(
name="Atoll",
fields=[
(
"id",
models.CharField(max_length=255, primary_key=True, serialize=False),
),
("name", models.CharField(max_length=255)),
("created_at", models.DateTimeField(default=django.utils.timezone.now)),
("updated_at", models.DateTimeField(auto_now=True)),
],
),
migrations.CreateModel(
name="Island",
fields=[
(
"id",
models.CharField(max_length=255, primary_key=True, serialize=False),
),
("name", models.CharField(max_length=255)),
("created_at", models.DateTimeField(default=django.utils.timezone.now)),
("updated_at", models.DateTimeField(auto_now=True)),
(
"atoll",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="islands",
to="api.atoll",
),
),
],
),
migrations.CreateModel(
name="User",
fields=[
(
"id",
models.BigAutoField(
auto_created=True,
primary_key=True,
serialize=False,
verbose_name="ID",
),
),
("password", models.CharField(max_length=128, verbose_name="password")),
(
"last_login",
models.DateTimeField(
blank=True, null=True, verbose_name="last login"
),
),
(
"is_superuser",
models.BooleanField(
default=False,
help_text="Designates that this user has all permissions without explicitly assigning them.",
verbose_name="superuser status",
),
),
(
"username",
models.CharField(
error_messages={
"unique": "A user with that username already exists."
},
help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.",
max_length=150,
unique=True,
validators=[
django.contrib.auth.validators.UnicodeUsernameValidator()
],
verbose_name="username",
),
),
(
"first_name",
models.CharField(
blank=True, max_length=150, verbose_name="first name"
),
),
(
"last_name",
models.CharField(
blank=True, max_length=150, verbose_name="last name"
),
),
(
"is_staff",
models.BooleanField(
default=False,
help_text="Designates whether the user can log into this admin site.",
verbose_name="staff status",
),
),
(
"is_active",
models.BooleanField(
default=True,
help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.",
verbose_name="active",
),
),
(
"date_joined",
models.DateTimeField(
default=django.utils.timezone.now, verbose_name="date joined"
),
),
("email", models.EmailField(max_length=254, unique=True)),
("address", models.CharField(blank=True, max_length=255)),
("mobile", models.CharField(blank=True, max_length=255)),
("designation", models.CharField(blank=True, max_length=255)),
("acc_no", models.CharField(blank=True, max_length=255)),
("id_card", models.CharField(blank=True, max_length=255)),
("verified", models.BooleanField(default=False)),
("dob", models.DateField(blank=True, null=True)),
("terms_accepted", models.BooleanField(default=False)),
("policy_accepted", models.BooleanField(default=False)),
("wallet_balance", models.FloatField(default=0.0)),
("ninja_user_id", models.CharField(blank=True, max_length=255)),
(
"groups",
models.ManyToManyField(
blank=True,
help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.",
related_name="user_set",
related_query_name="user",
to="auth.group",
verbose_name="groups",
),
),
(
"user_permissions",
models.ManyToManyField(
blank=True,
help_text="Specific permissions for this user.",
related_name="user_set",
related_query_name="user",
to="auth.permission",
verbose_name="user permissions",
),
),
(
"atoll",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="users",
to="api.atoll",
),
),
(
"island",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="users",
to="api.island",
),
),
],
options={
"verbose_name": "user",
"verbose_name_plural": "users",
"abstract": False,
},
managers=[
("objects", api.managers.CustomUserManager()),
],
),
]

View File

@ -0,0 +1,17 @@
# Generated by Django 5.1.2 on 2025-01-20 03:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("api", "0001_initial"),
]
operations = [
migrations.AlterField(
model_name="user",
name="email",
field=models.EmailField(blank=True, max_length=254, null=True, unique=True),
),
]

View File

@ -0,0 +1,16 @@
# Generated by Django 5.1.2 on 2025-01-20 04:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("api", "0002_alter_user_email"),
]
operations = [
migrations.AlterModelManagers(
name="user",
managers=[],
),
]

View File

@ -0,0 +1,26 @@
# Generated by Django 5.1.2 on 2025-01-20 04:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("api", "0003_alter_user_managers"),
]
operations = [
migrations.AlterField(
model_name="atoll",
name="id",
field=models.BigAutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
migrations.AlterField(
model_name="island",
name="id",
field=models.BigAutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
]

View File

14
api/mixins.py Normal file
View File

@ -0,0 +1,14 @@
from rest_framework import permissions
from .permissions import IsStaffEditorPermission
# from knox.auth import TokenAuthentication
class StaffEditorPermissionMixin:
permission_classes = [
# permissions.IsAdminUser,
permissions.IsAuthenticated,
IsStaffEditorPermission,
# TokenAuthentication,
]

46
api/models.py Normal file
View File

@ -0,0 +1,46 @@
"""
This is the models module for api.
"""
from django.contrib.auth.models import AbstractUser
from django.db import models
from .managers import CustomUserManager
from django.utils import timezone
class User(AbstractUser):
email = models.EmailField(unique=True, blank=True, null=True)
address = models.CharField(max_length=255, blank=True)
mobile = models.CharField(max_length=255, blank=True)
designation = models.CharField(max_length=255, blank=True)
acc_no = models.CharField(max_length=255, blank=True)
id_card = models.CharField(max_length=255, blank=True)
verified = models.BooleanField(default=False)
dob = models.DateField(blank=True, null=True)
terms_accepted = models.BooleanField(default=False)
policy_accepted = models.BooleanField(default=False)
wallet_balance = models.FloatField(default=0.0)
ninja_user_id = models.CharField(max_length=255, blank=True)
atoll = models.ForeignKey('Atoll', on_delete=models.SET_NULL, null=True, blank=True, related_name='users')
island = models.ForeignKey('Island', on_delete=models.SET_NULL, null=True, blank=True, related_name='users')
def get_all_fields(self, instance):
return [field.name for field in instance.get_fields()]
objects = CustomUserManager()
class Atoll(models.Model):
name = models.CharField(max_length=255)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
class Island(models.Model):
atoll = models.ForeignKey(Atoll, on_delete=models.CASCADE, related_name='islands')
name = models.CharField(max_length=255)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name

21
api/pagination.py Normal file
View File

@ -0,0 +1,21 @@
from rest_framework import pagination
from rest_framework.response import Response
class CustomPagination(pagination.LimitOffsetPagination):
def get_paginated_response(self, data):
return Response(
{
"meta": {
"total": self.count,
"per_page": self.limit,
"current_page": int(self.offset / self.limit) + 1,
"last_page": int((self.count - 1) / self.limit) + 1,
},
"links": {
"next_page": self.get_next_link(),
"previous_page": self.get_previous_link(),
},
"data": data,
}
)

32
api/permissions.py Normal file
View File

@ -0,0 +1,32 @@
from rest_framework import permissions
class IsStaffEditorPermission(permissions.DjangoModelPermissions):
perms_map = {
"GET": ["%(app_label)s.view_%(model_name)s"],
"OPTIONS": [],
"HEAD": [],
"POST": ["%(app_label)s.add_%(model_name)s"],
"PUT": ["%(app_label)s.change_%(model_name)s"],
"PATCH": ["%(app_label)s.change_%(model_name)s"],
"DELETE": ["%(app_label)s.delete_%(model_name)s"],
}
message = {
"message": "You do not have permission to perform this action.",
}
def has_permission(self, request, view):
# Ensure the user is authenticated
if not request.user.is_authenticated:
return False
# Get the model name from the view
model_name = view.queryset.model._meta.model_name
app_label = view.queryset.model._meta.app_label
# Check permissions based on the request method
perms = self.perms_map.get(request.method, [])
perms = [perm % {'app_label': app_label, 'model_name': model_name} for perm in perms]
return request.user.has_perms(perms)

94
api/serializers.py Normal file
View File

@ -0,0 +1,94 @@
from knox.models import AuthToken
from django.contrib.auth import authenticate
from api.models import User
from rest_framework import serializers
class CustomUserSerializer(serializers.ModelSerializer):
"""serializer for the user object"""
user_permissions = serializers.SerializerMethodField()
def get_user_permissions(self, instance):
permission_ids = instance.user_permissions.all()
return [
{"id": permission.id, "name": permission.name}
for permission in permission_ids
]
class Meta: # type: ignore
model = User
fields = (
"id",
"username",
"email",
"user_permissions",
"first_name",
"last_name",
"last_login",
"date_joined",
"is_superuser",
)
class CustomReadOnlyUserSerializer(serializers.ModelSerializer):
"""serializer for the user object"""
class Meta: # type: ignore
model = User
# fields = "__all__"
fields = (
"id",
"email",
"first_name",
"last_name",
"username",
"mobile",
"address",
)
class UserSerializer(serializers.ModelSerializer):
"""serializer for the user object"""
class Meta: # type: ignore
model = User
fields = ("username", "password")
extra_kwargs = {"password": {"write_only": True, "min_length": 5}}
def create(self, validated_data):
return User.objects.create_user(**validated_data)
class AuthSerializer(serializers.Serializer):
"""serializer for the user authentication object"""
username = serializers.CharField()
password = serializers.CharField(
style={"input_type": "password"}, trim_whitespace=False
)
def validate(self, attrs):
username = attrs.get("username")
password = attrs.get("password")
user = authenticate(
request=self.context.get("request"), username=username, password=password
)
if not user:
msg = "Unable to authenticate with provided credentials"
raise serializers.ValidationError(msg, code="authentication")
attrs["user"] = user
return user
class KnoxTokenSerializer(serializers.ModelSerializer):
"""serializer for the auth token object"""
class Meta: # type: ignore
model = AuthToken
fields = "__all__"

61
api/signals.py Normal file
View File

@ -0,0 +1,61 @@
from django.core.mail import EmailMultiAlternatives
from django.dispatch import receiver
from django.template.loader import render_to_string
from decouple import config
from django_rest_passwordreset.signals import reset_password_token_created
from django.db.models.signals import post_save
from api.models import User
from django.contrib.auth.models import Permission
@receiver(post_save, sender=User)
def assign_device_permissions(sender, instance, created, **kwargs):
if created:
# Assign all permissions for devices and read permission for atoll and island
device_permissions = Permission.objects.filter(content_type__model='device')
atoll_read_permission = Permission.objects.get(codename='view_atoll')
island_read_permission = Permission.objects.get(codename='view_island')
for permission in device_permissions:
instance.user_permissions.add(permission)
instance.user_permissions.add(atoll_read_permission, island_read_permission)
@receiver(reset_password_token_created)
def password_reset_token_created(
sender, instance, reset_password_token, *args, **kwargs
):
"""
Handles password reset tokens
When a token is created, an e-mail needs to be sent to the user
:param sender: View Class that sent the signal
:param instance: View Instance that sent the signal
:param reset_password_token: Token Model Object
:param args:
:param kwargs:
:return:
"""
context = {
"current_user": reset_password_token.user,
"username": reset_password_token.user.username,
"email": reset_password_token.user.email,
"reset_password_url": f"{config('FRONTEND_URL')}/auth/reset-password-confirm/?token={reset_password_token.key}",
}
# render email text
email_html_message = render_to_string("email/password_reset_email.html", context)
email_plaintext_message = (
f"Here is your password reset link: {context['reset_password_url']}"
)
msg = EmailMultiAlternatives(
# title:
"Password Reset for {title}".format(title="Sarlink Portal"),
# message:
email_plaintext_message, # This is the plaintext version
# from:
"noreply@sarlink.net",
# to:
[reset_password_token.user.email],
)
msg.attach_alternative(email_html_message, "text/html")
msg.send()

View File

@ -0,0 +1,102 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="description" content="Instructions to reset your password." />
<meta name="keywords" content="password, reset, email, instructions" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Password Reset Email</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
margin: 0;
padding: 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
background-color: #ffffff;
border-radius: 8px;
padding: 30px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.header {
margin-bottom: 30px;
}
.logo {
color: #2c3e50;
font-size: 24px;
font-weight: bold;
}
.message {
color: #6c757d;
font-size: 16px;
line-height: 1.5;
margin-top: 20px;
}
.footer {
margin-top: 30px;
color: #6c757d;
font-size: 14px;
}
.button {
display: inline-block;
padding: 10px 20px;
background-color: #007bff;
color: #ffffff !important;
text-decoration: none;
border-radius: 5px;
margin: 20px 0;
}
.button:hover {
background-color: #0056b3;
}
a {
color: #007bff;
text-decoration: underline;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<div class="logo">Password Reset Instructions</div>
</div>
<p class="message">
Hello {{ username }},
</p>
<p class="message">
We received a request to reset your password. Click the button below to create a new password:
</p>
<a href="{{ reset_password_url }}" class="button">Reset Password</a>
<p class="message">
If the button doesn't work, you can copy and paste this link into your browser:
<br>
<a href="{{ reset_password_url }}">{{ reset_password_url }}</a>
</p>
<p class="message">
If you did not request this password reset, you can safely ignore
this email.
</p>
<p class="footer">Best regards,<br>SARLink</p>
</div>
</body>
</html>

1
api/tests.py Normal file
View File

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

5
api/throttle.py Normal file
View File

@ -0,0 +1,5 @@
from rest_framework import throttling
class BurstRateThrottle(throttling.UserRateThrottle):
scope = "burst"

30
api/urls.py Normal file
View File

@ -0,0 +1,30 @@
from django.urls import path
from knox import views as knox_views
from .views import (
LoginView,
CreateUserView,
ManageUserView,
KnoxTokenListApiView,
ListUserView,
UserDetailAPIView,
healthcheck,
test_email,
)
urlpatterns = [
path("create/", CreateUserView.as_view(), name="create"),
path("profile/", ManageUserView.as_view(), name="profile"),
path("login/", LoginView.as_view(), name="knox_login"),
path("logout/", knox_views.LogoutView.as_view(), name="knox_logout"),
path("logoutall/", knox_views.LogoutAllView.as_view(), name="knox_logoutall"),
path("tokens/", KnoxTokenListApiView.as_view(), name="knox_tokens"),
# path("auth/", CustomAuthToken.as_view()),
path("users/", ListUserView.as_view(), name="users"),
path("users/<int:pk>/", UserDetailAPIView.as_view(), name="user-detail"),
path("healthcheck/", healthcheck, name="healthcheck"),
path("test/", test_email, name="testemail"),
]

29
api/utils.py Normal file
View File

@ -0,0 +1,29 @@
def reverse_dhivehi_string(input_str):
"""
Reverses a Dhivehi string while preserving character composition.
Args:
input_str (str): The Dhivehi string to be reversed
Returns:
str: The reversed Dhivehi string
"""
# Reverse the string and then normalize the character order
reversed_str = input_str[::-1]
# List to store the corrected characters
corrected_chars = []
# Iterate through the reversed string
i = 0
while i < len(reversed_str):
# Check if current character is a combining character
if i + 1 < len(reversed_str) and "\u0300" <= reversed_str[i + 1] <= "\u036F":
# If next character is a combining mark, add it before the base character
corrected_chars.append(reversed_str[i + 1] + reversed_str[i])
i += 2
else:
corrected_chars.append(reversed_str[i])
i += 1
return "".join(corrected_chars)

221
api/views.py Normal file
View File

@ -0,0 +1,221 @@
# django imports
from django.contrib.auth import login
# rest_framework imports
from rest_framework import generics, permissions
from rest_framework.authtoken.serializers import AuthTokenSerializer
from api.filters import UserFilter
from api.mixins import StaffEditorPermissionMixin
from api.models import User, Atoll, Island
from rest_framework.response import Response
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.decorators import api_view, permission_classes
# knox imports
from knox.views import LoginView as KnoxLoginView
from knox.models import AuthToken
from django_filters.rest_framework import DjangoFilterBackend
import re
from typing import cast, Dict, Any
from django.core.mail import send_mail
# local apps import
from .serializers import (
KnoxTokenSerializer,
UserSerializer,
AuthSerializer,
CustomUserSerializer,
CustomReadOnlyUserSerializer,
)
class CreateUserView(generics.CreateAPIView):
# Create user API view
serializer_class = UserSerializer
permission_classes = (permissions.AllowAny,)
queryset = User.objects.all()
def post(self, request, *args, **kwargs):
# Extract required fields from request data
password = request.data.get("password")
username = request.data.get("username") # This can be None
address = request.data.get("address")
mobile = request.data.get("mobile")
acc_no = request.data.get("acc_no")
id_card = request.data.get("id_card")
dob = request.data.get("dob")
atoll_id = request.data.get("atoll") # Get the atoll ID
island_id = request.data.get("island") # Get the island ID
terms_accepted = request.data.get("terms_accepted")
policy_accepted = request.data.get("policy_accepted")
firstname = request.data.get("firstname")
lastname = request.data.get("lastname")
# Validate required fields
existing_username = User.objects.filter(username=username).first()
if existing_username:
return Response({"message": "Username already exists."}, status=400)
if not firstname:
return Response({"message": "firstname is required."}, status=400)
if not lastname:
return Response({"message": "lastname is required."}, status=400)
if not password:
return Response({"message": "Password is required."}, status=400)
if not username:
return Response({"message": "Username is required."}, status=400)
if not address:
return Response({"message": "Address is required."}, status=400)
if not mobile:
return Response({"message": "Mobile number is required."}, status=400)
if not acc_no:
return Response({"message": "Account number is required."}, status=400)
if not id_card:
return Response({"message": "ID card is required."}, status=400)
if not dob:
return Response({"message": "Date of birth is required."}, status=400)
if not atoll_id:
return Response({"message": "Atoll is required."}, status=400)
if not island_id:
return Response({"message": "Island is required."}, status=400)
if terms_accepted is None:
return Response({"message": "Terms acceptance is required."}, status=400)
if policy_accepted is None:
return Response({"message": "Policy acceptance is required."}, status=400)
if not re.match(r"^[A-Z]{1,2}[0-9]{6,7}$", id_card):
return Response({"message": "Please enter a valid ID card number."}, status=400)
if not re.match(r"^[7|9][0-9]{6}$", mobile):
return Response({"message": "Please enter a valid mobile number."}, status=400)
if not re.match(r"^(7\d{12}|9\d{16})$", acc_no):
return Response({"message": "Please enter a valid account number."}, status=400)
# Fetch Atoll and Island instances
try:
atoll = Atoll.objects.get(id=atoll_id)
island = Island.objects.get(id=island_id)
except Atoll.DoesNotExist:
return Response({"message": "Atoll not found."}, status=404)
except Island.DoesNotExist:
return Response({"message": "Island not found."}, status=404)
# Create user without email
user = User.objects.create_user(
first_name=firstname,
last_name=lastname,
username=username,
password=password,
address=address,
mobile=str("+960") + str(mobile),
acc_no=acc_no,
id_card=id_card,
dob=dob,
atoll=atoll, # Assign the Atoll instance
island=island, # Assign the Island instance
terms_accepted=terms_accepted,
policy_accepted=policy_accepted,
)
serializer = self.get_serializer(user)
headers = self.get_success_headers(serializer.data)
return Response(
serializer.data, status=status.HTTP_201_CREATED, headers=headers
)
class LoginView(KnoxLoginView):
# login view extending KnoxLoginView
serializer_class = AuthSerializer
permission_classes = (permissions.AllowAny,)
throttle_scope = "login"
def post(self, request, format=None):
try:
serializer = AuthTokenSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = cast(Dict[str, Any], serializer.validated_data)["user"]
login(request, user)
response = super(LoginView, self).post(request, format=None)
return response
except ValidationError as e:
message = "Unable to log in with provided credentials."
if (
hasattr(e, "detail")
and isinstance(e.detail, list)
and len(e.detail) > 0
):
message = e.detail[0]
return Response({"message": message}, status=status.HTTP_400_BAD_REQUEST)
class ManageUserView(generics.RetrieveUpdateAPIView):
"""Manage the authenticated user"""
serializer_class = CustomUserSerializer
permission_classes = (permissions.IsAuthenticated,)
def get_object(self):
"""Retrieve and return authenticated user"""
return self.request.user
class KnoxTokenListApiView(
StaffEditorPermissionMixin,
generics.ListAPIView,
):
# Create user API view
serializer_class = KnoxTokenSerializer
permission_classes = (permissions.IsAuthenticated,)
queryset = AuthToken.objects.all()
def get(self, request, *args, **kwargs):
user_id = getattr(request.user, "id", None)
if user_id is None:
return Response({"error": "User ID not found"}, status=400)
queryset = AuthToken.objects.filter(user_id=user_id)
data = KnoxTokenSerializer(queryset, many=True).data
return Response({"data": data})
class ListUserView(StaffEditorPermissionMixin, generics.ListAPIView):
# Create user API view
serializer_class = CustomReadOnlyUserSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = "__all__"
filterset_class = UserFilter
queryset = User.objects.all()
class UserDetailAPIView(StaffEditorPermissionMixin, generics.RetrieveAPIView):
queryset = User.objects.all()
serializer_class = CustomReadOnlyUserSerializer
lookup_field = "pk"
def retrieve(self, request, *args, **kwargs):
instance = self.get_object()
serializer = self.get_serializer(instance)
data = serializer.data
# Customize the response format
return Response(data)
@api_view(["GET"])
def healthcheck(request):
return Response({"status": "ok"}, status=status.HTTP_200_OK)
@api_view(["POST"])
@permission_classes((permissions.AllowAny,))
def test_email(request):
send_mail(
"Subject here",
"Here is the message.",
"noreply@sarlink.net",
["shihaam@shihaam.me"],
fail_silently=False,
)
return Response({"status": "ok"}, status=status.HTTP_200_OK)

0
apibase/__init__.py Normal file
View File

16
apibase/asgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
ASGI config for apibase project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "apibase.settings")
application = get_asgi_application()

355
apibase/settings.py Normal file
View File

@ -0,0 +1,355 @@
"""
Django settings for apibase project.
Generated by 'django-admin startproject' using Django 5.0.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/ref/settings/
"""
import os
from pathlib import Path
import datetime
from rest_framework.settings import api_settings
from decouple import config
from django.utils.log import DEFAULT_LOGGING
import logging.config
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config("SECRET_KEY")
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config("DEBUG", cast=bool)
if not DEBUG:
ALLOWED_HOSTS = str(config("DJANGO_ALLOWED_HOSTS", cast=str)).split(" ")
if DEBUG:
INTERNAL_IPS = [
"127.0.0.1",
]
# CORS
# CORS_ALLOWED_ORIGINS = ["http://localhost:3000", "http://127.0.0.1:3000"]
# CORS_ALLOWED_ORIGIN_REGEXES
CORS_ALLOW_ALL_ORIGINS = True
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"rest_framework",
"django_rest_passwordreset",
"djangopasswordlessknox",
"django_extensions",
"django_seed",
"storages",
"whitenoise.runserver_nostatic",
"django.contrib.staticfiles",
# applications
"api",
"billing",
"devices",
# Authentication
"knox",
# third party
"django_filters",
"corsheaders",
]
if DEBUG:
INSTALLED_APPS.append("debug_toolbar")
INSTALLED_APPS.append("drf_spectacular")
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
"django.contrib.sessions.middleware.SessionMiddleware",
"corsheaders.middleware.CorsMiddleware",
"easyaudit.middleware.easyaudit.EasyAuditMiddleware",
"django.middleware.common.CommonMiddleware",
"django.middleware.csrf.CsrfViewMiddleware",
"django.contrib.auth.middleware.AuthenticationMiddleware",
"django.contrib.messages.middleware.MessageMiddleware",
"django.middleware.clickjacking.XFrameOptionsMiddleware",
]
if DEBUG:
MIDDLEWARE.append(
"debug_toolbar.middleware.DebugToolbarMiddleware",
)
ROOT_URLCONF = "apibase.urls"
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": [
BASE_DIR,
"templates/",
],
"APP_DIRS": True,
"OPTIONS": {
"context_processors": [
"django.template.context_processors.debug",
"django.template.context_processors.request",
"django.contrib.auth.context_processors.auth",
"django.contrib.messages.context_processors.messages",
],
},
},
]
WSGI_APPLICATION = "apibase.wsgi.application"
# Database
# https://docs.djangoproject.com/en/5.0/ref/settings/#databases
if not DEBUG:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": config("POSTGRES_DATABASE"),
"USER": config("POSTGRES_USER"),
"PASSWORD": config("POSTGRES_PASSWORD"),
"HOST": config("POSTGRES_HOST"),
"PORT": config("POSTGRES_PORT"),
"OPTIONS": {
"pool": True,
},
},
}
else:
DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
if not DEBUG:
CACHES = {
"default": {
"BACKEND": "django_redis.cache.RedisCache",
"LOCATION": "redis://redis:6379/",
"OPTIONS": {
"CLIENT_CLASS": "django_redis.client.DefaultClient",
},
}
}
# Password validation
# https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators
# Uses email as username for login
AUTH_USER_MODEL = "api.User"
AUTHENTICATION_BACKENDS = ["api.backends.EmailBackend"]
AUTH_PASSWORD_VALIDATORS = [
{
"NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
},
{
"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
},
{
"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
},
{
"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
},
]
# Internationalization
# https://docs.djangoproject.com/en/5.0/topics/i18n/
LANGUAGE_CODE = "en-us"
TIME_ZONE = "UTC"
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/5.0/howto/static-files/
STATIC_URL = "/static/"
STATIC_ROOT = BASE_DIR / "staticfiles"
STATICFILES_DIRS = [
# os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = "/media/"
MEDIA_ROOT = os.path.join(BASE_DIR, "media")
STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"
REST_FRAMEWORK = {
"DEFAULT_FILTER_BACKENDS": ["django_filters.rest_framework.DjangoFilterBackend"],
"DEFAULT_AUTHENTICATION_CLASSES": [
"knox.auth.TokenAuthentication",
# "api.authentication.TokenAuthentication",
# "api.authentication.TokenAuthSupportCookie",
# "rest_framework.authentication.SessionAuthentication",
# "rest_framework_simplejwt.authentication.JWTAuthentication",
],
"DEFAULT_PERMISSION_CLASSES": [
"rest_framework.permissions.IsAuthenticatedOrReadOnly"
],
"DEFAULT_PAGINATION_CLASS": "api.pagination.CustomPagination",
"PAGE_SIZE": 10,
"DEFAULT_THROTTLE_CLASSES": [
"rest_framework.throttling.AnonRateThrottle",
"rest_framework.throttling.UserRateThrottle",
"rest_framework.throttling.ScopedRateThrottle",
],
"DEFAULT_THROTTLE_RATES": {
"anon": "100/day",
"user": "1000/min",
"login": "1000/min",
},
"EXCEPTION_HANDLER": "api.exceptions.custom_exception_handler",
"DEFAULT_RENDERER_CLASSES": ("rest_framework.renderers.JSONRenderer",),
# "DEFAULT_SCHEMA_CLASS": "drf_spectacular.openapi.AutoSchema"
}
REST_KNOX = {
"SECURE_HASH_ALGORITHM": "cryptography.hazmat.primitives.hashes.SHA512",
"AUTH_TOKEN_CHARACTER_LENGTH": 64,
"TOKEN_TTL": datetime.timedelta(minutes=30),
"USER_SERIALIZER": "api.serializers.CustomUserSerializer",
"TOKEN_LIMIT_PER_USER": 10,
"AUTO_REFRESH": True,
"EXPIRY_DATETIME_FORMAT": api_settings.DATETIME_FORMAT,
}
DJANGORESIZED_DEFAULT_SIZE = [500, 500]
DJANGORESIZED_DEFAULT_QUALITY = 75
DJANGORESIZED_DEFAULT_KEEP_META = True
DJANGORESIZED_DEFAULT_FORCE_FORMAT = "JPEG"
DJANGORESIZED_DEFAULT_FORMAT_EXTENSIONS = {"JPEG": ".jpg"}
DJANGORESIZED_DEFAULT_NORMALIZE_ROTATION = True
AWS_ACCESS_KEY_ID = config("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = config("AWS_ACCESS_SECRET")
AWS_STORAGE_BUCKET_NAME = config("AWS_BUCKET")
AWS_S3_FILE_OVERWRITE = False
AWS_DEFAULT_ACL = None
DEFAULT_FILE_STORAGE = "storages.backends.s3.S3Storage"
STORAGES = {
"default": {
"BACKEND": "storages.backends.s3.S3Storage",
},
"staticfiles": {
"BACKEND": "whitenoise.storage.CompressedManifestStaticFilesStorage",
},
}
LOGGING_CONFIG = None
LOGLEVEL = os.environ.get("LOGLEVEL", "warning").upper()
logging.config.dictConfig(
{
"version": 1,
"disable_existing_loggers": False,
"formatters": {
"default": {
"format": "%(asctime)s %(name)-12s %(levelname)-8s %(message)s",
},
"request": {
"format": "%(asctime)s %(levelname)s %(message)s",
},
"django.server": DEFAULT_LOGGING["formatters"]["django.server"],
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "default",
},
"request": {
"class": "logging.StreamHandler",
"formatter": "request",
},
"django.server": DEFAULT_LOGGING["handlers"]["django.server"],
},
"loggers": {
"": {
"level": "WARNING",
"handlers": ["console"],
},
"app": {
"level": LOGLEVEL,
"handlers": ["console"],
"propagate": False,
},
"django.request": {
"level": "WARNING",
"handlers": ["request"],
"propagate": False,
},
"django.server": DEFAULT_LOGGING["loggers"]["django.server"],
},
}
)
if not DEBUG:
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = config("SECURE_HSTS_SECONDS", cast=int)
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_HSTS_PRELOAD = True
CSRF_TRUSTED_ORIGINS = [config("CSRF_ALLOWED_HOST")]
CSRF_COOKIE_DOMAIN = config("CSRF_COOKIE_DOMAIN")
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
EMAIL_BACKEND = (
"django.core.mail.backends.smtp.EmailBackend" # Replace with your preferred backend
)
EMAIL_HOST = config("EMAIL_HOSTNAME")
EMAIL_PORT = config("EMAIL_PORT", cast=int)
EMAIL_HOST_USER = config("EMAIL_USERNAME")
EMAIL_HOST_PASSWORD = config("EMAIL_PASSWORD")
# DEFAULT_FROM_EMAIL = "noreply@sarlink.net"
EMAIL_USE_TLS = True
PASSWORDLESS_AUTH = {
# 'PASSWORDLESS_EMAIL_TOKEN_HTML_TEMPLATE_NAME': "password_reset_email.html",
"PASSWORDLESS_AUTH_TYPES": ["EMAIL", "MOBILE"],
"PASSWORDLESS_USER_MOBILE_FIELD_NAME": "mobile",
"PASSWORDLESS_TEST_SUPPRESSION": False,
"PASSWORDLESS_REGISTER_NEW_USERS": True,
"PASSWORDLESS_EMAIL_NOREPLY_ADDRESS": "noreply@sarlink.net",
}

57
apibase/urls.py Normal file
View File

@ -0,0 +1,57 @@
"""
URL configuration for apibase project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from drf_spectacular.views import (
SpectacularAPIView,
SpectacularRedocView,
SpectacularSwaggerView,
)
urlpatterns = [
path("admin/", admin.site.urls),
path(
"api/password_reset/",
include("django_rest_passwordreset.urls", namespace="password_reset"),
),
path("", include("djangopasswordlessknox.urls")),
# Authentication
path("api/auth/", include("api.urls")),
# Devices
path("api/devices/", include("devices.urls")),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += (path("api-auth/", include("rest_framework.urls")),)
urlpatterns += (path("__debug__/", include("debug_toolbar.urls")),)
urlpatterns += (path("api/schema/", SpectacularAPIView.as_view(), name="schema"),)
urlpatterns += (
path(
"api/swagger/swagger-ui/",
SpectacularSwaggerView.as_view(),
name="swagger-ui",
),
)
urlpatterns += (
path(
"api/redoc/", SpectacularRedocView.as_view(url_name="schema"), name="redoc"
),
)

16
apibase/wsgi.py Normal file
View File

@ -0,0 +1,16 @@
"""
WSGI config for apibase project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "apibase.settings")
application = get_wsgi_application()

0
billing/__init__.py Normal file
View File

3
billing/admin.py Normal file
View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

6
billing/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class BillingConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "billing"

View File

@ -0,0 +1,56 @@
# Generated by Django 5.1.2 on 2025-01-20 04:50
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="Device",
fields=[
(
"id",
models.CharField(max_length=255, primary_key=True, serialize=False),
),
("name", models.CharField(max_length=255)),
("mac", models.CharField(max_length=255)),
(
"reason_for_blocking",
models.CharField(blank=True, max_length=255, null=True),
),
("is_active", models.BooleanField(default=False)),
("registered", models.BooleanField(default=False)),
("blocked", models.BooleanField(default=False)),
(
"blocked_by",
models.CharField(
choices=[("ADMIN", "Admin"), ("PARENT", "Parent")],
default="PARENT",
max_length=255,
),
),
("expiry_date", models.DateTimeField(blank=True, null=True)),
("created_at", models.DateTimeField(default=django.utils.timezone.now)),
("updated_at", models.DateTimeField(auto_now=True)),
(
"user",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="devices",
to=settings.AUTH_USER_MODEL,
),
),
],
),
]

View File

@ -0,0 +1,93 @@
# Generated by Django 5.1.2 on 2025-01-20 06:58
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("billing", "0001_initial"),
("devices", "0003_device_delete_billformula_remove_topup_user_and_more"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="BillFormula",
fields=[
(
"id",
models.CharField(max_length=255, primary_key=True, serialize=False),
),
("formula", models.CharField(max_length=255)),
("base_amount", models.FloatField()),
("discount_percentage", models.FloatField()),
("created_at", models.DateTimeField(default=django.utils.timezone.now)),
("updated_at", models.DateTimeField(auto_now=True)),
],
),
migrations.CreateModel(
name="Payment",
fields=[
(
"id",
models.CharField(max_length=255, primary_key=True, serialize=False),
),
("number_of_months", models.IntegerField()),
("amount", models.FloatField()),
("paid", models.BooleanField(default=False)),
("paid_at", models.DateTimeField(blank=True, null=True)),
(
"method",
models.CharField(
choices=[("WALLET", "Wallet"), ("TRANSFER", "Transfer")],
default="TRANSFER",
max_length=255,
),
),
("expires_at", models.DateTimeField(blank=True, null=True)),
("created_at", models.DateTimeField(default=django.utils.timezone.now)),
("updated_at", models.DateTimeField(auto_now=True)),
(
"devices",
models.ManyToManyField(
related_name="payments", to="devices.device"
),
),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="payments",
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.CreateModel(
name="Topup",
fields=[
(
"id",
models.CharField(max_length=255, primary_key=True, serialize=False),
),
("amount", models.FloatField()),
("paid", models.BooleanField(default=False)),
("created_at", models.DateTimeField(default=django.utils.timezone.now)),
("updated_at", models.DateTimeField(auto_now=True)),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="topups",
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.DeleteModel(
name="Device",
),
]

View File

51
billing/models.py Normal file
View File

@ -0,0 +1,51 @@
from django.db import models
from django.utils import timezone
from api.models import User
# Create your models here.
from devices.models import Device
# Create your models here.
class Payment(models.Model):
PAYMENT_TYPES = [
('WALLET', 'Wallet'),
('TRANSFER', 'Transfer'),
]
id = models.CharField(primary_key=True, max_length=255)
number_of_months = models.IntegerField()
amount = models.FloatField()
paid = models.BooleanField(default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='payments')
paid_at = models.DateTimeField(null=True, blank=True)
method = models.CharField(max_length=255, choices=PAYMENT_TYPES, default='TRANSFER')
expires_at = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
devices = models.ManyToManyField(Device, related_name='payments')
def __str__(self):
return f"Payment by {self.user}"
class BillFormula(models.Model):
id = models.CharField(primary_key=True, max_length=255)
formula = models.CharField(max_length=255)
base_amount = models.FloatField()
discount_percentage = models.FloatField()
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.formula
class Topup(models.Model):
id = models.CharField(primary_key=True, max_length=255)
amount = models.FloatField()
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='topups')
paid = models.BooleanField(default=False)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return f"Topup for {self.user}"

3
billing/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

2
billing/views.py Normal file
View File

@ -0,0 +1,2 @@
# Create your views here.

0
devices/__init__.py Normal file
View File

6
devices/admin.py Normal file
View File

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

6
devices/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class DevicesConfig(AppConfig):
default_auto_field = "django.db.models.BigAutoField"
name = "devices"

12
devices/filters.py Normal file
View File

@ -0,0 +1,12 @@
import django_filters
from .models import Device
class DeviceFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr="icontains")
mac = django_filters.CharFilter(lookup_expr="icontains")
user = django_filters.CharFilter(field_name='user__last_name', lookup_expr="icontains")
class Meta:
model = Device
fields = "__all__"

View File

@ -0,0 +1,84 @@
# Generated by Django 5.1.2 on 2025-01-20 04:51
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="BillFormula",
fields=[
(
"id",
models.CharField(max_length=255, primary_key=True, serialize=False),
),
("formula", models.CharField(max_length=255)),
("base_amount", models.FloatField()),
("discount_percentage", models.FloatField()),
("created_at", models.DateTimeField(default=django.utils.timezone.now)),
("updated_at", models.DateTimeField(auto_now=True)),
],
),
migrations.CreateModel(
name="Payment",
fields=[
(
"id",
models.CharField(max_length=255, primary_key=True, serialize=False),
),
("number_of_months", models.IntegerField()),
("amount", models.FloatField()),
("paid", models.BooleanField(default=False)),
("paid_at", models.DateTimeField(blank=True, null=True)),
(
"method",
models.CharField(
choices=[("WALLET", "Wallet"), ("TRANSFER", "Transfer")],
default="TRANSFER",
max_length=255,
),
),
("expires_at", models.DateTimeField(blank=True, null=True)),
("created_at", models.DateTimeField(default=django.utils.timezone.now)),
("updated_at", models.DateTimeField(auto_now=True)),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="payments",
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.CreateModel(
name="Topup",
fields=[
(
"id",
models.CharField(max_length=255, primary_key=True, serialize=False),
),
("amount", models.FloatField()),
("paid", models.BooleanField(default=False)),
("created_at", models.DateTimeField(default=django.utils.timezone.now)),
("updated_at", models.DateTimeField(auto_now=True)),
(
"user",
models.ForeignKey(
on_delete=django.db.models.deletion.CASCADE,
related_name="topups",
to=settings.AUTH_USER_MODEL,
),
),
],
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 5.1.2 on 2025-01-20 04:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("billing", "0001_initial"),
("devices", "0001_initial"),
]
operations = [
migrations.AddField(
model_name="payment",
name="devices",
field=models.ManyToManyField(related_name="payments", to="billing.device"),
),
]

View File

@ -0,0 +1,68 @@
# Generated by Django 5.1.2 on 2025-01-20 06:58
import django.db.models.deletion
import django.utils.timezone
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("devices", "0002_payment_devices"),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name="Device",
fields=[
(
"id",
models.CharField(max_length=255, primary_key=True, serialize=False),
),
("name", models.CharField(max_length=255)),
("mac", models.CharField(max_length=255)),
(
"reason_for_blocking",
models.CharField(blank=True, max_length=255, null=True),
),
("is_active", models.BooleanField(default=False)),
("registered", models.BooleanField(default=False)),
("blocked", models.BooleanField(default=False)),
(
"blocked_by",
models.CharField(
choices=[("ADMIN", "Admin"), ("PARENT", "Parent")],
default="PARENT",
max_length=255,
),
),
("expiry_date", models.DateTimeField(blank=True, null=True)),
("created_at", models.DateTimeField(default=django.utils.timezone.now)),
("updated_at", models.DateTimeField(auto_now=True)),
(
"user",
models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="devices",
to=settings.AUTH_USER_MODEL,
),
),
],
),
migrations.DeleteModel(
name="BillFormula",
),
migrations.RemoveField(
model_name="topup",
name="user",
),
migrations.DeleteModel(
name="Payment",
),
migrations.DeleteModel(
name="Topup",
),
]

View File

@ -0,0 +1,19 @@
# Generated by Django 5.1.2 on 2025-01-20 07:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("devices", "0003_device_delete_billformula_remove_topup_user_and_more"),
]
operations = [
migrations.AlterField(
model_name="device",
name="id",
field=models.BigAutoField(
auto_created=True, primary_key=True, serialize=False, verbose_name="ID"
),
),
]

View File

21
devices/models.py Normal file
View File

@ -0,0 +1,21 @@
from django.db import models
from django.utils import timezone
from api.models import User
class Device(models.Model):
name = models.CharField(max_length=255)
mac = models.CharField(max_length=255)
reason_for_blocking = models.CharField(max_length=255, null=True, blank=True)
is_active = models.BooleanField(default=False)
registered = models.BooleanField(default=False)
blocked = models.BooleanField(default=False)
blocked_by = models.CharField(max_length=255, choices=[('ADMIN', 'Admin'), ('PARENT', 'Parent')], default='PARENT')
expiry_date = models.DateTimeField(null=True, blank=True)
created_at = models.DateTimeField(default=timezone.now)
updated_at = models.DateTimeField(auto_now=True)
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, related_name='devices')
def __str__(self):
return self.name

20
devices/serializers.py Normal file
View File

@ -0,0 +1,20 @@
from rest_framework import serializers
from .models import Device
from api.serializers import CustomReadOnlyUserSerializer
class CreateDeviceSerializer(serializers.ModelSerializer):
class Meta:
model = Device
fields = ["name", "mac"]
class DeviceSerializer(serializers.ModelSerializer):
class Meta:
model = Device
fields = "__all__"
class ReadOnlyDeviceSerializer(serializers.ModelSerializer):
user = CustomReadOnlyUserSerializer(read_only=True)
class Meta: #type: ignore
depth = 2
model = Device
fields = "__all__"

3
devices/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

26
devices/urls.py Normal file
View File

@ -0,0 +1,26 @@
from django.urls import path
from . import views
urlpatterns = [
path(
"",
views.DeviceListCreateAPIView.as_view(),
name="device-list",
),
path(
"<int:pk>/",
views.DeviceDetailAPIView.as_view(),
name="device-detail",
),
path(
"<int:pk>/update/",
views.DeviceUpdateAPIView.as_view(),
name="device-edit",
),
path(
"<int:pk>/delete/",
views.DeviceDestroyAPIView.as_view(),
name="device-delete",
),
]

76
devices/views.py Normal file
View File

@ -0,0 +1,76 @@
from rest_framework import generics, status
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from .models import Device
from .serializers import CreateDeviceSerializer, DeviceSerializer, ReadOnlyDeviceSerializer
from api.mixins import StaffEditorPermissionMixin
from .filters import DeviceFilter
import re
class DeviceListCreateAPIView(
StaffEditorPermissionMixin,
generics.ListCreateAPIView,
):
queryset = Device.objects.select_related("user").all()
serializer_class = CreateDeviceSerializer
filter_backends = [DjangoFilterBackend]
filterset_fields = "__all__"
filterset_class = DeviceFilter
def get_serializer_class(self) -> type:
if self.request.method == "POST":
return CreateDeviceSerializer
return DeviceSerializer
# @method_decorator(cache_page(10))
def create(self, request, *args, **kwargs):
mac = request.data.get("mac", None)
if not re.match(r"^([0-9A-Fa-f]{2}([.:-]?)){5}[0-9A-Fa-f]{2}$", mac):
return Response({"error": "Invalid mac address"}, status=400)
if Device.objects.filter(mac=mac).exists():
return Response({"error": "Device with this mac already exists"}, status=400)
return super().create(request, *args, **kwargs)
def perform_create(self, serializer):
serializer.save(user=self.request.user)
class DeviceDetailAPIView(StaffEditorPermissionMixin, generics.RetrieveAPIView):
queryset = Device.objects.select_related("user").all()
serializer_class = ReadOnlyDeviceSerializer
lookup_field = "pk"
class DeviceUpdateAPIView(StaffEditorPermissionMixin, generics.UpdateAPIView):
queryset = Device.objects.all()
serializer_class = CreateDeviceSerializer
lookup_field = "pk"
def update(self, request, *args, **kwargs):
# Pass 'partial=True' to allow partial updates
partial = kwargs.pop("partial", True)
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=partial)
serializer.is_valid(raise_exception=True)
self.perform_update(serializer)
return Response(serializer.data)
class DeviceDestroyAPIView(StaffEditorPermissionMixin, generics.DestroyAPIView):
queryset = Device.objects.all()
serializer_class = DeviceSerializer
lookup_field = "pk"
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
device_name = instance.name
self.perform_destroy(instance)
return Response(
{"message": f"Device '{device_name}' deleted."},
status=status.HTTP_200_OK,
)

View File

@ -0,0 +1,12 @@
# -*- coding: utf-8 -*-
__title__ = 'djangopasswordlessknox'
__version__ = '1.4.0'
__author__ = 'Lijo'
__license__ = 'MIT'
__copyright__ = 'Copyright 2019 lijo'
# Version synonym
VERSION = __version__
default_app_config = 'djangopasswordlessknox.apps.DrfpasswordlessConfig'

View File

@ -0,0 +1,3 @@
VERSION = (1, 4, 0)
__version__ = '.'.join(map(str, VERSION))

View File

@ -0,0 +1,34 @@
from django.contrib import admin
from django.urls import reverse
from djangopasswordlessknox.models import CallbackToken
class UserLinkMixin(object):
"""
A mixin to add a linkable list_display user field.
"""
LINK_TO_USER_FIELD = 'link_to_user'
def link_to_user(self, obj):
link = reverse('admin:users_user_change', args=[obj.user.id])
return u'<a href={}>{}</a>'.format(link, obj.user.username)
link_to_user.allow_tags = True
link_to_user.short_description = 'User'
class AbstractCallbackTokenInline(admin.StackedInline):
max_num = 0
extra = 0
readonly_fields = ('created_at', 'key', 'is_active')
fields = ('created_at', 'user', 'key', 'is_active')
class CallbackInline(AbstractCallbackTokenInline):
model = CallbackToken
class AbstractCallbackTokenAdmin(UserLinkMixin, admin.ModelAdmin):
readonly_fields = ('created_at', 'user', 'key')
list_display = ('created_at', UserLinkMixin.LINK_TO_USER_FIELD, 'key', 'is_active')
fields = ('created_at', 'user', 'key', 'is_active')
extra = 0

View File

@ -0,0 +1,9 @@
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class DrfpasswordlessConfig(AppConfig):
name = 'djangopasswordlessknox'
verbose = _("DRF Passwordless")
def ready(self):
import djangopasswordlessknox.signals

View File

@ -0,0 +1,43 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-04-05 03:27
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import djangopasswordlessknox.models
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='CallbackToken',
fields=[
('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False, unique=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
('is_active', models.BooleanField(default=True)),
('to_alias', models.CharField(blank=True, max_length=40)),
('to_alias_type', models.CharField(blank=True, max_length=20)),
('key', models.CharField(default=djangopasswordlessknox.models.generate_numeric_token, max_length=6, unique=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
options={
'verbose_name': 'Callback Token',
'abstract': False,
'ordering': ['-id'],
'get_latest_by': 'created_at',
},
),
migrations.AlterUniqueTogether(
name='callbacktoken',
unique_together=set([('key', 'is_active')]),
),
]

View File

@ -0,0 +1,62 @@
import uuid
from random import randint
from django.db import models
from django.conf import settings
def generate_hex_token():
return uuid.uuid1().hex
def generate_numeric_token():
"""
Generate a random 6 digit string of numbers.
We use this formatting to allow leading 0s.
"""
return str("%06d" % randint(0, 999999))
class CallbackTokenManger(models.Manager):
def active(self):
return self.get_queryset().filter(is_active=True)
def inactive(self):
return self.get_queryset().filter(is_active=False)
class AbstractBaseCallbackToken(models.Model):
"""
Callback Authentication Tokens
These tokens present a client with their authorization token
on successful exchange of a random token (email) or token (for mobile)
When a new token is created, older ones of the same type are invalidated
via the pre_save signal in signals.py.
"""
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True)
created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name=None, on_delete=models.CASCADE)
is_active = models.BooleanField(default=True)
to_alias = models.CharField(blank=True, max_length=40)
to_alias_type = models.CharField(blank=True, max_length=20)
objects = CallbackTokenManger()
class Meta:
abstract = True
get_latest_by = 'created_at'
ordering = ['-id']
unique_together = (('key', 'is_active'),)
def __str__(self):
return str(self.key)
class CallbackToken(AbstractBaseCallbackToken):
"""
Generates a random six digit number to be returned.
"""
key = models.CharField(default=generate_numeric_token, max_length=6, unique=True)
class Meta(AbstractBaseCallbackToken.Meta):
verbose_name = 'Callback Token'

View File

@ -0,0 +1,257 @@
import logging
from django.utils.translation import gettext_lazy as _
from django.contrib.auth import get_user_model
from django.core.exceptions import PermissionDenied
from django.core.validators import RegexValidator
from rest_framework import serializers
from djangopasswordlessknox.models import CallbackToken
from djangopasswordlessknox.settings import api_settings
from djangopasswordlessknox.utils import authenticate_by_token, verify_user_alias, validate_token_age
logger = logging.getLogger(__name__)
User = get_user_model()
class TokenField(serializers.CharField):
default_error_messages = {
'required': _('Invalid Token'),
'invalid': _('Invalid Token'),
'blank': _('Invalid Token'),
'max_length': _('Tokens are {max_length} digits long.'),
'min_length': _('Tokens are {min_length} digits long.')
}
class AbstractBaseAliasAuthenticationSerializer(serializers.Serializer):
"""
Abstract class that returns a callback token based on the field given
Returns a token if valid, None or a message if not.
"""
@property
def alias_type(self):
# The alias type, either email or mobile
raise NotImplementedError
def validate(self, attrs):
alias = attrs.get(self.alias_type)
print("ALIAS", alias)
print("ALIAS TYPE", self.alias_type)
if alias:
# Create or authenticate a user
# Return THem
if api_settings.PASSWORDLESS_REGISTER_NEW_USERS is True:
# If new aliases should register new users.
try:
user = User.objects.get(**{self.alias_type: alias})
user_created = False
except User.DoesNotExist:
# If no user is found, raise an error
msg = ""
if self.alias_type == 'email':
msg = _('No user found with this email.')
elif self.alias_type == 'mobile':
msg = _('No user found with this mobile number.')
raise serializers.ValidationError(msg)
else:
# If new aliases should not register new users.
try:
user = User.objects.get(**{self.alias_type: alias})
except User.DoesNotExist:
user = None
if user:
if not user.is_active:
# If valid, return attrs so we can create a token in our logic controller
msg = _('User account is disabled.')
raise serializers.ValidationError(msg)
else:
msg = _('No account is associated with this alias.')
raise serializers.ValidationError(msg)
else:
msg = _('Missing %s.') % self.alias_type
raise serializers.ValidationError(msg)
attrs['user'] = user
return attrs
class EmailAuthSerializer(AbstractBaseAliasAuthenticationSerializer):
@property
def alias_type(self):
return 'email'
email = serializers.EmailField()
class MobileAuthSerializer(AbstractBaseAliasAuthenticationSerializer):
@property
def alias_type(self):
return 'mobile'
phone_regex = RegexValidator(regex=r'^[7|9][0-9]{6}$',
message="Mobile number must be entered in the format:"
" '7xxxxxx' or '9xxxxxx'.")
mobile = serializers.CharField(validators=[phone_regex], max_length=15)
"""
Verification
"""
class AbstractBaseAliasVerificationSerializer(serializers.Serializer):
"""
Abstract class that returns a callback token based on the field given
Returns a token if valid, None or a message if not.
"""
@property
def alias_type(self):
# The alias type, either email or mobile
raise NotImplementedError
def validate(self, attrs):
msg = _('There was a problem with your request.')
if self.alias_type:
# Get request.user
# Get their specified valid endpoint
# Validate
request = self.context["request"]
if request and hasattr(request, "user"):
user = request.user
if user:
if not user.is_active:
# If valid, return attrs so we can create a token in our logic controller
msg = _('User account is disabled.')
else:
if hasattr(user, self.alias_type):
# Has the appropriate alias type
attrs['user'] = user
return attrs
else:
msg = _('This user doesn\'t have an %s.' % self.alias_type)
raise serializers.ValidationError(msg)
else:
msg = _('Missing %s.') % self.alias_type
raise serializers.ValidationError(msg)
class EmailVerificationSerializer(AbstractBaseAliasVerificationSerializer):
@property
def alias_type(self):
return 'email'
class MobileVerificationSerializer(AbstractBaseAliasVerificationSerializer):
@property
def alias_type(self):
return 'mobile'
"""
Callback Token
"""
def token_age_validator(value):
"""
Check token age
Makes sure a token is within the proper expiration datetime window.
"""
valid_token = validate_token_age(value)
if not valid_token:
raise serializers.ValidationError("The token you entered isn't valid.")
return value
class AbstractBaseCallbackTokenSerializer(serializers.Serializer):
"""
Abstract class inspired by DRF's own token serializer.
Returns a user if valid, None or a message if not.
"""
token = TokenField(min_length=6, max_length=6, validators=[token_age_validator])
class CallbackTokenAuthSerializer(AbstractBaseCallbackTokenSerializer):
def validate(self, attrs):
callback_token = attrs.get('token', None)
token = CallbackToken.objects.get(key=callback_token, is_active=True)
if token:
# Check the token type for our uni-auth method.
# authenticates and checks the expiry of the callback token.
user = authenticate_by_token(token)
if user:
if not user.is_active:
msg = _('User account is disabled.')
raise serializers.ValidationError(msg)
if api_settings.PASSWORDLESS_USER_MARK_EMAIL_VERIFIED \
or api_settings.PASSWORDLESS_USER_MARK_MOBILE_VERIFIED:
# Mark this alias as verified
user = User.objects.get(pk=token.user.pk)
success = verify_user_alias(user, token)
if success is False:
msg = _('Error validating user alias.')
raise serializers.ValidationError(msg)
attrs['user'] = user
return attrs
else:
msg = _('Invalid Token')
raise serializers.ValidationError(msg)
else:
msg = _('Missing authentication token.')
raise serializers.ValidationError(msg)
class CallbackTokenVerificationSerializer(AbstractBaseCallbackTokenSerializer):
"""
Takes a user and a token, verifies the token belongs to the user and
validates the alias that the token was sent from.
"""
def validate(self, attrs):
try:
user_id = self.context.get("user_id")
callback_token = attrs.get('token', None)
token = CallbackToken.objects.get(key=callback_token, is_active=True)
user = User.objects.get(pk=user_id)
if token.user == user:
# Check that the token.user is the request.user
# Mark this alias as verified
success = verify_user_alias(user, token)
if success is False:
logger.debug("djangopasswordlessknox: Error verifying alias.")
attrs['user'] = user
return attrs
else:
msg = _('This token is invalid. Try again later.')
logger.debug("djangopasswordlessknox: User token mismatch when verifying alias.")
except CallbackToken.DoesNotExist:
msg = _('Missing authentication token.')
logger.debug("djangopasswordlessknox: Tried to validate alias with bad token.")
pass
except User.DoesNotExist:
msg = _('Missing user.')
logger.debug("djangopasswordlessknox: Tried to validate alias with bad user.")
pass
except PermissionDenied:
msg = _('Insufficient permissions.')
logger.debug("djangopasswordlessknox: Permission denied while validating alias.")
pass
raise serializers.ValidationError(msg)

View File

@ -0,0 +1,23 @@
from djangopasswordlessknox.utils import (
create_callback_token_for_user,
send_email_with_callback_token,
send_sms_with_callback_token
)
class TokenService(object):
@staticmethod
def send_token(user, alias_type, **message_payload):
token = create_callback_token_for_user(user, alias_type)
send_action = None
if alias_type == 'email':
send_action = send_email_with_callback_token
elif alias_type == 'mobile':
send_action = send_sms_with_callback_token
if send_action is None:
raise ValueError(f"Invalid alias_type: {alias_type}")
# Send to alias
success = send_action(user, token, **message_payload)
return success

View File

@ -0,0 +1,79 @@
from django.conf import settings
from rest_framework.settings import APISettings
USER_SETTINGS = getattr(settings, 'PASSWORDLESS_AUTH', None)
DEFAULTS = {
# Allowed auth types, can be EMAIL, MOBILE, or both.
'PASSWORDLESS_AUTH_TYPES': ['EMAIL'],
# Amount of time that tokens last, in seconds
'PASSWORDLESS_TOKEN_EXPIRE_TIME': 15 * 60,
# The user's email field name
'PASSWORDLESS_USER_EMAIL_FIELD_NAME': 'email',
# The user's mobile field name
'PASSWORDLESS_USER_MOBILE_FIELD_NAME': 'mobile',
# Marks itself as verified the first time a user completes auth via token.
# Automatically unmarks itself if email is changed.
'PASSWORDLESS_USER_MARK_EMAIL_VERIFIED': False,
'PASSWORDLESS_USER_EMAIL_VERIFIED_FIELD_NAME': 'email_verified',
# Marks itself as verified the first time a user completes auth via token.
# Automatically unmarks itself if mobile number is changed.
'PASSWORDLESS_USER_MARK_MOBILE_VERIFIED': False,
'PASSWORDLESS_USER_MOBILE_VERIFIED_FIELD_NAME': 'mobile_verified',
# The email the callback token is sent from
'PASSWORDLESS_EMAIL_NOREPLY_ADDRESS': None,
# The email subject
'PASSWORDLESS_EMAIL_SUBJECT': "Your Login Token",
# A plaintext email message overridden by the html message. Takes one string.
'PASSWORDLESS_EMAIL_PLAINTEXT_MESSAGE': "Enter this token to sign in: %s",
# The email template name.
'PASSWORDLESS_EMAIL_TOKEN_HTML_TEMPLATE_NAME': "passwordless_default_token_email.html",
# Your twilio number that sends the callback tokens.
'PASSWORDLESS_MOBILE_NOREPLY_NUMBER': None,
# The message sent to mobile users logging in. Takes one string.
'PASSWORDLESS_MOBILE_MESSAGE': "Use this code to log in: %s",
# Registers previously unseen aliases as new users.
'PASSWORDLESS_REGISTER_NEW_USERS': False,
# Suppresses actual SMS for testing
'PASSWORDLESS_TEST_SUPPRESSION': False,
# Context Processors for Email Template
'PASSWORDLESS_CONTEXT_PROCESSORS': [],
# The verification email subject
'PASSWORDLESS_EMAIL_VERIFICATION_SUBJECT': "Your Verification Token",
# A plaintext verification email message overridden by the html message. Takes one string.
'PASSWORDLESS_EMAIL_VERIFICATION_PLAINTEXT_MESSAGE': "Enter this verification code: %s",
# The verification email template name.
'PASSWORDLESS_EMAIL_VERIFICATION_TOKEN_HTML_TEMPLATE_NAME': "passwordless_default_verification_token_email.html",
# The message sent to mobile users logging in. Takes one string.
'PASSWORDLESS_MOBILE_VERIFICATION_MESSAGE': "Enter this verification code: %s",
# Automatically send verification email or sms when a user changes their alias.
'PASSWORDLESS_AUTO_SEND_VERIFICATION_TOKEN': False,
}
# List of settings that may be in string import notation.
IMPORT_STRINGS = (
'PASSWORDLESS_EMAIL_TOKEN_HTML_TEMPLATE',
'PASSWORDLESS_CONTEXT_PROCESSORS',
)
api_settings = APISettings(USER_SETTINGS, DEFAULTS, IMPORT_STRINGS) #type: ignore

View File

@ -0,0 +1,118 @@
import logging
from django.contrib.auth import get_user_model
from django.dispatch import receiver
from django.db.models import signals
from djangopasswordlessknox.models import CallbackToken
from djangopasswordlessknox.models import generate_numeric_token
from djangopasswordlessknox.settings import api_settings
from djangopasswordlessknox.services import TokenService
logger = logging.getLogger(__name__)
@receiver(signals.pre_save, sender=CallbackToken)
def invalidate_previous_tokens(sender, instance, **kwargs):
"""
Invalidates all previously issued tokens as a post_save signal.
"""
active_tokens = None
if isinstance(instance, CallbackToken):
active_tokens = CallbackToken.objects.active().filter(user=instance.user).exclude(id=instance.id)
# Invalidate tokens
if active_tokens:
for token in active_tokens:
token.is_active = False
token.save()
@receiver(signals.pre_save, sender=CallbackToken)
def check_unique_tokens(sender, instance, **kwargs):
"""
Ensures that mobile and email tokens are unique or tries once more to generate.
"""
if isinstance(instance, CallbackToken):
if CallbackToken.objects.filter(key=instance.key, is_active=True).exists():
instance.key = generate_numeric_token()
User = get_user_model()
@receiver(signals.pre_save, sender=User)
def update_alias_verification(sender, instance, **kwargs):
"""
Flags a user's email as unverified if they change it.
Optionally sends a verification token to the new endpoint.
"""
if isinstance(instance, User):
if instance.id:
if api_settings.PASSWORDLESS_USER_MARK_EMAIL_VERIFIED is True:
"""
For marking email aliases as not verified when a user changes it.
"""
email_field = api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME
email_verified_field = api_settings.PASSWORDLESS_USER_EMAIL_VERIFIED_FIELD_NAME
# Verify that this is an existing instance and not a new one.
try:
user_old = User.objects.get(id=instance.id) # Pre-save object
instance_email = getattr(instance, email_field) # Incoming Email
old_email = getattr(user_old, email_field) # Pre-save object email
if instance_email != old_email and instance_email != "" and instance_email is not None:
# Email changed, verification should be flagged
setattr(instance, email_verified_field, False)
if api_settings.PASSWORDLESS_AUTO_SEND_VERIFICATION_TOKEN is True:
email_subject = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_SUBJECT
email_plaintext = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_PLAINTEXT_MESSAGE
email_html = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_TOKEN_HTML_TEMPLATE_NAME
message_payload = {'email_subject': email_subject,
'email_plaintext': email_plaintext,
'email_html': email_html}
success = TokenService.send_token(instance, 'email', **message_payload)
if success:
logger.info('djangopasswordlessknox: Successfully sent email on updated address: %s'
% instance_email)
else:
logger.info('djangopasswordlessknox: Failed to send email to updated address: %s'
% instance_email)
except User.DoesNotExist:
# User probably is just initially being created
setattr(instance, email_verified_field, True)
if api_settings.PASSWORDLESS_USER_MARK_MOBILE_VERIFIED is True:
"""
For marking mobile aliases as not verified when a user changes it.
"""
mobile_field = api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME
mobile_verified_field = api_settings.PASSWORDLESS_USER_MOBILE_VERIFIED_FIELD_NAME
# Verify that this is an existing instance and not a new one.
try:
user_old = User.objects.get(id=instance.id) # Pre-save object
instance_mobile = getattr(instance, mobile_field) # Incoming mobile
old_mobile = getattr(user_old, mobile_field) # Pre-save object mobile
if instance_mobile != old_mobile and instance_mobile != "" and instance_mobile is not None:
# Mobile changed, verification should be flagged
setattr(instance, mobile_verified_field, False)
if api_settings.PASSWORDLESS_AUTO_SEND_VERIFICATION_TOKEN is True:
mobile_message = api_settings.PASSWORDLESS_MOBILE_MESSAGE
message_payload = {'mobile_message': mobile_message}
success = TokenService.send_token(instance, 'mobile', **message_payload)
if success:
logger.info('djangopasswordlessknox: Successfully sent SMS on updated mobile: %s'
% instance_mobile)
else:
logger.info('djangopasswordlessknox: Failed to send SMS to updated mobile: %s'
% instance_mobile)
except User.DoesNotExist:
# User probably is just initially being created
setattr(instance, mobile_verified_field, True)

View File

@ -0,0 +1,88 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Your Login Token</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f5f5f5;
margin: 0;
padding: 20px;
}
.container {
max-width: 600px;
margin: 0 auto;
background-color: #ffffff;
border-radius: 8px;
padding: 30px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.header {
text-align: center;
margin-bottom: 30px;
}
.logo {
color: #2c3e50;
font-size: 24px;
font-weight: bold;
}
.token-container {
background-color: #f8f9fa;
border: 2px solid #e9ecef;
border-radius: 6px;
padding: 20px;
text-align: center;
margin: 20px 0;
}
.token {
color: #007bff;
font-size: 32px;
font-weight: bold;
letter-spacing: 2px;
}
.message {
color: #6c757d;
font-size: 16px;
line-height: 1.5;
margin-top: 20px;
}
.footer {
margin-top: 30px;
text-align: center;
color: #6c757d;
font-size: 14px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<div class="logo">SARLink Portal</div>
</div>
<div class="token-container">
<div class="message">Your login code is:</div>
<div class="token">{{ callback_token }}</div>
</div>
<div class="message">
Please use this code to complete your login. This code will
expire in 15 minutes for security purposes.
</div>
<div class="footer">
If you didn't request this code, please ignore this email.
<br />
© 2024 Council Portal. All rights reserved.
</div>
</div>
</body>
</html>

View File

@ -0,0 +1,10 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Your Verification Token</title>
</head>
<body>
<h2>Use this verification code: {{ callback_token }}</h2>
</body>
</html>

View File

@ -0,0 +1,18 @@
from django.urls import path
from djangopasswordlessknox.views import (
ObtainEmailCallbackToken,
ObtainMobileCallbackToken,
ObtainAuthTokenFromCallbackToken,
VerifyAliasFromCallbackToken,
ObtainEmailVerificationCallbackToken,
ObtainMobileVerificationCallbackToken,
)
urlpatterns = [
path('callback/auth/', ObtainAuthTokenFromCallbackToken.as_view(), name='auth_callback'),
path('auth/email/', ObtainEmailCallbackToken.as_view(), name='auth_email'),
path('auth/mobile/', ObtainMobileCallbackToken.as_view(), name='auth_mobile'),
path('callback/verify/', VerifyAliasFromCallbackToken.as_view(), name='verify_callback'),
path('verify/email/', ObtainEmailVerificationCallbackToken.as_view(), name='verify_email'),
path('verify/mobile/', ObtainMobileVerificationCallbackToken.as_view(), name='verify_mobile'),
]

View File

@ -0,0 +1,211 @@
import logging
# import os
from django.contrib.auth import get_user_model
from django.core.exceptions import PermissionDenied
from django.core.mail import send_mail
from django.template import loader
from django.utils import timezone
from djangopasswordlessknox.models import CallbackToken
from djangopasswordlessknox.settings import api_settings
# from twilio.rest import Client
from decouple import config
import requests
import json
logger = logging.getLogger(__name__)
User = get_user_model()
def authenticate_by_token(callback_token):
try:
token = CallbackToken.objects.get(key=callback_token, is_active=True)
# Returning a user designates a successful authentication.
token.user = User.objects.get(pk=token.user.pk)
token.is_active = False # Mark this token as used.
token.save()
return token.user
except CallbackToken.DoesNotExist:
logger.debug("djangopasswordlessknox: Challenged with a callback token that doesn't exist.")
except User.DoesNotExist:
logger.debug("djangopasswordlessknox: Authenticated user somehow doesn't exist.")
except PermissionDenied:
logger.debug("djangopasswordlessknox: Permission denied while authenticating.")
return None
def create_callback_token_for_user(user, token_type):
token = None
token_type = token_type.upper()
if token_type == 'EMAIL':
token = CallbackToken.objects.create(user=user,
to_alias_type=token_type,
to_alias=getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME))
elif token_type == 'MOBILE':
token = CallbackToken.objects.create(user=user,
to_alias_type=token_type,
to_alias=getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME))
if token is not None:
return token
return None
def validate_token_age(callback_token):
"""
Returns True if a given token is within the age expiration limit.
"""
try:
token = CallbackToken.objects.get(key=callback_token, is_active=True)
seconds = (timezone.now() - token.created_at).total_seconds()
token_expiry_time = api_settings.PASSWORDLESS_TOKEN_EXPIRE_TIME
if seconds <= token_expiry_time:
return True
else:
# Invalidate our token.
token.is_active = False
token.save()
return False
except CallbackToken.DoesNotExist:
# No valid token.
return False
def verify_user_alias(user, token):
"""
Marks a user's contact point as verified depending on accepted token type.
"""
if token.to_alias_type == 'EMAIL':
if token.to_alias == getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME):
setattr(user, api_settings.PASSWORDLESS_USER_EMAIL_VERIFIED_FIELD_NAME, True)
elif token.to_alias_type == 'MOBILE':
if token.to_alias == getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME):
setattr(user, api_settings.PASSWORDLESS_USER_MOBILE_VERIFIED_FIELD_NAME, True)
else:
return False
user.save()
return True
def inject_template_context(context):
"""
Injects additional context into email template.
"""
for processor in api_settings.PASSWORDLESS_CONTEXT_PROCESSORS:
context.update(processor())
return context
def send_email_with_callback_token(user, email_token, **kwargs):
"""
Sends a Email to user.email.
Passes silently without sending in test environment
"""
try:
if api_settings.PASSWORDLESS_EMAIL_NOREPLY_ADDRESS:
# Make sure we have a sending address before sending.
# Get email subject and message
email_subject = kwargs.get('email_subject',
api_settings.PASSWORDLESS_EMAIL_SUBJECT)
email_plaintext = kwargs.get('email_plaintext',
api_settings.PASSWORDLESS_EMAIL_PLAINTEXT_MESSAGE)
email_html = kwargs.get('email_html',
api_settings.PASSWORDLESS_EMAIL_TOKEN_HTML_TEMPLATE_NAME)
# Inject context if user specifies.
context = inject_template_context({'callback_token': email_token.key, })
html_message = loader.render_to_string(email_html, context,)
send_mail(
email_subject,
email_plaintext % email_token.key,
api_settings.PASSWORDLESS_EMAIL_NOREPLY_ADDRESS,
[getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME)],
fail_silently=False,
html_message=html_message,)
else:
logger.debug("Failed to send token email. Missing PASSWORDLESS_EMAIL_NOREPLY_ADDRESS.")
return False
return True
except Exception as e:
logger.debug("Failed to send token email to user: %d."
"Possibly no email on user object. Email entered was %s" %
(user.id, getattr(user, api_settings.PASSWORDLESS_USER_EMAIL_FIELD_NAME)))
logger.debug(e)
return False
def send_sms_with_callback_token(user, mobile_token, **kwargs):
"""
Sends a SMS to user.mobile via Twilio.
Passes silently without sending in test environment.
"""
base_string = kwargs.get('mobile_message', api_settings.PASSWORDLESS_MOBILE_MESSAGE)
try:
if api_settings.PASSWORDLESS_MOBILE_NOREPLY_NUMBER:
print("Sending SMS")
# We need a sending number to send properly
if api_settings.PASSWORDLESS_TEST_SUPPRESSION is True:
# we assume success to prevent spamming SMS during testing.
return True
to_number = getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME)
if to_number.__class__.__name__ == 'PhoneNumber':
to_number = to_number.__str__()
# user_withh_mobile_exists = User.objects.filter(mobile=to_number).exists()
# if not user_withh_mobile_exists:
# print("User with mobile number does not exist.")
# logger.debug("User with mobile number does not exist.")
# return False
api_url = config("SMS_API_URL")
api_key = config("SMS_API_KEY")
if not api_url or not api_key:
logger.debug("Failed to send SMS. Missing SMS_API_URL or SMS_API_KEY.")
return False
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {api_key}"
}
data = {
"number": to_number,
"message": base_string % mobile_token.key,
"check_delivery": False
}
response = requests.post(api_url, headers=headers, data=json.dumps(data))
if response.status_code == 200:
return True
else:
logger.debug(f"Failed to send SMS. Status code: {response.status_code}")
return False
else:
logger.debug("Failed to send token sms. Missing PASSWORDLESS_MOBILE_NOREPLY_NUMBER.")
return False
except ImportError:
logger.debug("Couldn't import Twilio client. Is twilio installed?")
return False
except KeyError:
logger.debug("Couldn't send SMS."
"Did you set your Twilio account tokens and specify a PASSWORDLESS_MOBILE_NOREPLY_NUMBER?")
except Exception as e:
logger.debug("Failed to send token SMS to user: {}. "
"Possibly no mobile number on user object or the twilio package isn't set up yet. "
"Number entered was {}".format(user.id, getattr(user, api_settings.PASSWORDLESS_USER_MOBILE_FIELD_NAME)))
logger.debug(e)
return False

View File

@ -0,0 +1,213 @@
import logging
from rest_framework import parsers, renderers, status
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.views import APIView
from rest_framework import generics
from djangopasswordlessknox.settings import api_settings
from knox.models import AuthTokenManager, AuthToken
from djangopasswordlessknox.serializers import (
EmailAuthSerializer,
MobileAuthSerializer,
CallbackTokenAuthSerializer,
CallbackTokenVerificationSerializer,
EmailVerificationSerializer,
MobileVerificationSerializer,
)
from djangopasswordlessknox.services import TokenService
from djangopasswordlessknox.services import TokenService
from knox.settings import knox_settings
from rest_framework.serializers import DateTimeField
from django.utils import timezone
from django.contrib.auth.signals import user_logged_in, user_logged_out
logger = logging.getLogger(__name__)
class AbstractBaseObtainCallbackToken(APIView):
"""
This returns a 6-digit callback token we can trade for a user's Auth Token.
"""
success_response = "A login token has been sent to you."
failure_response = "Unable to send you a login code. Try again later."
message_payload = {}
@property
def serializer_class(self):
# Our serializer depending on type
raise NotImplementedError
@property
def alias_type(self):
# Alias Type
raise NotImplementedError
def post(self, request, *args, **kwargs):
if self.alias_type.upper() not in api_settings.PASSWORDLESS_AUTH_TYPES:
# Only allow auth types allowed in settings.
return Response(status=status.HTTP_404_NOT_FOUND)
serializer = self.serializer_class(data=request.data, context={'request': request})
if serializer.is_valid(raise_exception=True):
# Validate -
user = serializer.validated_data['user']
# Create and send callback token
success = TokenService.send_token(user, self.alias_type, **self.message_payload)
# Respond With Success Or Failure of Sent
if success:
status_code = status.HTTP_200_OK
response_detail = self.success_response
else:
status_code = status.HTTP_400_BAD_REQUEST
response_detail = self.failure_response
return Response({'detail': response_detail}, status=status_code)
else:
return Response(serializer.error_messages, status=status.HTTP_400_BAD_REQUEST)
class ObtainEmailCallbackToken(AbstractBaseObtainCallbackToken, generics.GenericAPIView):
permission_classes = (AllowAny,)
serializer_class = EmailAuthSerializer
success_response = "A login token has been sent to your email."
failure_response = "Unable to email you a login code. Try again later."
alias_type = 'email'
email_subject = api_settings.PASSWORDLESS_EMAIL_SUBJECT
email_plaintext = api_settings.PASSWORDLESS_EMAIL_PLAINTEXT_MESSAGE
email_html = api_settings.PASSWORDLESS_EMAIL_TOKEN_HTML_TEMPLATE_NAME
message_payload = {'email_subject': email_subject,
'email_plaintext': email_plaintext,
'email_html': email_html}
class ObtainMobileCallbackToken(AbstractBaseObtainCallbackToken, generics.GenericAPIView):
permission_classes = (AllowAny,)
serializer_class = MobileAuthSerializer
success_response = "We texted you a login code."
failure_response = "Unable to send you a login code. Try again later."
alias_type = 'mobile'
mobile_message = api_settings.PASSWORDLESS_MOBILE_MESSAGE
message_payload = {'mobile_message': mobile_message}
class ObtainEmailVerificationCallbackToken(AbstractBaseObtainCallbackToken, generics.GenericAPIView):
permission_classes = (IsAuthenticated,)
serializer_class = EmailVerificationSerializer
success_response = "A verification token has been sent to your email."
failure_response = "Unable to email you a verification code. Try again later."
alias_type = 'email'
email_subject = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_SUBJECT
email_plaintext = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_PLAINTEXT_MESSAGE
email_html = api_settings.PASSWORDLESS_EMAIL_VERIFICATION_TOKEN_HTML_TEMPLATE_NAME
message_payload = {
'email_subject': email_subject,
'email_plaintext': email_plaintext,
'email_html': email_html
}
class ObtainMobileVerificationCallbackToken(AbstractBaseObtainCallbackToken, generics.GenericAPIView):
permission_classes = (IsAuthenticated,)
serializer_class = MobileVerificationSerializer
success_response = "We texted you a verification code."
failure_response = "Unable to send you a verification code. Try again later."
alias_type = 'mobile'
mobile_message = api_settings.PASSWORDLESS_MOBILE_MESSAGE
message_payload = {'mobile_message': mobile_message}
class AbstractBaseObtainAuthToken(APIView):
"""
This is a duplicate of rest_framework's own ObtainAuthToken method.
Instead, this returns an Auth Token based on our 6 digit callback token and source.
"""
serializer_class = None
def get_context(self):
return {'request': self.request, 'format': self.format_kwarg, 'view': self}
def get_token_ttl(self):
return knox_settings.TOKEN_TTL
def get_token_limit_per_user(self):
return knox_settings.TOKEN_LIMIT_PER_USER
def get_user_serializer_class(self):
return knox_settings.USER_SERIALIZER
def get_expiry_datetime_format(self):
return knox_settings.EXPIRY_DATETIME_FORMAT
def format_expiry_datetime(self, expiry):
datetime_format = self.get_expiry_datetime_format()
return DateTimeField(format=datetime_format).to_representation(expiry)
def get_post_response_data(self, user, token, instance):
UserSerializer = self.get_user_serializer_class()
data = {
'expiry': self.format_expiry_datetime(instance.expiry),
'token': token
}
if UserSerializer is not None:
data["user"] = UserSerializer(
user,
context=self.get_context()
).data
return data
def post(self, request, format=None):
token_limit_per_user = self.get_token_limit_per_user()
serializer = self.serializer_class(data=request.data)
if serializer.is_valid(raise_exception=True):
user = serializer.validated_data['user']
if token_limit_per_user is not None:
now = timezone.now()
token = user.auth_token_set.filter(expiry__gt=now)
if token.count() >= token_limit_per_user:
return Response(
{"error": "Maximum amount of tokens allowed per user exceeded."},
status=status.HTTP_403_FORBIDDEN
)
token_ttl = self.get_token_ttl()
instance, token = AuthToken.objects.create(user, token_ttl)
user_logged_in.send(sender=user.__class__,
request=request, user=user)
data = self.get_post_response_data(user, token, instance)
return Response(data)
class ObtainAuthTokenFromCallbackToken(AbstractBaseObtainAuthToken, generics.GenericAPIView):
"""
This is a duplicate of rest_framework's own ObtainAuthToken method.
Instead, this returns an Auth Token based on our callback token and source.
"""
permission_classes = (AllowAny,)
serializer_class = CallbackTokenAuthSerializer
class VerifyAliasFromCallbackToken(APIView):
"""
This verifies an alias on correct callback token entry using the same logic as auth.
Should be refactored at some point.
"""
serializer_class = CallbackTokenVerificationSerializer
def post(self, request, *args, **kwargs):
serializer = self.serializer_class(data=request.data, context={'user_id': self.request.user.id})
if serializer.is_valid(raise_exception=True):
return Response({'detail': 'Alias verified.'}, status=status.HTTP_200_OK)
else:
logger.error("Couldn't verify unknown user. Errors on serializer: {}".format(serializer.error_messages))
return Response({'detail': 'We couldn\'t verify this alias. Try again later.'}, status.HTTP_400_BAD_REQUEST)

38
docker-compose.prod.yml Normal file
View File

@ -0,0 +1,38 @@
services:
api:
build:
context: .
dockerfile: Dockerfile.prod
restart: always
command: gunicorn apibase.wsgi:application --bind 0.0.0.0:5000 --workers=2
volumes:
- /home/<username>/docker/council-api/staticfiles:/home/app/api/staticfiles
ports:
- 5000:5000
env_file:
- ./.env
depends_on:
- db
- redis
db:
image: postgres:15
restart: always
volumes:
- ./postgres_data:/var/lib/postgresql/data/
env_file:
- ./.env
environment:
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- POSTGRES_DB=${POSTGRES_DATABASE}
ports:
- 5232:5432
redis:
image: "redis:alpine"
restart: always
expose:
- "6379"

30
docker-compose.yml Normal file
View File

@ -0,0 +1,30 @@
services:
api:
build: .
command: python manage.py runserver 0.0.0.0:8000
volumes:
- ./:/usr/src/app/
ports:
- 8000:8000
env_file:
- ./.env
depends_on:
- db
- redis
db:
image: postgres:15
volumes:
- postgres_data:/var/lib/postgresql/data/
environment:
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASSWORD}
- POSTGRES_DB=${POSTGRES_DATABASE}
redis:
image: "redis:alpine"
restart: always
expose:
- "6379"
volumes:
postgres_data:

14
entrypoint.prod.sh Executable file
View File

@ -0,0 +1,14 @@
#!/bin/sh
if [ "$DATABASE" = "postgres" ]
then
echo "Waiting for postgres..."
while ! nc -z $POSTGRES_HOST $POSTGRES_PORT; do
sleep 0.1
done
echo "PostgreSQL started"
fi
exec "$@"

14
entrypoint.sh Normal file
View File

@ -0,0 +1,14 @@
#!/bin/sh
if [ "$DATABASE" = "postgres" ]
then
echo "Waiting for postgres..."
while ! nc -z $POSTGRES_HOST $POSTGRES_PORT; do
sleep 0.1
done
echo "PostgreSQL started"
fi
exec "$@"

23
manage.py Normal file
View File

@ -0,0 +1,23 @@
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "apibase.settings")
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == "__main__":
main()

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

13
pyrightconfig.json Normal file
View File

@ -0,0 +1,13 @@
{
"venvPath": ".",
"venv": ".venv",
"reportMissingImports": "error",
"include": ["src"],
"exclude": [
"council-api/**/migrations",
"**/__pycache__",
"src/experimental",
"src/typestubs"
]
}

99
requirements.txt Normal file
View File

@ -0,0 +1,99 @@
aiohappyeyeballs==2.4.3
aiohttp==3.11.2
aiohttp-retry==2.8.3
aiosignal==1.3.1
arabic-reshaper==3.0.0
asgiref==3.8.1
asn1crypto==1.5.1
async-timeout==4.0.3
attrs==24.2.0
black==23.12.1
boto3==1.35.49
botocore==1.35.49
certifi==2024.2.2
cffi==1.16.0
chardet==5.2.0
charset-normalizer==3.3.2
click==8.1.7
colorama==0.4.6
cryptography==41.0.7
cssselect2==0.7.0
dj-database-url==2.1.0
django==5.1.2
django-cors-headers==4.3.1
django-debug-toolbar==4.2.0
django-easy-audit==1.3.7
django-extensions==3.2.3
django-filter==23.5
django-redis==5.4.0
django-rest-knox==4.2.0
django-rest-passwordreset==1.5.0
django-seed==0.3.1
django-storages==1.14.4
django-stubs==5.1.1
django-stubs-ext==5.1.1
djangorestframework==3.14.0
djangorestframework-simplejwt==5.3.1
djangorestframework-stubs==3.15.1
dnspython==2.4.2
drf-spectacular==0.27.2
faker==30.8.0
frozenlist==1.5.0
gunicorn==23.0.0
html5lib==1.1
idna==3.6
inflection==0.5.1
jmespath==1.0.1
jsonschema==4.23.0
jsonschema-specifications==2024.10.1
lxml==5.1.0
multidict==6.1.0
mypy-extensions==1.0.0
oscrypto==1.3.0
packaging==23.2
pathspec==0.12.1
pillow==10.2.0
platformdirs==4.1.0
propcache==0.2.0
psycopg==3.2.3
psycopg-binary==3.2.3
psycopg-pool==3.2.4
psycopg2-binary==2.9.9
pycparser==2.21
pyhanko==0.21.0
pyhanko-certvalidator==0.26.3
pyjwt==2.8.0
pymongo==4.6.1
pypdf==4.0.2
pypng==0.20220715.0
python-bidi==0.4.2
python-dateutil==2.9.0.post0
python-decouple==3.8
pytz==2023.3.post1
pyyaml==6.0.1
qrcode==7.4.2
redis==5.0.1
referencing==0.35.1
reportlab==4.0.9
requests==2.31.0
rpds-py==0.21.0
ruff==0.7.0
s3transfer==0.10.3
six==1.16.0
sqlparse==0.5.1
svglib==1.5.1
tinycss2==1.2.1
tomli==2.0.2
toposort==1.10
twilio==9.3.7
types-pyyaml==6.0.12.20240917
types-requests==2.32.0.20241016
typing-extensions==4.12.2
tzdata==2023.4
tzlocal==5.2
uritemplate==4.1.1
uritools==4.0.2
urllib3==2.2.1
webencodings==0.5.1
whitenoise==6.7.0
yarl==1.17.2