add-frames #1
89 changed files with 26502 additions and 0 deletions
10
backend/.gitignore
vendored
Normal file
10
backend/.gitignore
vendored
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
.venv
|
||||||
|
.idea
|
||||||
|
.vscode
|
||||||
|
__pycache__
|
||||||
|
*.pyc
|
||||||
|
.DS_Store
|
||||||
|
*.swp
|
||||||
|
.envrc
|
||||||
|
.direnv
|
||||||
|
run_app.local.sh
|
10
backend/.pylintrc
Normal file
10
backend/.pylintrc
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
[MAIN]
|
||||||
|
|
||||||
|
# List of plugins (as comma separated values of python module names) to load,
|
||||||
|
# usually to register additional checkers.
|
||||||
|
load-plugins=pylint_flask,pylint_flask_sqlalchemy
|
||||||
|
|
||||||
|
# List of class names for which member attributes should not be checked (useful
|
||||||
|
# for classes with dynamically set attributes). This supports the use of
|
||||||
|
# qualified names.
|
||||||
|
ignored-classes=optparse.Values,thread._local,_thread._local,argparse.Namespace,scoped_session
|
25
backend/Dockerfile
Normal file
25
backend/Dockerfile
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
FROM python:3.10-slim
|
||||||
|
|
||||||
|
RUN apt-get update
|
||||||
|
RUN apt-get install -y gcc
|
||||||
|
|
||||||
|
## make a local directory
|
||||||
|
RUN mkdir /app
|
||||||
|
|
||||||
|
# set "app" as the working directory from which CMD, RUN, ADD references
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# copy requirements.txt to /app
|
||||||
|
ADD requirements.txt .
|
||||||
|
|
||||||
|
# pip install the local requirements.txt
|
||||||
|
RUN pip install -r requirements.txt
|
||||||
|
|
||||||
|
# now copy all the files in this directory to /code
|
||||||
|
ADD . .
|
||||||
|
|
||||||
|
# Listen to port 80 at runtime
|
||||||
|
EXPOSE 5000
|
||||||
|
|
||||||
|
# Define our command to be run when launching the container
|
||||||
|
CMD ["gunicorn", "app:app", "-b", "0.0.0.0:5000", "--workers", "4", "--reload", "--capture-output", "--enable-stdio-inheritance", "--log-level", "DEBUG"]
|
661
backend/LICENSE
Normal file
661
backend/LICENSE
Normal file
|
@ -0,0 +1,661 @@
|
||||||
|
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 19 November 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU Affero General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works, specifically designed to ensure
|
||||||
|
cooperation with the community in the case of network server software.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
our General Public Licenses are 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.
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
Developers that use our General Public Licenses protect your rights
|
||||||
|
with two steps: (1) assert copyright on the software, and (2) offer
|
||||||
|
you this License which gives you legal permission to copy, distribute
|
||||||
|
and/or modify the software.
|
||||||
|
|
||||||
|
A secondary benefit of defending all users' freedom is that
|
||||||
|
improvements made in alternate versions of the program, if they
|
||||||
|
receive widespread use, become available for other developers to
|
||||||
|
incorporate. Many developers of free software are heartened and
|
||||||
|
encouraged by the resulting cooperation. However, in the case of
|
||||||
|
software used on network servers, this result may fail to come about.
|
||||||
|
The GNU General Public License permits making a modified version and
|
||||||
|
letting the public access it on a server without ever releasing its
|
||||||
|
source code to the public.
|
||||||
|
|
||||||
|
The GNU Affero General Public License is designed specifically to
|
||||||
|
ensure that, in such cases, the modified source code becomes available
|
||||||
|
to the community. It requires the operator of a network server to
|
||||||
|
provide the source code of the modified version running there to the
|
||||||
|
users of that server. Therefore, public use of a modified version, on
|
||||||
|
a publicly accessible server, gives the public access to the source
|
||||||
|
code of the modified version.
|
||||||
|
|
||||||
|
An older license, called the Affero General Public License and
|
||||||
|
published by Affero, was designed to accomplish similar goals. This is
|
||||||
|
a different license, not a version of the Affero GPL, but Affero has
|
||||||
|
released a new version of the Affero GPL which permits relicensing under
|
||||||
|
this license.
|
||||||
|
|
||||||
|
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, if you modify the
|
||||||
|
Program, your modified version must prominently offer all users
|
||||||
|
interacting with it remotely through a computer network (if your version
|
||||||
|
supports such interaction) an opportunity to receive the Corresponding
|
||||||
|
Source of your version by providing access to the Corresponding Source
|
||||||
|
from a network server at no charge, through some standard or customary
|
||||||
|
means of facilitating copying of software. This Corresponding Source
|
||||||
|
shall include the Corresponding Source for any work covered by version 3
|
||||||
|
of the GNU General Public License that is incorporated pursuant to the
|
||||||
|
following paragraph.
|
||||||
|
|
||||||
|
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 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 work with which it is combined will remain governed by version
|
||||||
|
3 of the GNU General Public License.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU Affero 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 Affero 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 Affero 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 Affero 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.
|
||||||
|
|
||||||
|
bootstrap
|
||||||
|
Copyright (C) 2019 Stackspin
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU Affero 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 Affero General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU Affero General Public License
|
||||||
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If your software can interact with users remotely through a computer
|
||||||
|
network, you should also make sure that it provides a way for users to
|
||||||
|
get its source. For example, if your program is a web application, its
|
||||||
|
interface could display a "Source" link that leads users to an archive
|
||||||
|
of the code. There are many ways you could offer source, and different
|
||||||
|
solutions will be better for different programs; see section 13 for the
|
||||||
|
specific requirements.
|
||||||
|
|
||||||
|
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 AGPL, see
|
||||||
|
<http://www.gnu.org/licenses/>.
|
104
backend/README.md
Normal file
104
backend/README.md
Normal file
|
@ -0,0 +1,104 @@
|
||||||
|
# Stackspin dashboard backend
|
||||||
|
|
||||||
|
Backend for the [Stackspin dashboard](https://open.greenhost.net/stackspin/dashboard)
|
||||||
|
|
||||||
|
## Login application
|
||||||
|
|
||||||
|
Apart from the dashboard backend this repository contains a flask application
|
||||||
|
that functions as the identity provider, login, consent and logout endpoints
|
||||||
|
for the OpenID Connect (OIDC) process.
|
||||||
|
The application relies on the following components:
|
||||||
|
|
||||||
|
- **Hydra**: Hydra is an open source OIDC server.
|
||||||
|
It means applications can connect to Hydra to start a session with a user.
|
||||||
|
Hydra provides the application with the username
|
||||||
|
and other roles/claims for the application.
|
||||||
|
Hydra is developed by Ory and has security as one of their top priorities.
|
||||||
|
|
||||||
|
- **Kratos**: This is Identity Manager
|
||||||
|
and contains all the user profiles and secrets (passwords).
|
||||||
|
Kratos is designed to work mostly between UI (browser) and kratos directly,
|
||||||
|
over a public API endpoint.
|
||||||
|
Authentication, form-validation, etc. are all handled by Kratos.
|
||||||
|
Kratos only provides an API and not UI itself.
|
||||||
|
Kratos provides an admin API as well,
|
||||||
|
which is only used from the server-side flask app to create/delete users.
|
||||||
|
|
||||||
|
- **MariaDB**: The login application, as well as Hydra and Kratos, need to store data.
|
||||||
|
This is done in a MariaDB database server.
|
||||||
|
There is one instance with three databases.
|
||||||
|
As all databases are very small we do not foresee resource limitation problems.
|
||||||
|
|
||||||
|
If Hydra hits a new session/user, it has to know if this user has access.
|
||||||
|
To do so, the user has to login through a login application.
|
||||||
|
This application is developed by the Stackspin team (Greenhost)
|
||||||
|
and is part of this repository.
|
||||||
|
It is a Python Flask application
|
||||||
|
The application follows flows defined in Kratos,
|
||||||
|
and as such a lot of the interaction is done in the web-browser,
|
||||||
|
rather then server-side.
|
||||||
|
As a result,
|
||||||
|
the login application has a UI component which relies heavily on JavaScript.
|
||||||
|
As this is a relatively small application,
|
||||||
|
it is based on traditional Bootstrap + JQuery.
|
||||||
|
|
||||||
|
# Development
|
||||||
|
|
||||||
|
To develop the Dashboard,
|
||||||
|
you need a Stackspin cluster that is set up as a development environment.
|
||||||
|
Follow the instructions [in the dashboard-dev-overrides
|
||||||
|
repository](https://open.greenhost.net/stackspin/dashboard-dev-overrides#dashboard-dev-overrides)
|
||||||
|
in order to set up a development-capable cluster.
|
||||||
|
The end-points for the Dashboard,
|
||||||
|
as well as Kratos and Hydra, will point to `http://stackspin_proxy:8081` in that cluster.
|
||||||
|
As a result, you can run components using the `docker-compose` file in
|
||||||
|
this repository, and still log into Stackspin applications that run on the cluster.
|
||||||
|
|
||||||
|
|
||||||
|
## Setting up the local development environment
|
||||||
|
|
||||||
|
After this process is finished, the following will run locally:
|
||||||
|
|
||||||
|
- The [dashboard](https://open.greenhost.net/stackspin/dashboard)
|
||||||
|
- The
|
||||||
|
[dashboard-backend](https://open.greenhost.net/stackspin/dashboard-backend)
|
||||||
|
|
||||||
|
The following will be available locally through a proxy and port-forwards:
|
||||||
|
|
||||||
|
- Hydra admin
|
||||||
|
- Kratos admin and public
|
||||||
|
- The MariaDB database connections
|
||||||
|
|
||||||
|
These need to be available locally, because Kratos wants to run on the same
|
||||||
|
domain as the front-end that serves the login interface.
|
||||||
|
|
||||||
|
|
||||||
|
### 1. Setup hosts file
|
||||||
|
|
||||||
|
The application will run on `http://stackspin_proxy`. Add the following line to
|
||||||
|
`/etc/hosts` to be able to access that from your browser:
|
||||||
|
|
||||||
|
```
|
||||||
|
127.0.0.1 stackspin_proxy
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. Kubernetes access
|
||||||
|
|
||||||
|
The script needs you to have access to the Kubernetes cluster that runs
|
||||||
|
Stackspin. Point the `KUBECONFIG` environment variable to a kubectl config. That
|
||||||
|
kubeconfig will be mounted inside docker containers, so also make sure your
|
||||||
|
Docker user can read it.
|
||||||
|
|
||||||
|
### 3. Run it all
|
||||||
|
|
||||||
|
Now, run this script that sets a few environment variables based on what is in
|
||||||
|
your cluster secrets, and starts `docker-compose` to start a reverse proxy as
|
||||||
|
well as the flask application in this repository.
|
||||||
|
|
||||||
|
```
|
||||||
|
./run_app.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Front-end developmenet
|
||||||
|
|
||||||
|
Start the [dashboard front-end app](https://open.greenhost.net/stackspin/dashboard/#yarn-start).
|
75
backend/app.py
Normal file
75
backend/app.py
Normal file
|
@ -0,0 +1,75 @@
|
||||||
|
from flask import Flask, jsonify
|
||||||
|
from flask_cors import CORS
|
||||||
|
from flask_jwt_extended import JWTManager
|
||||||
|
from flask_migrate import Migrate
|
||||||
|
from jsonschema.exceptions import ValidationError
|
||||||
|
from werkzeug.exceptions import BadRequest
|
||||||
|
|
||||||
|
# These imports are required
|
||||||
|
from areas import api_v1
|
||||||
|
from cliapp import cli
|
||||||
|
from web import web
|
||||||
|
|
||||||
|
from areas import users
|
||||||
|
from areas import apps
|
||||||
|
from areas import auth
|
||||||
|
from areas import roles
|
||||||
|
from cliapp import cliapp
|
||||||
|
from web import login
|
||||||
|
|
||||||
|
from database import db
|
||||||
|
|
||||||
|
from helpers import (
|
||||||
|
BadRequest,
|
||||||
|
KratosError,
|
||||||
|
HydraError,
|
||||||
|
Unauthorized,
|
||||||
|
bad_request_error,
|
||||||
|
validation_error,
|
||||||
|
kratos_error,
|
||||||
|
global_error,
|
||||||
|
hydra_error,
|
||||||
|
unauthorized_error,
|
||||||
|
)
|
||||||
|
|
||||||
|
from config import *
|
||||||
|
import logging
|
||||||
|
|
||||||
|
app = Flask(__name__)
|
||||||
|
|
||||||
|
app.config["SECRET_KEY"] = SECRET_KEY
|
||||||
|
app.config["SQLALCHEMY_DATABASE_URI"] = SQLALCHEMY_DATABASE_URI
|
||||||
|
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = SQLALCHEMY_TRACK_MODIFICATIONS
|
||||||
|
|
||||||
|
cors = CORS(app)
|
||||||
|
Migrate(app, db)
|
||||||
|
db.init_app(app)
|
||||||
|
|
||||||
|
|
||||||
|
app.logger.setLevel(logging.INFO)
|
||||||
|
|
||||||
|
app.register_blueprint(api_v1)
|
||||||
|
app.register_blueprint(web)
|
||||||
|
app.register_blueprint(cli)
|
||||||
|
|
||||||
|
# Error handlers
|
||||||
|
app.register_error_handler(Exception, global_error)
|
||||||
|
app.register_error_handler(BadRequest, bad_request_error)
|
||||||
|
app.register_error_handler(ValidationError, validation_error)
|
||||||
|
app.register_error_handler(KratosError, kratos_error)
|
||||||
|
app.register_error_handler(HydraError, hydra_error)
|
||||||
|
app.register_error_handler(Unauthorized, unauthorized_error)
|
||||||
|
|
||||||
|
jwt = JWTManager(app)
|
||||||
|
|
||||||
|
# When token is not valid or missing handler
|
||||||
|
@jwt.invalid_token_loader
|
||||||
|
@jwt.unauthorized_loader
|
||||||
|
@jwt.expired_token_loader
|
||||||
|
def expired_token_callback(*args):
|
||||||
|
return jsonify({"errorMessage": "Unauthorized"}), 401
|
||||||
|
|
||||||
|
|
||||||
|
@app.route("/")
|
||||||
|
def index():
|
||||||
|
return "Stackspin API v1.0"
|
9
backend/areas/__init__.py
Normal file
9
backend/areas/__init__.py
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
from flask import Blueprint
|
||||||
|
|
||||||
|
api_v1 = Blueprint("api_v1", __name__, url_prefix="/api/v1")
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route("/")
|
||||||
|
@api_v1.route("/health")
|
||||||
|
def api_index():
|
||||||
|
return "Stackspin API v1.0"
|
3
backend/areas/apps/__init__.py
Normal file
3
backend/areas/apps/__init__.py
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
from .apps import *
|
||||||
|
from .apps_service import *
|
||||||
|
from .models import *
|
67
backend/areas/apps/apps.py
Normal file
67
backend/areas/apps/apps.py
Normal file
|
@ -0,0 +1,67 @@
|
||||||
|
from flask import jsonify
|
||||||
|
from flask_jwt_extended import jwt_required
|
||||||
|
from flask_cors import cross_origin
|
||||||
|
|
||||||
|
from areas import api_v1
|
||||||
|
from .apps_service import AppsService
|
||||||
|
|
||||||
|
|
||||||
|
CONFIG_DATA = [
|
||||||
|
{
|
||||||
|
"id": "values.yml",
|
||||||
|
"description": "Some user friendly description",
|
||||||
|
"raw": "cronjob:\n # Set curl to accept insecure connections when acme staging is used\n curlInsecure: false",
|
||||||
|
"fields": [
|
||||||
|
{"name": "cronjob", "type": "string", "value": ""},
|
||||||
|
{"name": "curlInsecure", "type": "boolean", "value": "false"}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
@api_v1.route('/apps', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
def get_apps():
|
||||||
|
"""Return data about all apps"""
|
||||||
|
apps = AppsService.get_all_apps()
|
||||||
|
return jsonify(apps)
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route('/apps/<string:slug>', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
def get_app(slug):
|
||||||
|
"""Return data about a single app"""
|
||||||
|
app = AppsService.get_app(slug)
|
||||||
|
return jsonify(app)
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route('/apps', methods=['POST'])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
def post_app():
|
||||||
|
"""Unused function, returns bogus data for now"""
|
||||||
|
return jsonify([]), 201
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route('/apps/<string:slug>', methods=['PUT'])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
def put_app(slug):
|
||||||
|
"""Unused function, returns bogus data for now"""
|
||||||
|
return jsonify([])
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route('/apps/<string:slug>/config', methods=['GET'])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
def get_config(slug):
|
||||||
|
"""Returns bogus config data"""
|
||||||
|
return jsonify(CONFIG_DATA)
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route('/apps/<string:slug>/config', methods=['DELETE'])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
def delete_config(slug):
|
||||||
|
"""Does nothing, then returns bogus config data"""
|
||||||
|
return jsonify(CONFIG_DATA)
|
17
backend/areas/apps/apps_service.py
Normal file
17
backend/areas/apps/apps_service.py
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
from .models import App, AppRole
|
||||||
|
|
||||||
|
class AppsService:
|
||||||
|
@staticmethod
|
||||||
|
def get_all_apps():
|
||||||
|
apps = App.query.all()
|
||||||
|
return [app.to_dict() for app in apps]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_app(slug):
|
||||||
|
app = App.query.filter_by(slug=slug).first()
|
||||||
|
return app.to_dict()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_app_roles():
|
||||||
|
app_roles = AppRole.query.all()
|
||||||
|
return [{"user_id": app_role.user_id, "app_id": app_role.app_id, "role_id": app_role.role_id} for app_role in app_roles]
|
298
backend/areas/apps/models.py
Normal file
298
backend/areas/apps/models.py
Normal file
|
@ -0,0 +1,298 @@
|
||||||
|
"""Everything to do with Apps"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import base64
|
||||||
|
|
||||||
|
from sqlalchemy import ForeignKey, Integer, String, Boolean
|
||||||
|
from sqlalchemy.orm import relationship
|
||||||
|
|
||||||
|
from database import db
|
||||||
|
import helpers.kubernetes as k8s
|
||||||
|
|
||||||
|
|
||||||
|
DEFAULT_APP_SUBDOMAINS = {
|
||||||
|
"nextcloud": "files",
|
||||||
|
"wordpress": "www",
|
||||||
|
"monitoring": "grafana",
|
||||||
|
}
|
||||||
|
|
||||||
|
class App(db.Model):
|
||||||
|
"""
|
||||||
|
The App object, interact with the App database object. Data is stored in
|
||||||
|
the local database.
|
||||||
|
"""
|
||||||
|
|
||||||
|
id = db.Column(Integer, primary_key=True)
|
||||||
|
name = db.Column(String(length=64))
|
||||||
|
slug = db.Column(String(length=64), unique=True)
|
||||||
|
external = db.Column(Boolean, unique=False, nullable=False, server_default='0')
|
||||||
|
# The URL is only stored in the DB for external applications; otherwise the
|
||||||
|
# URL is stored in a configmap (see get_url)
|
||||||
|
url = db.Column(String(length=128), unique=False)
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"{self.id} <{self.name}>"
|
||||||
|
|
||||||
|
def get_url(self):
|
||||||
|
"""
|
||||||
|
Returns the URL where this application is running
|
||||||
|
|
||||||
|
For external applications: the URL is stored in the database
|
||||||
|
|
||||||
|
For internal applications: the URL is stored in a configmap named
|
||||||
|
`stackspin-{self.slug}-kustomization-variables under
|
||||||
|
`{self.slug_domain}`. This function reads that configmap. If the
|
||||||
|
configmap does not contain a URL for the application (which is
|
||||||
|
possible, if the app is not installed yet, for example), we return a
|
||||||
|
default URL.
|
||||||
|
"""
|
||||||
|
|
||||||
|
if self.external:
|
||||||
|
return self.url
|
||||||
|
|
||||||
|
# Get domain name from configmap
|
||||||
|
ks_config_map = k8s.get_kubernetes_config_map_data(
|
||||||
|
f"stackspin-{self.slug}-kustomization-variables",
|
||||||
|
"flux-system")
|
||||||
|
domain_key = f"{self.slug}_domain"
|
||||||
|
|
||||||
|
# If config map found with this domain name for this service, return
|
||||||
|
# that URL
|
||||||
|
if ks_config_map and domain_key in ks_config_map.keys():
|
||||||
|
return f"https://{ks_config_map[domain_key]}"
|
||||||
|
|
||||||
|
domain_secret = k8s.get_kubernetes_secret_data(
|
||||||
|
"stackspin-cluster-variables",
|
||||||
|
"flux-system")
|
||||||
|
domain = base64.b64decode(domain_secret['domain']).decode()
|
||||||
|
|
||||||
|
# See if there is another default subdomain for this app than just
|
||||||
|
# "slug.{domain}"
|
||||||
|
if self.slug in DEFAULT_APP_SUBDOMAINS:
|
||||||
|
return f"https://{DEFAULT_APP_SUBDOMAINS[self.slug]}.{domain}"
|
||||||
|
|
||||||
|
# No default known
|
||||||
|
return f"https://{self.slug}.{domain}"
|
||||||
|
|
||||||
|
def get_status(self):
|
||||||
|
"""Returns an AppStatus object that describes the current cluster state"""
|
||||||
|
return AppStatus(self)
|
||||||
|
|
||||||
|
def install(self):
|
||||||
|
"""Creates a Kustomization in the Kubernetes cluster that installs this application"""
|
||||||
|
# Generate the necessary passwords, etc. from a template
|
||||||
|
self.__generate_secrets()
|
||||||
|
# Create add-<app> kustomization
|
||||||
|
self.__create_kustomization()
|
||||||
|
|
||||||
|
def uninstall(self):
|
||||||
|
"""
|
||||||
|
Delete the app kustomization.
|
||||||
|
|
||||||
|
In our case, this triggers a deletion of the app's PVCs (so deletes all
|
||||||
|
data), as well as any other Kustomizations and HelmReleases related to
|
||||||
|
the app. It also triggers a deletion of the OAuth2Client object, but
|
||||||
|
does not delete the secrets generated by the `install` command. It also
|
||||||
|
does not remove the TLS secret generated by cert-manager.
|
||||||
|
"""
|
||||||
|
self.__delete_kustomization()
|
||||||
|
|
||||||
|
def delete(self):
|
||||||
|
"""
|
||||||
|
Fully deletes an application
|
||||||
|
|
||||||
|
This includes user roles, all kubernetes objects and also PVCs, so your
|
||||||
|
data will be *gone*
|
||||||
|
"""
|
||||||
|
# Delete all roles first
|
||||||
|
for role in self.roles:
|
||||||
|
db.session.delete(role)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
db.session.delete(self)
|
||||||
|
return db.session.commit()
|
||||||
|
|
||||||
|
def __generate_secrets(self):
|
||||||
|
"""Generates passwords for app installation"""
|
||||||
|
# Create app variables secret
|
||||||
|
if self.variables_template_filepath:
|
||||||
|
k8s.create_variables_secret(self.slug, self.variables_template_filepath)
|
||||||
|
|
||||||
|
k8s.create_variables_secret(
|
||||||
|
self.slug,
|
||||||
|
os.path.join(
|
||||||
|
self.__get_templates_dir(),
|
||||||
|
"stackspin-oauth-variables.yaml.jinja"
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def __create_kustomization(self):
|
||||||
|
"""Creates the `add-{app_slug}` kustomization in the Kubernetes cluster"""
|
||||||
|
kustomization_template_filepath = \
|
||||||
|
os.path.join(self.__get_templates_dir(),
|
||||||
|
"add-app-kustomization.yaml.jinja")
|
||||||
|
k8s.store_kustomization(kustomization_template_filepath, self.slug)
|
||||||
|
|
||||||
|
def __delete_kustomization(self):
|
||||||
|
"""Deletes kustomization for this app"""
|
||||||
|
k8s.delete_kustomization(f"add-{self.slug}")
|
||||||
|
|
||||||
|
|
||||||
|
@property
|
||||||
|
def variables_template_filepath(self):
|
||||||
|
"""Path to the variables template used to generate secrets the app needs"""
|
||||||
|
variables_template_filepath = os.path.join(self.__get_templates_dir(),
|
||||||
|
f"stackspin-{self.slug}-variables.yaml.jinja")
|
||||||
|
if os.path.exists(variables_template_filepath):
|
||||||
|
return variables_template_filepath
|
||||||
|
return None
|
||||||
|
|
||||||
|
@property
|
||||||
|
def namespace(self):
|
||||||
|
"""
|
||||||
|
Returns the Kubernetes namespace of this app
|
||||||
|
|
||||||
|
FIXME: This should probably become a database field.
|
||||||
|
"""
|
||||||
|
if self.slug in ['nextcloud', 'wordpress', 'wekan', 'zulip']:
|
||||||
|
return 'stackspin-apps'
|
||||||
|
return 'stackspin'
|
||||||
|
|
||||||
|
@property
|
||||||
|
def roles(self):
|
||||||
|
"""
|
||||||
|
All roles that are linked to this app
|
||||||
|
"""
|
||||||
|
return AppRole.query.filter_by(
|
||||||
|
app_id=self.id
|
||||||
|
).all()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def kustomization(self):
|
||||||
|
"""Returns the kustomization object for this app"""
|
||||||
|
return k8s.get_kustomization(self.slug)
|
||||||
|
|
||||||
|
def to_dict(self):
|
||||||
|
"""
|
||||||
|
represent this object as a dict, compatible for JSON output
|
||||||
|
"""
|
||||||
|
|
||||||
|
return {"id": self.id,
|
||||||
|
"name": self.name,
|
||||||
|
"slug": self.slug,
|
||||||
|
"external": self.external,
|
||||||
|
"status": self.get_status().to_dict(),
|
||||||
|
"url": self.get_url()}
|
||||||
|
|
||||||
|
@property
|
||||||
|
def helmreleases(self):
|
||||||
|
"""Returns the helmreleases associated with the kustomization for this app"""
|
||||||
|
return k8s.get_all_helmreleases(self.namespace,
|
||||||
|
f"kustomize.toolkit.fluxcd.io/name={self.slug}")
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def __get_templates_dir():
|
||||||
|
"""Returns directory that contains the Jinja templates used to create app secrets."""
|
||||||
|
return os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates")
|
||||||
|
|
||||||
|
|
||||||
|
class AppRole(db.Model): # pylint: disable=too-few-public-methods
|
||||||
|
"""
|
||||||
|
The AppRole object, stores the roles Users have on Apps
|
||||||
|
"""
|
||||||
|
|
||||||
|
user_id = db.Column(String(length=64), primary_key=True)
|
||||||
|
app_id = db.Column(Integer, ForeignKey("app.id"), primary_key=True)
|
||||||
|
role_id = db.Column(Integer, ForeignKey("role.id"))
|
||||||
|
|
||||||
|
role = relationship("Role")
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return (f"role_id: {self.role_id}, user_id: {self.user_id},"
|
||||||
|
f" app_id: {self.app_id}, role: {self.role}")
|
||||||
|
|
||||||
|
class AppStatus(): # pylint: disable=too-few-public-methods
|
||||||
|
"""
|
||||||
|
Represents the status of an app in the Kubernetes cluster.
|
||||||
|
|
||||||
|
This class can answer a few questions, like "is the app installed?", but
|
||||||
|
can also return raw status messages from Kustomizations and HelmReleases
|
||||||
|
|
||||||
|
This constructor sets three variables:
|
||||||
|
|
||||||
|
self.installed (bool): Whether the app should be installed
|
||||||
|
self.ready (bool): Whether the app is installed correctly
|
||||||
|
self.message (str): Information about the status
|
||||||
|
|
||||||
|
:param app: An app of which the kustomization and helmreleases
|
||||||
|
property will be used.
|
||||||
|
:type app: App
|
||||||
|
"""
|
||||||
|
def __init__(self, app):
|
||||||
|
if app.external:
|
||||||
|
self.installed = True
|
||||||
|
self.ready = True
|
||||||
|
self.message = "App is external"
|
||||||
|
return
|
||||||
|
|
||||||
|
kustomization = app.kustomization
|
||||||
|
if kustomization is not None and "status" in kustomization:
|
||||||
|
ks_ready, ks_message = AppStatus.check_condition(kustomization['status'])
|
||||||
|
self.installed = True
|
||||||
|
if ks_ready:
|
||||||
|
self.ready = ks_ready
|
||||||
|
self.message = "Installed"
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
ks_ready = None
|
||||||
|
ks_message = "Kustomization does not exist"
|
||||||
|
self.installed = False
|
||||||
|
self.ready = False
|
||||||
|
self.message = "Not installed"
|
||||||
|
return
|
||||||
|
|
||||||
|
helmreleases = app.helmreleases
|
||||||
|
for helmrelease in helmreleases:
|
||||||
|
hr_status = helmrelease['status']
|
||||||
|
hr_ready, hr_message = AppStatus.check_condition(hr_status)
|
||||||
|
|
||||||
|
# For now, only show the message of the first HR that isn't ready
|
||||||
|
if not hr_ready:
|
||||||
|
self.ready = False
|
||||||
|
self.message = f"HelmRelease {helmrelease['metadata']['name']} status: {hr_message}"
|
||||||
|
return
|
||||||
|
|
||||||
|
# If we end up here, all HRs are ready, but the kustomization is not
|
||||||
|
self.ready = ks_ready
|
||||||
|
self.message = f"App Kustomization status: {ks_message}"
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"Installed: {self.installed}\tReady: {self.ready}\tMessage: {self.message}"
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def check_condition(status):
|
||||||
|
"""
|
||||||
|
Returns a tuple that has true/false for readiness and a message
|
||||||
|
|
||||||
|
Ready, in this case means that the condition's type == "Ready" and its
|
||||||
|
status == "True". If the condition type "Ready" does not occur, the
|
||||||
|
status is interpreted as not ready.
|
||||||
|
|
||||||
|
The message that is returned is the message that comes with the
|
||||||
|
condition with type "Ready"
|
||||||
|
|
||||||
|
:param status: Kubernetes resource's "status" object.
|
||||||
|
:type status: dict
|
||||||
|
"""
|
||||||
|
for condition in status["conditions"]:
|
||||||
|
if condition["type"] == "Ready":
|
||||||
|
return condition["status"] == "True", condition["message"]
|
||||||
|
return False, "Condition with type 'Ready' not found"
|
||||||
|
|
||||||
|
def to_dict(self):
|
||||||
|
"""Represents this app status as a dict"""
|
||||||
|
return {
|
||||||
|
"installed": self.installed,
|
||||||
|
"ready": self.ready,
|
||||||
|
"message": self.message,
|
||||||
|
}
|
|
@ -0,0 +1,14 @@
|
||||||
|
---
|
||||||
|
apiVersion: kustomize.toolkit.fluxcd.io/v1beta2
|
||||||
|
kind: Kustomization
|
||||||
|
metadata:
|
||||||
|
name: add-{{ app }}
|
||||||
|
namespace: flux-system
|
||||||
|
spec:
|
||||||
|
interval: 1h0m0s
|
||||||
|
path: ./flux2/cluster/optional/{{ app }}
|
||||||
|
prune: true
|
||||||
|
sourceRef:
|
||||||
|
kind: GitRepository
|
||||||
|
name: stackspin
|
||||||
|
|
|
@ -0,0 +1,13 @@
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: stackspin-nextcloud-variables
|
||||||
|
data:
|
||||||
|
nextcloud_password: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
nextcloud_mariadb_password: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
nextcloud_mariadb_root_password: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
nextcloud_redis_password: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
onlyoffice_database_password: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
onlyoffice_jwt_secret: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
onlyoffice_rabbitmq_password: "{{ 32 | generate_password | b64encode }}"
|
|
@ -0,0 +1,8 @@
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: stackspin-{{ app }}-oauth-variables
|
||||||
|
data:
|
||||||
|
client_id: "{{ app | b64encode }}"
|
||||||
|
client_secret: "{{ 32 | generate_password | b64encode }}"
|
|
@ -0,0 +1,7 @@
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: stackspin-wekan-variables
|
||||||
|
data:
|
||||||
|
mongodb_password: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
mongodb_root_password: "{{ 32 | generate_password | b64encode }}"
|
|
@ -0,0 +1,9 @@
|
||||||
|
---
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: stackspin-wordpress-variables
|
||||||
|
data:
|
||||||
|
wordpress_admin_password: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
wordpress_mariadb_password: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
wordpress_mariadb_root_password: "{{ 32 | generate_password | b64encode }}"
|
|
@ -0,0 +1,12 @@
|
||||||
|
apiVersion: v1
|
||||||
|
kind: Secret
|
||||||
|
metadata:
|
||||||
|
name: stackspin-zulip-variables
|
||||||
|
data:
|
||||||
|
admin_password: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
memcached_password: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
rabbitmq_password: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
rabbitmq_erlang_cookie: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
redis_password: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
postgresql_password: "{{ 32 | generate_password | b64encode }}"
|
||||||
|
zulip_password: "{{ 32 | generate_password | b64encode }}"
|
1
backend/areas/auth/__init__.py
Normal file
1
backend/areas/auth/__init__.py
Normal file
|
@ -0,0 +1 @@
|
||||||
|
from .auth import *
|
67
backend/areas/auth/auth.py
Normal file
67
backend/areas/auth/auth.py
Normal file
|
@ -0,0 +1,67 @@
|
||||||
|
from flask import jsonify, request
|
||||||
|
from flask_jwt_extended import create_access_token
|
||||||
|
from flask_cors import cross_origin
|
||||||
|
from datetime import timedelta
|
||||||
|
|
||||||
|
from areas import api_v1
|
||||||
|
from areas.apps import App, AppRole
|
||||||
|
from config import *
|
||||||
|
from helpers import HydraOauth, BadRequest, KratosApi
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route("/login", methods=["POST"])
|
||||||
|
@cross_origin()
|
||||||
|
def login():
|
||||||
|
authorization_url = HydraOauth.authorize()
|
||||||
|
return jsonify({"authorizationUrl": authorization_url})
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route("/hydra/callback")
|
||||||
|
@cross_origin()
|
||||||
|
def hydra_callback():
|
||||||
|
state = request.args.get("state")
|
||||||
|
code = request.args.get("code")
|
||||||
|
if state == None:
|
||||||
|
raise BadRequest("Missing state query param")
|
||||||
|
|
||||||
|
if code == None:
|
||||||
|
raise BadRequest("Missing code query param")
|
||||||
|
|
||||||
|
token = HydraOauth.get_token(state, code)
|
||||||
|
user_info = HydraOauth.get_user_info()
|
||||||
|
# Match Kratos identity with Hydra
|
||||||
|
identities = KratosApi.get("/identities")
|
||||||
|
identity = None
|
||||||
|
for i in identities.json():
|
||||||
|
if i["traits"]["email"] == user_info["email"]:
|
||||||
|
identity = i
|
||||||
|
|
||||||
|
access_token = create_access_token(
|
||||||
|
identity=token, expires_delta=timedelta(days=365), additional_claims={"user_id": identity["id"]}
|
||||||
|
)
|
||||||
|
|
||||||
|
apps = App.query.all()
|
||||||
|
app_roles = []
|
||||||
|
for app in apps:
|
||||||
|
tmp_app_role = AppRole.query.filter_by(
|
||||||
|
user_id=identity["id"], app_id=app.id
|
||||||
|
).first()
|
||||||
|
app_roles.append(
|
||||||
|
{
|
||||||
|
"name": app.slug,
|
||||||
|
"role_id": tmp_app_role.role_id if tmp_app_role else None,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return jsonify(
|
||||||
|
{
|
||||||
|
"accessToken": access_token,
|
||||||
|
"userInfo": {
|
||||||
|
"id": identity["id"],
|
||||||
|
"email": user_info["email"],
|
||||||
|
"name": user_info["name"],
|
||||||
|
"preferredUsername": user_info["preferred_username"],
|
||||||
|
"app_roles": app_roles,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
2
backend/areas/roles/__init__.py
Normal file
2
backend/areas/roles/__init__.py
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
from .roles import *
|
||||||
|
from .models import *
|
12
backend/areas/roles/models.py
Normal file
12
backend/areas/roles/models.py
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
from sqlalchemy import Integer, String
|
||||||
|
from database import db
|
||||||
|
|
||||||
|
|
||||||
|
class Role(db.Model):
|
||||||
|
NO_ACCESS_ROLE_ID = 3
|
||||||
|
|
||||||
|
id = db.Column(Integer, primary_key=True)
|
||||||
|
name = db.Column(String(length=64))
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"Role {self.name}"
|
18
backend/areas/roles/role_service.py
Normal file
18
backend/areas/roles/role_service.py
Normal file
|
@ -0,0 +1,18 @@
|
||||||
|
from areas.apps.models import AppRole
|
||||||
|
from .models import Role
|
||||||
|
|
||||||
|
|
||||||
|
class RoleService:
|
||||||
|
@staticmethod
|
||||||
|
def get_roles():
|
||||||
|
roles = Role.query.all()
|
||||||
|
return [{"id": r.id, "name": r.name} for r in roles]
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_role_by_id(role_id):
|
||||||
|
return Role.query.filter_by(id=role_id).first()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def is_user_admin(userId):
|
||||||
|
dashboard_role_id = AppRole.query.filter_by(user_id=userId, app_id=1).first().role_id
|
||||||
|
return dashboard_role_id == 1
|
15
backend/areas/roles/roles.py
Normal file
15
backend/areas/roles/roles.py
Normal file
|
@ -0,0 +1,15 @@
|
||||||
|
from flask import jsonify, request
|
||||||
|
from flask_jwt_extended import jwt_required
|
||||||
|
from flask_cors import cross_origin
|
||||||
|
|
||||||
|
from areas import api_v1
|
||||||
|
|
||||||
|
from .role_service import RoleService
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route("/roles", methods=["GET"])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
def get_roles():
|
||||||
|
roles = RoleService.get_roles()
|
||||||
|
return jsonify(roles)
|
2
backend/areas/users/__init__.py
Normal file
2
backend/areas/users/__init__.py
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
from .users import *
|
||||||
|
from .user_service import *
|
195
backend/areas/users/user_service.py
Normal file
195
backend/areas/users/user_service.py
Normal file
|
@ -0,0 +1,195 @@
|
||||||
|
import ory_kratos_client
|
||||||
|
from ory_kratos_client.model.submit_self_service_recovery_flow_body \
|
||||||
|
import SubmitSelfServiceRecoveryFlowBody
|
||||||
|
from ory_kratos_client.api import v0alpha2_api as kratos_api
|
||||||
|
from config import KRATOS_ADMIN_URL
|
||||||
|
|
||||||
|
from database import db
|
||||||
|
from areas.apps import App, AppRole, AppsService
|
||||||
|
from areas.roles import Role, RoleService
|
||||||
|
from helpers import KratosApi
|
||||||
|
|
||||||
|
from flask import current_app
|
||||||
|
|
||||||
|
from helpers.error_handler import KratosError
|
||||||
|
|
||||||
|
kratos_admin_api_configuration = \
|
||||||
|
ory_kratos_client.Configuration(host=KRATOS_ADMIN_URL, discard_unknown_keys=True)
|
||||||
|
KRATOS_ADMIN = \
|
||||||
|
kratos_api.V0alpha2Api(ory_kratos_client.ApiClient(kratos_admin_api_configuration))
|
||||||
|
|
||||||
|
class UserService:
|
||||||
|
@staticmethod
|
||||||
|
def get_users():
|
||||||
|
res = KratosApi.get("/admin/identities").json()
|
||||||
|
userList = []
|
||||||
|
for r in res:
|
||||||
|
userList.append(UserService.__insertAppRoleToUser(r["id"], r))
|
||||||
|
|
||||||
|
return userList
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_user(id):
|
||||||
|
res = KratosApi.get("/admin/identities/{}".format(id)).json()
|
||||||
|
return UserService.__insertAppRoleToUser(id, res)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def post_user(data):
|
||||||
|
kratos_data = {
|
||||||
|
"schema_id": "default",
|
||||||
|
"traits": {
|
||||||
|
"name": data["name"],
|
||||||
|
"email": data["email"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
res = KratosApi.post("/admin/identities", kratos_data).json()
|
||||||
|
|
||||||
|
if data["app_roles"]:
|
||||||
|
app_roles = data["app_roles"]
|
||||||
|
for ar in app_roles:
|
||||||
|
app = App.query.filter_by(slug=ar["name"]).first()
|
||||||
|
app_role = AppRole(
|
||||||
|
user_id=res["id"],
|
||||||
|
role_id=ar["role_id"] if "role_id" in ar else Role.NO_ACCESS_ROLE_ID,
|
||||||
|
app_id=app.id,
|
||||||
|
)
|
||||||
|
|
||||||
|
db.session.add(app_role)
|
||||||
|
db.session.commit()
|
||||||
|
else:
|
||||||
|
all_apps = AppsService.get_all_apps()
|
||||||
|
for app in all_apps:
|
||||||
|
app_role = AppRole(
|
||||||
|
user_id=res["id"],
|
||||||
|
role_id=Role.NO_ACCESS_ROLE_ID,
|
||||||
|
app_id=app.id,
|
||||||
|
)
|
||||||
|
|
||||||
|
db.session.add(app_role)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
UserService.__start_recovery_flow(data["email"])
|
||||||
|
|
||||||
|
return UserService.get_user(res["id"])
|
||||||
|
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def __start_recovery_flow(email):
|
||||||
|
"""
|
||||||
|
Start a Kratos recovery flow for the user's email address.
|
||||||
|
|
||||||
|
This sends out an email to the user that explains to them how they can
|
||||||
|
set their password. Make sure the user exists inside Kratos before you
|
||||||
|
use this function.
|
||||||
|
|
||||||
|
:param email: Email to send recovery link to
|
||||||
|
:type email: str
|
||||||
|
"""
|
||||||
|
api_response = KRATOS_ADMIN.initialize_self_service_recovery_flow_without_browser()
|
||||||
|
flow = api_response['id']
|
||||||
|
# Submit the recovery flow to send an email to the new user.
|
||||||
|
submit_self_service_recovery_flow_body = \
|
||||||
|
SubmitSelfServiceRecoveryFlowBody(method="link", email=email)
|
||||||
|
api_response = KRATOS_ADMIN.submit_self_service_recovery_flow(flow,
|
||||||
|
submit_self_service_recovery_flow_body=
|
||||||
|
submit_self_service_recovery_flow_body)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def put_user(id, user_editing_id, data):
|
||||||
|
kratos_data = {
|
||||||
|
"schema_id": "default",
|
||||||
|
"traits": {"email": data["email"], "name": data["name"]},
|
||||||
|
}
|
||||||
|
KratosApi.put("/admin/identities/{}".format(id), kratos_data)
|
||||||
|
|
||||||
|
is_admin = RoleService.is_user_admin(user_editing_id)
|
||||||
|
|
||||||
|
if is_admin and data["app_roles"]:
|
||||||
|
app_roles = data["app_roles"]
|
||||||
|
for ar in app_roles:
|
||||||
|
app = App.query.filter_by(slug=ar["name"]).first()
|
||||||
|
app_role = AppRole.query.filter_by(
|
||||||
|
user_id=id, app_id=app.id).first()
|
||||||
|
|
||||||
|
if app_role:
|
||||||
|
app_role.role_id = ar["role_id"] if "role_id" in ar else None
|
||||||
|
db.session.commit()
|
||||||
|
else:
|
||||||
|
appRole = AppRole(
|
||||||
|
user_id=id,
|
||||||
|
role_id=ar["role_id"] if "role_id" in ar else None,
|
||||||
|
app_id=app.id,
|
||||||
|
)
|
||||||
|
db.session.add(appRole)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
return UserService.get_user(id)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def delete_user(id):
|
||||||
|
app_role = AppRole.query.filter_by(user_id=id).all()
|
||||||
|
for ar in app_role:
|
||||||
|
db.session.delete(ar)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def post_multiple_users(data):
|
||||||
|
# check if data is array
|
||||||
|
# for every item in array call Kratos
|
||||||
|
created_users = []
|
||||||
|
existing_users = []
|
||||||
|
creation_failed_users = []
|
||||||
|
|
||||||
|
for user_data in data['users']:
|
||||||
|
user_email = user_data["email"]
|
||||||
|
if not user_email:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
UserService.post_user(user_data)
|
||||||
|
current_app.logger.info(f"Batch create user: {user_email}")
|
||||||
|
created_users.append(user_email)
|
||||||
|
except KratosError as err:
|
||||||
|
status_code = err.args[1]
|
||||||
|
if status_code == 409:
|
||||||
|
existing_users.append(user_email)
|
||||||
|
elif status_code == 400:
|
||||||
|
creation_failed_users.append(user_email)
|
||||||
|
current_app.logger.error(
|
||||||
|
f"Exception calling Kratos: {err} on creating user: {user_email} {status_code}")
|
||||||
|
except Exception as error:
|
||||||
|
current_app.logger.error(
|
||||||
|
f"Exception: {error} on creating user: {user_email}")
|
||||||
|
creation_failed_users.append(user_email)
|
||||||
|
|
||||||
|
success_response = {}
|
||||||
|
existing_response = {}
|
||||||
|
failed_response = {}
|
||||||
|
if created_users:
|
||||||
|
success_response = {"users": created_users,
|
||||||
|
"message": f"{len(created_users)} users created"}
|
||||||
|
if existing_users:
|
||||||
|
existing_response = {
|
||||||
|
"users": existing_users, "message": f"{len(existing_users)} users already exist: {', '.join(existing_users)}"}
|
||||||
|
if creation_failed_users:
|
||||||
|
failed_response = {"users": creation_failed_users,
|
||||||
|
"message": f"{len(creation_failed_users)} users failed to create: {', '.join(creation_failed_users)}"}
|
||||||
|
|
||||||
|
return {"success": success_response, "existing": existing_response, "failed": failed_response}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def __insertAppRoleToUser(userId, userRes):
|
||||||
|
apps = App.query.all()
|
||||||
|
app_roles = []
|
||||||
|
for app in apps:
|
||||||
|
tmp_app_role = AppRole.query.filter_by(
|
||||||
|
user_id=userId, app_id=app.id
|
||||||
|
).first()
|
||||||
|
app_roles.append(
|
||||||
|
{
|
||||||
|
"name": app.slug,
|
||||||
|
"role_id": tmp_app_role.role_id if tmp_app_role else None,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
userRes["traits"]["app_roles"] = app_roles
|
||||||
|
return userRes
|
101
backend/areas/users/users.py
Normal file
101
backend/areas/users/users.py
Normal file
|
@ -0,0 +1,101 @@
|
||||||
|
from flask import jsonify, request
|
||||||
|
from flask_jwt_extended import get_jwt, jwt_required
|
||||||
|
from flask_cors import cross_origin
|
||||||
|
from flask_expects_json import expects_json
|
||||||
|
|
||||||
|
from areas import api_v1
|
||||||
|
from helpers import KratosApi
|
||||||
|
from helpers.auth_guard import admin_required
|
||||||
|
|
||||||
|
from .validation import schema, schema_multiple
|
||||||
|
from .user_service import UserService
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route("/users", methods=["GET"])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
@admin_required()
|
||||||
|
def get_users():
|
||||||
|
res = UserService.get_users()
|
||||||
|
return jsonify(res)
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route("/users/<string:id>", methods=["GET"])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
@admin_required()
|
||||||
|
def get_user(id):
|
||||||
|
res = UserService.get_user(id)
|
||||||
|
return jsonify(res)
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route("/users", methods=["POST"])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
@expects_json(schema)
|
||||||
|
@admin_required()
|
||||||
|
def post_user():
|
||||||
|
data = request.get_json()
|
||||||
|
res = UserService.post_user(data)
|
||||||
|
return jsonify(res)
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route("/users/<string:id>", methods=["PUT"])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
@expects_json(schema)
|
||||||
|
@admin_required()
|
||||||
|
def put_user(id):
|
||||||
|
data = request.get_json()
|
||||||
|
user_id = __get_user_id_from_jwt()
|
||||||
|
res = UserService.put_user(id, user_id, data)
|
||||||
|
return jsonify(res)
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route("/users/<string:id>", methods=["DELETE"])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
@admin_required()
|
||||||
|
def delete_user(id):
|
||||||
|
res = KratosApi.delete("/identities/{}".format(id))
|
||||||
|
if res.status_code == 204:
|
||||||
|
UserService.delete_user(id)
|
||||||
|
return jsonify(), res.status_code
|
||||||
|
return jsonify(res.json()), res.status_code
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route("/users-batch", methods=["POST"])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
@expects_json(schema_multiple)
|
||||||
|
@admin_required()
|
||||||
|
def post_multiple_users():
|
||||||
|
"""Expects an array of user JSON schema in request body."""
|
||||||
|
data = request.get_json()
|
||||||
|
res = UserService.post_multiple_users(data)
|
||||||
|
return jsonify(res)
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route("/me", methods=["GET"])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
def get_personal_info():
|
||||||
|
user_id = __get_user_id_from_jwt()
|
||||||
|
res = UserService.get_user(user_id)
|
||||||
|
return jsonify(res)
|
||||||
|
|
||||||
|
|
||||||
|
@api_v1.route("/me", methods=["PUT"])
|
||||||
|
@jwt_required()
|
||||||
|
@cross_origin()
|
||||||
|
@expects_json(schema)
|
||||||
|
def update_personal_info():
|
||||||
|
data = request.get_json()
|
||||||
|
user_id = __get_user_id_from_jwt()
|
||||||
|
res = UserService.put_user(user_id, user_id, data)
|
||||||
|
return jsonify(res)
|
||||||
|
|
||||||
|
|
||||||
|
def __get_user_id_from_jwt():
|
||||||
|
claims = get_jwt()
|
||||||
|
return claims["user_id"]
|
42
backend/areas/users/validation.py
Normal file
42
backend/areas/users/validation.py
Normal file
|
@ -0,0 +1,42 @@
|
||||||
|
import re
|
||||||
|
|
||||||
|
schema = {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"email": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Email of the user",
|
||||||
|
"pattern": r"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])",
|
||||||
|
"minLength": 1,
|
||||||
|
},
|
||||||
|
"app_roles": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"type": "object",
|
||||||
|
"properties": {
|
||||||
|
"name": {
|
||||||
|
"type": "string",
|
||||||
|
"description": "Name of the app",
|
||||||
|
"minLenght": 1,
|
||||||
|
},
|
||||||
|
"role_id": {
|
||||||
|
"type": ["integer", "null"],
|
||||||
|
"description": "Role of the user",
|
||||||
|
"minimum": 1,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": ["name", "role_id"],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"required": ["email", "app_roles"],
|
||||||
|
}
|
||||||
|
|
||||||
|
schema_multiple = {
|
||||||
|
"users": {
|
||||||
|
"type": "array",
|
||||||
|
"items": {
|
||||||
|
"$ref": schema
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
3
backend/cliapp/__init__.py
Normal file
3
backend/cliapp/__init__.py
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
from flask import Blueprint
|
||||||
|
|
||||||
|
cli = Blueprint("cli", __name__)
|
1
backend/cliapp/cliapp/__init__.py
Normal file
1
backend/cliapp/cliapp/__init__.py
Normal file
|
@ -0,0 +1 @@
|
||||||
|
from .cli import *
|
412
backend/cliapp/cliapp/cli.py
Normal file
412
backend/cliapp/cliapp/cli.py
Normal file
|
@ -0,0 +1,412 @@
|
||||||
|
"""Flask application which provides the interface of a login panel. The
|
||||||
|
application interacts with different backend, like the Kratos backend for users,
|
||||||
|
Hydra for OIDC sessions and MariaDB for application and role specifications.
|
||||||
|
The application provides also several command line options to interact with
|
||||||
|
the user entries in the database(s)"""
|
||||||
|
|
||||||
|
import sys
|
||||||
|
|
||||||
|
import click
|
||||||
|
import hydra_client
|
||||||
|
import ory_kratos_client
|
||||||
|
from flask import current_app
|
||||||
|
from flask.cli import AppGroup
|
||||||
|
from ory_kratos_client.api import v0alpha2_api as kratos_api
|
||||||
|
from sqlalchemy import func
|
||||||
|
|
||||||
|
from config import HYDRA_ADMIN_URL, KRATOS_ADMIN_URL, KRATOS_PUBLIC_URL
|
||||||
|
from helpers import KratosUser
|
||||||
|
from cliapp import cli
|
||||||
|
from areas.roles import Role
|
||||||
|
from areas.apps import AppRole, App
|
||||||
|
from database import db
|
||||||
|
|
||||||
|
# APIs
|
||||||
|
# Create HYDRA & KRATOS API interfaces
|
||||||
|
HYDRA = hydra_client.HydraAdmin(HYDRA_ADMIN_URL)
|
||||||
|
|
||||||
|
# Kratos has an admin and public end-point. We create an API for them
|
||||||
|
# both. The kratos implementation has bugs, which forces us to set
|
||||||
|
# the discard_unknown_keys to True.
|
||||||
|
kratos_admin_api_configuration = \
|
||||||
|
ory_kratos_client.Configuration(host=KRATOS_ADMIN_URL, discard_unknown_keys=True)
|
||||||
|
KRATOS_ADMIN = \
|
||||||
|
kratos_api.V0alpha2Api(ory_kratos_client.ApiClient(kratos_admin_api_configuration))
|
||||||
|
|
||||||
|
kratos_public_api_configuration = \
|
||||||
|
ory_kratos_client.Configuration(host=KRATOS_PUBLIC_URL, discard_unknown_keys=True)
|
||||||
|
KRATOS_PUBLIC = \
|
||||||
|
kratos_api.V0alpha2Api(ory_kratos_client.ApiClient(kratos_public_api_configuration))
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
# CLI INTERFACE #
|
||||||
|
##############################################################################
|
||||||
|
# Define Flask CLI command groups and commands
|
||||||
|
user_cli = AppGroup("user")
|
||||||
|
app_cli = AppGroup("app")
|
||||||
|
|
||||||
|
## CLI APP COMMANDS
|
||||||
|
|
||||||
|
|
||||||
|
@app_cli.command("create")
|
||||||
|
@click.argument("slug")
|
||||||
|
@click.argument("name")
|
||||||
|
@click.argument("external-url", required=False)
|
||||||
|
def create_app(slug, name, external_url = None):
|
||||||
|
"""Adds an app into the database
|
||||||
|
:param slug: str short name of the app
|
||||||
|
:param name: str name of the application
|
||||||
|
:param extenal-url: if set, it marks this as an external app and
|
||||||
|
configures the url
|
||||||
|
"""
|
||||||
|
current_app.logger.info(f"Creating app definition: {name} ({slug}")
|
||||||
|
|
||||||
|
obj = App()
|
||||||
|
obj.name = name
|
||||||
|
obj.slug = slug
|
||||||
|
|
||||||
|
app_obj = App.query.filter_by(slug=slug).first()
|
||||||
|
|
||||||
|
if app_obj:
|
||||||
|
current_app.logger.info(f"App definition: {name} ({slug}) already exists in database")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
if (external_url):
|
||||||
|
obj.external = True
|
||||||
|
obj.url = external_url
|
||||||
|
|
||||||
|
db.session.add(obj)
|
||||||
|
db.session.commit()
|
||||||
|
current_app.logger.info(f"App definition: {name} ({slug}) created")
|
||||||
|
|
||||||
|
|
||||||
|
@app_cli.command("list")
|
||||||
|
def list_app():
|
||||||
|
"""List all apps found in the database"""
|
||||||
|
current_app.logger.info("Listing configured apps")
|
||||||
|
apps = App.query.all()
|
||||||
|
|
||||||
|
for obj in apps:
|
||||||
|
print(f"App name: {obj.name}\tSlug: {obj.slug},\tURL: {obj.get_url()}\tStatus: {obj.get_status()}")
|
||||||
|
|
||||||
|
|
||||||
|
@app_cli.command(
|
||||||
|
"delete",
|
||||||
|
)
|
||||||
|
@click.argument("slug")
|
||||||
|
def delete_app(slug):
|
||||||
|
"""Removes app from database
|
||||||
|
:param slug: str Slug of app to remove
|
||||||
|
"""
|
||||||
|
current_app.logger.info(f"Trying to delete app: {slug}")
|
||||||
|
app_obj = App.query.filter_by(slug=slug).first()
|
||||||
|
|
||||||
|
if not app_obj:
|
||||||
|
current_app.logger.info("Not found")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
app_status = app_obj.get_status()
|
||||||
|
if app_status.installed and not app_obj.external:
|
||||||
|
current_app.logger.info("Can not delete installed application, run"
|
||||||
|
" 'uninstall' first")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
app_obj.delete()
|
||||||
|
current_app.logger.info("Success.")
|
||||||
|
|
||||||
|
|
||||||
|
@app_cli.command(
|
||||||
|
"uninstall",
|
||||||
|
)
|
||||||
|
@click.argument("slug")
|
||||||
|
def uninstall_app(slug):
|
||||||
|
"""Uninstalls the app from the cluster
|
||||||
|
:param slug: str Slug of app to remove
|
||||||
|
"""
|
||||||
|
current_app.logger.info(f"Trying to uninstall app: {slug}")
|
||||||
|
app_obj = App.query.filter_by(slug=slug).first()
|
||||||
|
|
||||||
|
if not app_obj:
|
||||||
|
current_app.logger.info("Not found")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
app_obj.uninstall()
|
||||||
|
current_app.logger.info("Success.")
|
||||||
|
|
||||||
|
@app_cli.command("status")
|
||||||
|
@click.argument("slug")
|
||||||
|
def status_app(slug):
|
||||||
|
"""Gets the current app status from the Kubernetes cluster
|
||||||
|
:param slug: str Slug of app to remove
|
||||||
|
"""
|
||||||
|
current_app.logger.info(f"Getting status for app: {slug}")
|
||||||
|
|
||||||
|
app = App.query.filter_by(slug=slug).first()
|
||||||
|
|
||||||
|
if not app:
|
||||||
|
current_app.logger.error(f"App {slug} does not exist")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
current_app.logger.info(app.get_status())
|
||||||
|
|
||||||
|
@app_cli.command("install")
|
||||||
|
@click.argument("slug")
|
||||||
|
def install_app(slug):
|
||||||
|
"""Installs app into Kubernetes cluster
|
||||||
|
:param slug: str Slug of app to install
|
||||||
|
"""
|
||||||
|
current_app.logger.info(f"Installing app: {slug}")
|
||||||
|
|
||||||
|
app = App.query.filter_by(slug=slug).first()
|
||||||
|
|
||||||
|
if not app:
|
||||||
|
current_app.logger.error(f"App {slug} does not exist")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
if app.external:
|
||||||
|
current_app.logger.info(
|
||||||
|
f"App {slug} is an external app and can not be provisioned automatically")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
current_status = app.get_status()
|
||||||
|
if not current_status.installed:
|
||||||
|
app.install()
|
||||||
|
current_app.logger.info(
|
||||||
|
f"App {slug} installing... use `status` to see status")
|
||||||
|
else:
|
||||||
|
current_app.logger.error(f"App {slug} is already installed")
|
||||||
|
|
||||||
|
@app_cli.command("roles")
|
||||||
|
@click.argument("slug")
|
||||||
|
def roles_app(slug):
|
||||||
|
"""Gets a list of roles for this app
|
||||||
|
:param slug: str Slug of app queried
|
||||||
|
"""
|
||||||
|
current_app.logger.info(f"Getting roles for app: {slug}")
|
||||||
|
|
||||||
|
app = App.query.filter_by(slug=slug).first()
|
||||||
|
|
||||||
|
if not app:
|
||||||
|
current_app.logger.error(f"App {slug} does not exist")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
current_app.logger.info("Roles: ")
|
||||||
|
for role in app.roles:
|
||||||
|
current_app.logger.info(role)
|
||||||
|
|
||||||
|
|
||||||
|
cli.cli.add_command(app_cli)
|
||||||
|
|
||||||
|
|
||||||
|
## CLI USER COMMANDS
|
||||||
|
@user_cli.command("setrole")
|
||||||
|
@click.argument("email")
|
||||||
|
@click.argument("app_slug")
|
||||||
|
@click.argument("role")
|
||||||
|
def setrole(email, app_slug, role):
|
||||||
|
"""Set role for a user
|
||||||
|
:param email: Email address of user to assign role
|
||||||
|
:param app_slug: Slug name of the app, for example 'nextcloud'
|
||||||
|
:param role: Role to assign. currently only 'admin', 'user'
|
||||||
|
"""
|
||||||
|
|
||||||
|
current_app.logger.info(f"Assigning role {role} to {email} for app {app_slug}")
|
||||||
|
|
||||||
|
# Find user
|
||||||
|
user = KratosUser.find_by_email(KRATOS_ADMIN, email)
|
||||||
|
|
||||||
|
if role not in ("admin", "user"):
|
||||||
|
print("At this point only the roles 'admin' and 'user' are accepted")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
if not user:
|
||||||
|
print("User not found. Abort")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
app_obj = db.session.query(App).filter(App.slug == app_slug).first()
|
||||||
|
if not app_obj:
|
||||||
|
print("App not found. Abort.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
role_obj = (
|
||||||
|
db.session.query(AppRole)
|
||||||
|
.filter(AppRole.app_id == app_obj.id)
|
||||||
|
.filter(AppRole.user_id == user.uuid)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
|
||||||
|
if role_obj:
|
||||||
|
db.session.delete(role_obj)
|
||||||
|
|
||||||
|
role = Role.query.filter(func.lower(Role.name) == func.lower(role)).first()
|
||||||
|
|
||||||
|
obj = AppRole()
|
||||||
|
obj.user_id = user.uuid
|
||||||
|
obj.app_id = app_obj.id
|
||||||
|
obj.role_id = role.id if role else None
|
||||||
|
|
||||||
|
db.session.add(obj)
|
||||||
|
db.session.commit()
|
||||||
|
|
||||||
|
|
||||||
|
@user_cli.command("show")
|
||||||
|
@click.argument("email")
|
||||||
|
def show_user(email):
|
||||||
|
"""Show user details. Output a table with the user and details about the
|
||||||
|
internal state/values of the user object
|
||||||
|
:param email: Email address of the user to show
|
||||||
|
"""
|
||||||
|
user = KratosUser.find_by_email(KRATOS_ADMIN, email)
|
||||||
|
if user is not None:
|
||||||
|
print(user)
|
||||||
|
print("")
|
||||||
|
print(f"UUID: {user.uuid}")
|
||||||
|
print(f"Username: {user.username}")
|
||||||
|
print(f"Updated: {user.updated_at}")
|
||||||
|
print(f"Created: {user.created_at}")
|
||||||
|
print(f"State: {user.state}")
|
||||||
|
print(f"Roles:")
|
||||||
|
results = db.session.query(AppRole, Role).join(App, Role)\
|
||||||
|
.add_entity(App).add_entity(Role)\
|
||||||
|
.filter(AppRole.user_id == user.uuid)
|
||||||
|
for entry in results:
|
||||||
|
app = entry[-2]
|
||||||
|
role = entry[-1]
|
||||||
|
print(f" {role.name: >9} on {app.name}")
|
||||||
|
else:
|
||||||
|
print(f"User with email address '{email}' was not found")
|
||||||
|
|
||||||
|
|
||||||
|
@user_cli.command("update")
|
||||||
|
@click.argument("email")
|
||||||
|
@click.argument("field")
|
||||||
|
@click.argument("value")
|
||||||
|
def update_user(email, field, value):
|
||||||
|
"""Update an user object. It can modify email and name currently
|
||||||
|
:param email: Email address of user to update
|
||||||
|
:param field: Field to update, supported [name|email]
|
||||||
|
:param value: The value to set the field with
|
||||||
|
"""
|
||||||
|
current_app.logger.info(f"Looking for user with email: {email}")
|
||||||
|
user = KratosUser.find_by_email(KRATOS_ADMIN, email)
|
||||||
|
if not user:
|
||||||
|
current_app.logger.error(f"User with email {email} not found.")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
if field == "name":
|
||||||
|
user.name = value
|
||||||
|
elif field == "email":
|
||||||
|
user.email = value
|
||||||
|
else:
|
||||||
|
current_app.logger.error(f"Field not found: {field}")
|
||||||
|
|
||||||
|
user.save()
|
||||||
|
|
||||||
|
|
||||||
|
@user_cli.command("delete")
|
||||||
|
@click.argument("email")
|
||||||
|
def delete_user(email):
|
||||||
|
"""Delete an user from the database
|
||||||
|
:param email: Email address of user to delete
|
||||||
|
"""
|
||||||
|
current_app.logger.info(f"Looking for user with email: {email}")
|
||||||
|
user = KratosUser.find_by_email(KRATOS_ADMIN, email)
|
||||||
|
if not user:
|
||||||
|
current_app.logger.error(f"User with email {email} not found.")
|
||||||
|
sys.exit(1)
|
||||||
|
user.delete()
|
||||||
|
|
||||||
|
|
||||||
|
@user_cli.command("create")
|
||||||
|
@click.argument("email")
|
||||||
|
def create_user(email):
|
||||||
|
"""Create a user in the kratos database. The argument must be an unique
|
||||||
|
email address
|
||||||
|
:param email: string Email address of user to add
|
||||||
|
"""
|
||||||
|
current_app.logger.info(f"Creating user with email: ({email})")
|
||||||
|
|
||||||
|
# Create a user
|
||||||
|
user = KratosUser.find_by_email(KRATOS_ADMIN, email)
|
||||||
|
if user:
|
||||||
|
current_app.logger.info("User already exists. Not recreating")
|
||||||
|
return
|
||||||
|
|
||||||
|
user = KratosUser(KRATOS_ADMIN)
|
||||||
|
user.email = email
|
||||||
|
user.save()
|
||||||
|
|
||||||
|
|
||||||
|
@user_cli.command("setpassword")
|
||||||
|
@click.argument("email")
|
||||||
|
@click.argument("password")
|
||||||
|
def setpassword_user(email, password):
|
||||||
|
"""Set a password for an account
|
||||||
|
:param email: email address of account to set a password for
|
||||||
|
:param password: password to be set
|
||||||
|
:raise: exception if unexepted error happens
|
||||||
|
"""
|
||||||
|
|
||||||
|
current_app.logger.info(f"Setting password for: ({email})")
|
||||||
|
|
||||||
|
# Kratos does not provide an interface to set a password directly. However
|
||||||
|
# we still want to be able to set a password. So we have to hack our way
|
||||||
|
# a bit around this. We do this by creating a recovery link though the
|
||||||
|
# admin interface (which is not e-mailed) and then follow the recovery
|
||||||
|
# flow in the public facing pages of kratos
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Get the ID of the user
|
||||||
|
kratos_user = KratosUser.find_by_email(KRATOS_ADMIN, email)
|
||||||
|
if kratos_user is None:
|
||||||
|
current_app.logger.error(f"User with email '{email}' not found")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# Get a recovery URL
|
||||||
|
url = kratos_user.get_recovery_link()
|
||||||
|
|
||||||
|
# Execute UI sequence to set password, given we have a recovery URL
|
||||||
|
result = kratos_user.ui_set_password(KRATOS_PUBLIC_URL, url, password)
|
||||||
|
|
||||||
|
except Exception as error: # pylint: disable=broad-except
|
||||||
|
current_app.logger.error(f"Error while setting password: {error}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
if result:
|
||||||
|
current_app.logger.info("Success setting password")
|
||||||
|
else:
|
||||||
|
current_app.logger.error("Failed to set password. Password too weak?")
|
||||||
|
|
||||||
|
|
||||||
|
@user_cli.command("list")
|
||||||
|
def list_user():
|
||||||
|
"""Show a list of users in the database"""
|
||||||
|
current_app.logger.info("Listing users")
|
||||||
|
users = KratosUser.find_all(KRATOS_ADMIN)
|
||||||
|
|
||||||
|
for obj in users:
|
||||||
|
print(obj)
|
||||||
|
|
||||||
|
|
||||||
|
@user_cli.command("recover")
|
||||||
|
@click.argument("email")
|
||||||
|
def recover_user(email):
|
||||||
|
"""Get recovery link for a user, to manual update the user/use
|
||||||
|
:param email: Email address of the user
|
||||||
|
"""
|
||||||
|
|
||||||
|
current_app.logger.info(f"Trying to send recover email for user: {email}")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Get the ID of the user
|
||||||
|
kratos_user = KratosUser.find_by_email(KRATOS_ADMIN, email)
|
||||||
|
|
||||||
|
# Get a recovery URL
|
||||||
|
url = kratos_user.get_recovery_link()
|
||||||
|
|
||||||
|
print(url)
|
||||||
|
except Exception as error: # pylint: disable=broad-except
|
||||||
|
current_app.logger.error(f"Error while getting reset link: {error}")
|
||||||
|
|
||||||
|
|
||||||
|
cli.cli.add_command(user_cli)
|
22
backend/config.py
Normal file
22
backend/config.py
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
import os
|
||||||
|
|
||||||
|
SECRET_KEY = os.environ.get("SECRET_KEY")
|
||||||
|
HYDRA_CLIENT_ID = os.environ.get("HYDRA_CLIENT_ID")
|
||||||
|
HYDRA_CLIENT_SECRET = os.environ.get("HYDRA_CLIENT_SECRET")
|
||||||
|
HYDRA_AUTHORIZATION_BASE_URL = os.environ.get("HYDRA_AUTHORIZATION_BASE_URL")
|
||||||
|
TOKEN_URL = os.environ.get("TOKEN_URL")
|
||||||
|
|
||||||
|
LOGIN_PANEL_URL = os.environ.get("LOGIN_PANEL_URL")
|
||||||
|
|
||||||
|
HYDRA_PUBLIC_URL = os.environ.get("HYDRA_PUBLIC_URL")
|
||||||
|
HYDRA_ADMIN_URL = os.environ.get("HYDRA_ADMIN_URL")
|
||||||
|
KRATOS_ADMIN_URL = os.environ.get("KRATOS_ADMIN_URL")
|
||||||
|
KRATOS_PUBLIC_URL = str(os.environ.get("KRATOS_PUBLIC_URL")) + "/"
|
||||||
|
|
||||||
|
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")
|
||||||
|
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||||
|
|
||||||
|
# Set this to "true" to load the config from a Kubernetes serviceaccount
|
||||||
|
# running in a Kubernetes pod. Set it to "false" to load the config from the
|
||||||
|
# `KUBECONFIG` environment variable.
|
||||||
|
LOAD_INCLUSTER_CONFIG = os.environ.get("LOAD_INCLUSTER_CONFIG").lower() == "true"
|
2
backend/database.py
Normal file
2
backend/database.py
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
from flask_sqlalchemy import SQLAlchemy
|
||||||
|
db = SQLAlchemy()
|
80
backend/docker-compose.yml
Normal file
80
backend/docker-compose.yml
Normal file
|
@ -0,0 +1,80 @@
|
||||||
|
version: '3'
|
||||||
|
services:
|
||||||
|
stackspin_proxy:
|
||||||
|
image: nginx:1.23.1
|
||||||
|
ports:
|
||||||
|
- "8081:8081"
|
||||||
|
volumes:
|
||||||
|
- ./proxy/default.conf:/etc/nginx/conf.d/default.conf
|
||||||
|
depends_on:
|
||||||
|
- kube_port_kratos_public
|
||||||
|
- flask_app
|
||||||
|
flask_app:
|
||||||
|
build: .
|
||||||
|
environment:
|
||||||
|
- FLASK_APP=app.py
|
||||||
|
- FLASK_ENV=development
|
||||||
|
- HYDRA_CLIENT_ID=dashboard-local
|
||||||
|
|
||||||
|
# Domain-specific URL settings
|
||||||
|
- HYDRA_AUTHORIZATION_BASE_URL=https://sso.$DOMAIN/oauth2/auth
|
||||||
|
- TOKEN_URL=https://sso.$DOMAIN/oauth2/token
|
||||||
|
- HYDRA_PUBLIC_URL=https://sso.$DOMAIN
|
||||||
|
|
||||||
|
# Local path overrides
|
||||||
|
- KRATOS_PUBLIC_URL=http://stackspin_proxy:8081/kratos
|
||||||
|
- KRATOS_ADMIN_URL=http://kube_port_kratos_admin:8000
|
||||||
|
- HYDRA_ADMIN_URL=http://kube_port_hydra_admin:4445
|
||||||
|
- LOGIN_PANEL_URL=http://stackspin_proxy:8081/web/
|
||||||
|
- DATABASE_URL=mysql+pymysql://stackspin:$DATABASE_PASSWORD@kube_port_mysql/stackspin
|
||||||
|
|
||||||
|
# ENV variables that are deployment-specific
|
||||||
|
- SECRET_KEY=$FLASK_SECRET_KEY
|
||||||
|
- HYDRA_CLIENT_SECRET=$HYDRA_CLIENT_SECRET
|
||||||
|
- KUBECONFIG=/.kube/config
|
||||||
|
|
||||||
|
# Disable loading config from the service account
|
||||||
|
- LOAD_INCLUSTER_CONFIG=false
|
||||||
|
ports:
|
||||||
|
- "5000:5000"
|
||||||
|
user: "${KUBECTL_UID}:${KUBECTL_GID}"
|
||||||
|
volumes:
|
||||||
|
- .:/app
|
||||||
|
- "$KUBECONFIG:/.kube/config"
|
||||||
|
depends_on:
|
||||||
|
- kube_port_mysql
|
||||||
|
entrypoint: ["bash", "-c", "flask run --host $$(hostname -i)"]
|
||||||
|
kube_port_kratos_admin:
|
||||||
|
image: bitnami/kubectl:1.25.3
|
||||||
|
user: "${KUBECTL_UID}:${KUBECTL_GID}"
|
||||||
|
expose:
|
||||||
|
- 8000
|
||||||
|
volumes:
|
||||||
|
- "$KUBECONFIG:/.kube/config"
|
||||||
|
entrypoint: ["bash", "-c", "kubectl -n stackspin port-forward --address $$(hostname -i) service/kratos-admin 8000:80"]
|
||||||
|
kube_port_hydra_admin:
|
||||||
|
image: bitnami/kubectl:1.25.3
|
||||||
|
user: "${KUBECTL_UID}:${KUBECTL_GID}"
|
||||||
|
expose:
|
||||||
|
- 4445
|
||||||
|
volumes:
|
||||||
|
- "$KUBECONFIG:/.kube/config"
|
||||||
|
entrypoint: ["bash", "-c", "kubectl -n stackspin port-forward --address $$(hostname -i) service/hydra-admin 4445:4445"]
|
||||||
|
kube_port_kratos_public:
|
||||||
|
image: bitnami/kubectl:1.25.3
|
||||||
|
user: "${KUBECTL_UID}:${KUBECTL_GID}"
|
||||||
|
ports:
|
||||||
|
- "8080:8080"
|
||||||
|
expose:
|
||||||
|
- 8080
|
||||||
|
volumes:
|
||||||
|
- "$KUBECONFIG:/.kube/config"
|
||||||
|
entrypoint: ["bash", "-c", "kubectl -n stackspin port-forward --address $$(hostname -i) service/kratos-public 8080:80"]
|
||||||
|
kube_port_mysql:
|
||||||
|
image: bitnami/kubectl:1.25.3
|
||||||
|
user: "${KUBECTL_UID}:${KUBECTL_GID}"
|
||||||
|
expose:
|
||||||
|
- 3306
|
||||||
|
volumes:
|
||||||
|
- "$KUBECONFIG:/.kube/config"
|
||||||
|
entrypoint: ["bash", "-c", "kubectl -n stackspin port-forward --address $$(hostname -i) service/single-sign-on-database-mariadb 3306:3306"]
|
4
backend/helpers/__init__.py
Normal file
4
backend/helpers/__init__.py
Normal file
|
@ -0,0 +1,4 @@
|
||||||
|
from .kratos_api import *
|
||||||
|
from .error_handler import *
|
||||||
|
from .hydra_oauth import *
|
||||||
|
from .kratos_user import *
|
24
backend/helpers/auth_guard.py
Normal file
24
backend/helpers/auth_guard.py
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
|
from areas.roles.role_service import RoleService
|
||||||
|
|
||||||
|
from flask_jwt_extended import get_jwt, verify_jwt_in_request
|
||||||
|
from helpers import Unauthorized
|
||||||
|
|
||||||
|
|
||||||
|
def admin_required():
|
||||||
|
def wrapper(fn):
|
||||||
|
@wraps(fn)
|
||||||
|
def decorator(*args, **kwargs):
|
||||||
|
verify_jwt_in_request()
|
||||||
|
claims = get_jwt()
|
||||||
|
user_id = claims["user_id"]
|
||||||
|
is_admin = RoleService.is_user_admin(user_id)
|
||||||
|
if is_admin:
|
||||||
|
return fn(*args, **kwargs)
|
||||||
|
else:
|
||||||
|
raise Unauthorized("You need to have admin permissions.")
|
||||||
|
|
||||||
|
return decorator
|
||||||
|
|
||||||
|
return wrapper
|
17
backend/helpers/classes.py
Normal file
17
backend/helpers/classes.py
Normal file
|
@ -0,0 +1,17 @@
|
||||||
|
|
||||||
|
"""Generic classes used by different parts of the application"""
|
||||||
|
|
||||||
|
import urllib.request
|
||||||
|
|
||||||
|
# Instead of processing the redirect, we return, so the application
|
||||||
|
# can handle the redirect itself. This is needed to extract cookies
|
||||||
|
# etc.
|
||||||
|
class RedirectFilter(urllib.request.HTTPRedirectHandler):
|
||||||
|
"""Overrides the standard redirect handler so it does not automatically
|
||||||
|
redirect. This allows for inspecting the return values before redirecting or
|
||||||
|
override the redirect action"""
|
||||||
|
|
||||||
|
# pylint: disable=too-many-arguments
|
||||||
|
# This amount of arguments is expected by the HTTPRedirectHandler
|
||||||
|
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||||
|
return None
|
50
backend/helpers/error_handler.py
Normal file
50
backend/helpers/error_handler.py
Normal file
|
@ -0,0 +1,50 @@
|
||||||
|
from flask import jsonify
|
||||||
|
from jsonschema import ValidationError
|
||||||
|
|
||||||
|
|
||||||
|
class KratosError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class HydraError(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class BadRequest(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class Unauthorized(Exception):
|
||||||
|
pass
|
||||||
|
|
||||||
|
def bad_request_error(e):
|
||||||
|
message = e.args[0] if e.args else "Bad request to the server."
|
||||||
|
return jsonify({"errorMessage": message}), 400
|
||||||
|
|
||||||
|
|
||||||
|
def validation_error(e):
|
||||||
|
original_error = e.description
|
||||||
|
return (
|
||||||
|
jsonify({"errorMessage": "{} is not valid.".format(original_error.path[0])}),
|
||||||
|
400,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def kratos_error(e):
|
||||||
|
message = "[KratosError] " + e.args[0] if e.args else "Failed to contact Kratos."
|
||||||
|
status_code = e.args[1] if e.args else 500
|
||||||
|
return jsonify({"errorMessage": message}), status_code
|
||||||
|
|
||||||
|
|
||||||
|
def hydra_error(e):
|
||||||
|
message = "[HydraError] " + e.args[0] if e.args else "Failed to contact Hydra."
|
||||||
|
status_code = e.args[1] if e.args else 500
|
||||||
|
return jsonify({"errorMessage": message}), status_code
|
||||||
|
|
||||||
|
|
||||||
|
def global_error(e):
|
||||||
|
message = str(e)
|
||||||
|
return jsonify({"errorMessage": message}), 500
|
||||||
|
|
||||||
|
def unauthorized_error(e):
|
||||||
|
message = str(e)
|
||||||
|
return jsonify({"errorMessage": message}), 403
|
8
backend/helpers/exceptions.py
Normal file
8
backend/helpers/exceptions.py
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
|
||||||
|
"""Custom exception handler to raise consistent exceptions, as different backend
|
||||||
|
raise different exceptions"""
|
||||||
|
|
||||||
|
class BackendError(Exception):
|
||||||
|
"""The backend error is raised when interacting with
|
||||||
|
the backend fails or gives an unexpected result. The
|
||||||
|
error contains a oneliner description of the problem"""
|
50
backend/helpers/hydra_oauth.py
Normal file
50
backend/helpers/hydra_oauth.py
Normal file
|
@ -0,0 +1,50 @@
|
||||||
|
from flask import request, session
|
||||||
|
from requests_oauthlib import OAuth2Session
|
||||||
|
|
||||||
|
from config import *
|
||||||
|
from helpers import HydraError
|
||||||
|
|
||||||
|
|
||||||
|
class HydraOauth:
|
||||||
|
@staticmethod
|
||||||
|
def authorize():
|
||||||
|
try:
|
||||||
|
hydra = OAuth2Session(HYDRA_CLIENT_ID)
|
||||||
|
authorization_url, state = hydra.authorization_url(
|
||||||
|
HYDRA_AUTHORIZATION_BASE_URL
|
||||||
|
)
|
||||||
|
|
||||||
|
return authorization_url
|
||||||
|
except Exception as err:
|
||||||
|
raise HydraError(str(err), 500)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_token(state, code):
|
||||||
|
try:
|
||||||
|
hydra = OAuth2Session(
|
||||||
|
client_id=HYDRA_CLIENT_ID,
|
||||||
|
state=state,
|
||||||
|
)
|
||||||
|
token = hydra.fetch_token(
|
||||||
|
token_url=TOKEN_URL,
|
||||||
|
code=code,
|
||||||
|
client_secret=HYDRA_CLIENT_SECRET,
|
||||||
|
include_client_id=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
session["hydra_token"] = token
|
||||||
|
return token
|
||||||
|
except Exception as err:
|
||||||
|
raise HydraError(str(err), 500)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get_user_info():
|
||||||
|
try:
|
||||||
|
hydra = OAuth2Session(
|
||||||
|
client_id=HYDRA_CLIENT_ID, token=session["hydra_token"]
|
||||||
|
)
|
||||||
|
user_info = hydra.get("{}/userinfo".format(HYDRA_PUBLIC_URL))
|
||||||
|
|
||||||
|
return user_info.json()
|
||||||
|
except Exception as err:
|
||||||
|
raise HydraError(str(err), 500)
|
57
backend/helpers/kratos_api.py
Normal file
57
backend/helpers/kratos_api.py
Normal file
|
@ -0,0 +1,57 @@
|
||||||
|
from logging import error
|
||||||
|
import requests
|
||||||
|
|
||||||
|
from config import *
|
||||||
|
from .error_handler import KratosError
|
||||||
|
|
||||||
|
|
||||||
|
class KratosApi:
|
||||||
|
@staticmethod
|
||||||
|
def __handleError(res):
|
||||||
|
if res.status_code >= 400:
|
||||||
|
message = res.json()["error"]["message"]
|
||||||
|
raise KratosError(message, res.status_code)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def get(url):
|
||||||
|
try:
|
||||||
|
res = requests.get("{}{}".format(KRATOS_ADMIN_URL, url))
|
||||||
|
KratosApi.__handleError(res)
|
||||||
|
return res
|
||||||
|
except KratosError as err:
|
||||||
|
raise err
|
||||||
|
except:
|
||||||
|
raise KratosError()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def post(url, data):
|
||||||
|
try:
|
||||||
|
res = requests.post("{}{}".format(KRATOS_ADMIN_URL, url), json=data)
|
||||||
|
KratosApi.__handleError(res)
|
||||||
|
return res
|
||||||
|
except KratosError as err:
|
||||||
|
raise err
|
||||||
|
except:
|
||||||
|
raise KratosError()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def put(url, data):
|
||||||
|
try:
|
||||||
|
res = requests.put("{}{}".format(KRATOS_ADMIN_URL, url), json=data)
|
||||||
|
KratosApi.__handleError(res)
|
||||||
|
return res
|
||||||
|
except KratosError as err:
|
||||||
|
raise err
|
||||||
|
except:
|
||||||
|
raise KratosError()
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def delete(url):
|
||||||
|
try:
|
||||||
|
res = requests.delete("{}{}".format(KRATOS_ADMIN_URL, url))
|
||||||
|
KratosApi.__handleError(res)
|
||||||
|
return res
|
||||||
|
except KratosError as err:
|
||||||
|
raise err
|
||||||
|
except:
|
||||||
|
raise KratosError()
|
392
backend/helpers/kratos_user.py
Normal file
392
backend/helpers/kratos_user.py
Normal file
|
@ -0,0 +1,392 @@
|
||||||
|
"""
|
||||||
|
Implement the Kratos model to interact with kratos users
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import re
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
from typing import Dict
|
||||||
|
from urllib.request import Request
|
||||||
|
|
||||||
|
# Some imports commented out to satisfy pylint. They will be used once more
|
||||||
|
# functions are migrated to this model
|
||||||
|
from ory_kratos_client.model.admin_create_identity_body import AdminCreateIdentityBody
|
||||||
|
from ory_kratos_client.model.admin_create_self_service_recovery_link_body \
|
||||||
|
import AdminCreateSelfServiceRecoveryLinkBody
|
||||||
|
from ory_kratos_client.model.admin_update_identity_body import AdminUpdateIdentityBody
|
||||||
|
from ory_kratos_client.rest import ApiException as KratosApiException
|
||||||
|
|
||||||
|
from .classes import RedirectFilter
|
||||||
|
from .exceptions import BackendError
|
||||||
|
|
||||||
|
# pylint: disable=too-many-instance-attributes
|
||||||
|
class KratosUser():
|
||||||
|
"""
|
||||||
|
The User object, interact with the User. It both calls to Kratos as to
|
||||||
|
the database for storing and retrieving data.
|
||||||
|
"""
|
||||||
|
|
||||||
|
api = None
|
||||||
|
__uuid = None
|
||||||
|
email = None
|
||||||
|
name = None
|
||||||
|
username = None
|
||||||
|
state = None
|
||||||
|
created_at = None
|
||||||
|
updated_at = None
|
||||||
|
|
||||||
|
def __init__(self, api, uuid = None):
|
||||||
|
self.api = api
|
||||||
|
self.state = 'active'
|
||||||
|
if uuid:
|
||||||
|
try:
|
||||||
|
obj = api.admin_get_identity(uuid)
|
||||||
|
if obj:
|
||||||
|
self.__uuid = uuid
|
||||||
|
try:
|
||||||
|
self.name = obj.traits['name']
|
||||||
|
except KeyError:
|
||||||
|
self.name = ""
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.username = obj.traits['username']
|
||||||
|
except KeyError:
|
||||||
|
self.username = ""
|
||||||
|
self.email = obj.traits['email']
|
||||||
|
self.state = obj.state
|
||||||
|
self.created_at = obj.created_at
|
||||||
|
self.updated_at = obj.updated_at
|
||||||
|
except KratosApiException as error:
|
||||||
|
raise BackendError(f"Unable to get entry, kratos replied with: {error}") from error
|
||||||
|
|
||||||
|
|
||||||
|
def __repr__(self):
|
||||||
|
return f"\"{self.name}\" <{self.email}>"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def uuid(self):
|
||||||
|
"""Gets the protected UUID propery"""
|
||||||
|
return self.__uuid
|
||||||
|
|
||||||
|
def save(self):
|
||||||
|
"""Saves this object into the kratos backend database. If the object
|
||||||
|
is new, it will create, otherwise update an entry.
|
||||||
|
:raise: BackendError is an error with Kratos happened.
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Traits are the "profile" values we will set, kratos will complain on
|
||||||
|
# empty values, so we check if "name" is set and only add it if so.
|
||||||
|
traits = {'email':self.email}
|
||||||
|
|
||||||
|
if self.name:
|
||||||
|
traits['name'] = self.name
|
||||||
|
|
||||||
|
# If we have a UUID, we are updating
|
||||||
|
if self.__uuid:
|
||||||
|
body = AdminUpdateIdentityBody(
|
||||||
|
schema_id="default",
|
||||||
|
state=self.state,
|
||||||
|
traits=traits,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
api_response = self.api.admin_update_identity(self.__uuid,
|
||||||
|
admin_update_identity_body=body)
|
||||||
|
except KratosApiException as error:
|
||||||
|
raise BackendError(f"Unable to save entry, kratos replied with:{error}") from error
|
||||||
|
else:
|
||||||
|
|
||||||
|
body = AdminCreateIdentityBody(
|
||||||
|
schema_id="default",
|
||||||
|
traits=traits,
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
# Create an Identity
|
||||||
|
api_response = self.api.admin_create_identity(
|
||||||
|
admin_create_identity_body=body)
|
||||||
|
if api_response.id:
|
||||||
|
self.__uuid = api_response.id
|
||||||
|
except KratosApiException as error:
|
||||||
|
raise BackendError(f"Unable to save entry, kratos replied with:{error}") from error
|
||||||
|
|
||||||
|
def delete(self):
|
||||||
|
"""Deletes the object from kratos
|
||||||
|
:raise: BackendError if Krator API call fails
|
||||||
|
"""
|
||||||
|
if self.__uuid:
|
||||||
|
try:
|
||||||
|
self.api.admin_delete_identity(self.__uuid)
|
||||||
|
return True
|
||||||
|
except KratosApiException as error:
|
||||||
|
raise BackendError(
|
||||||
|
f"Unable to delete entry, kratos replied with: {error}"
|
||||||
|
) from error
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def find_by_email(api, email):
|
||||||
|
"""Queries Kratos to find kratos ID for this given identifier
|
||||||
|
:param api: Kratos ADMIN API Object
|
||||||
|
:param email: Identifier to look for
|
||||||
|
:return: Return none or string with ID
|
||||||
|
"""
|
||||||
|
|
||||||
|
kratos_id = None
|
||||||
|
|
||||||
|
# Get out user ID by iterating over all available IDs
|
||||||
|
data = api.admin_list_identities()
|
||||||
|
for kratos_obj in data.value:
|
||||||
|
# Unique identifier we use
|
||||||
|
if kratos_obj.traits['email'] == email:
|
||||||
|
kratos_id = str(kratos_obj.id)
|
||||||
|
return KratosUser(api, kratos_id)
|
||||||
|
|
||||||
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def find_all(api):
|
||||||
|
"""Queries Kratos to find all kratos users and return them
|
||||||
|
as a list of KratosUser objects
|
||||||
|
:return: Return list
|
||||||
|
"""
|
||||||
|
|
||||||
|
kratos_id = None
|
||||||
|
return_list = []
|
||||||
|
# Get out user ID by iterating over all available IDs
|
||||||
|
data = api.admin_list_identities()
|
||||||
|
for kratos_obj in data.value:
|
||||||
|
kratos_id = str(kratos_obj.id)
|
||||||
|
return_list.append(KratosUser(api, kratos_id))
|
||||||
|
|
||||||
|
return return_list
|
||||||
|
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def extract_cookies(cookies):
|
||||||
|
"""Extract session and CSRF cookie from a list of cookies.
|
||||||
|
|
||||||
|
Iterate over a list of cookies and extract the session
|
||||||
|
cookies required for Kratos User Panel UI
|
||||||
|
|
||||||
|
:param cookies: str[], list of cookies
|
||||||
|
:return: Cookies concatenated as string
|
||||||
|
:rtype: str
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Find kratos session cookie & csrf
|
||||||
|
cookie_csrf = None
|
||||||
|
cookie_session = None
|
||||||
|
for cookie in cookies:
|
||||||
|
search = re.match(r'ory_kratos_session=([^;]*);.*$', cookie)
|
||||||
|
if search:
|
||||||
|
cookie_session = "ory_kratos_session=" + search.group(1)
|
||||||
|
search = re.match(r'(csrf_token[^;]*);.*$', cookie)
|
||||||
|
if search:
|
||||||
|
cookie_csrf = search.group(1)
|
||||||
|
|
||||||
|
if not cookie_csrf or not cookie_session:
|
||||||
|
raise BackendError("Flow started, but expected cookies not found")
|
||||||
|
|
||||||
|
# Combined the relevant cookies
|
||||||
|
cookie = cookie_csrf + "; " + cookie_session
|
||||||
|
return cookie
|
||||||
|
|
||||||
|
|
||||||
|
def get_recovery_link(self):
|
||||||
|
"""Call the kratos API to create a recovery URL for a kratos ID
|
||||||
|
:param: api Kratos ADMIN API Object
|
||||||
|
:param: kratos_id UUID of kratos object
|
||||||
|
:return: Return none or string with recovery URL
|
||||||
|
"""
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Create body request to get recovery link with admin API
|
||||||
|
body = AdminCreateSelfServiceRecoveryLinkBody(
|
||||||
|
expires_in="15m",
|
||||||
|
identity_id=self.__uuid
|
||||||
|
)
|
||||||
|
|
||||||
|
# Get recovery link from admin API
|
||||||
|
call = self.api.admin_create_self_service_recovery_link(
|
||||||
|
admin_create_self_service_recovery_link_body=body)
|
||||||
|
|
||||||
|
url = call.recovery_link
|
||||||
|
except KratosApiException:
|
||||||
|
return None
|
||||||
|
return url
|
||||||
|
|
||||||
|
def ui_set_password(self, api_url, recovery_url, password):
|
||||||
|
"""Follow a Kratos UI sequence to set password
|
||||||
|
Kratos does not provide an interface to set a password directly. However
|
||||||
|
we still can set a password by following the UI sequence. To so so we
|
||||||
|
to follow the steps which are normally done in a browser once someone
|
||||||
|
clicks the recovery link.
|
||||||
|
:param: api_url URL to public endpoint of API
|
||||||
|
:param: recovery_url Recovery URL as generated by Kratos
|
||||||
|
:param: password Password
|
||||||
|
:raise: Exception with error message as first argument
|
||||||
|
:return: boolean True on success, False on failure (usualy password
|
||||||
|
to simple)
|
||||||
|
"""
|
||||||
|
# Step 1: Open the recovery link and extract the cookies, as we need them
|
||||||
|
# for the next steps
|
||||||
|
try:
|
||||||
|
# We override the default Redirect handler with our custom handler to
|
||||||
|
# be able to catch the cookies.
|
||||||
|
opener = urllib.request.build_opener(RedirectFilter)
|
||||||
|
|
||||||
|
# We rewrite the URL we got. It can be we run this from an enviroment
|
||||||
|
# with different KRATUS_PUBLIC_URL API endpoint then kratos provide
|
||||||
|
# itself. For example in the case running as a job to create an admin
|
||||||
|
# account before TLS is setup/working
|
||||||
|
search = re.match(r'.*(self-service.recovery.flow.*)$', recovery_url)
|
||||||
|
if search:
|
||||||
|
recovery_url = api_url + search.group(1)
|
||||||
|
else:
|
||||||
|
raise BackendError('Did not find recovery flow')
|
||||||
|
opener.open(recovery_url)
|
||||||
|
# If we do not have a 2xx status, urllib throws an error, as we "stopped"
|
||||||
|
# at our redirect, we expect a 3xx status
|
||||||
|
except urllib.error.HTTPError as http_error:
|
||||||
|
# Kratos pre-0.8 returned 302, kratos 0.8 returns 303
|
||||||
|
if http_error.status in (302, 303):
|
||||||
|
# Get the cookie and redirect location from the response
|
||||||
|
# headers
|
||||||
|
cookies = http_error.headers.get_all('Set-Cookie')
|
||||||
|
url = http_error.headers.get('Location')
|
||||||
|
else:
|
||||||
|
raise BackendError('Unable to fetch recovery link') from http_error
|
||||||
|
else:
|
||||||
|
raise BackendError('Recovery link returned unexpected data')
|
||||||
|
|
||||||
|
# Step 2: Extract cookies and data for next step. We expect to have an
|
||||||
|
# authorized session now. We need the cookies for followup calls
|
||||||
|
# to make changes to the account (set password)
|
||||||
|
|
||||||
|
# Get flow id
|
||||||
|
search = re.match(r'.*\?flow=(.*)', url)
|
||||||
|
if search:
|
||||||
|
flow = search.group(1)
|
||||||
|
else:
|
||||||
|
raise BackendError('No Flow ID found for recovery sequence')
|
||||||
|
|
||||||
|
# Extract cookies with helper function
|
||||||
|
cookie = self.extract_cookies(cookies)
|
||||||
|
|
||||||
|
# Step 3: Get the "UI", kratos expect us to call the API to get the UI
|
||||||
|
# elements which contains the CSRF token, which is needed when
|
||||||
|
# posting the password data
|
||||||
|
try:
|
||||||
|
url = api_url + "/self-service/settings/flows?id=" + flow
|
||||||
|
|
||||||
|
req = Request(url, headers={'Cookie':cookie})
|
||||||
|
opener = urllib.request.build_opener()
|
||||||
|
|
||||||
|
# Execute the request, read the data, decode the JSON, get the
|
||||||
|
# right CSRF token out of the decoded JSON
|
||||||
|
obj = json.loads(opener.open(req).read())
|
||||||
|
csrf_token = obj['ui']['nodes'][0]['attributes']['value']
|
||||||
|
|
||||||
|
except Exception as error:
|
||||||
|
raise BackendError("Unable to get password reset UI") from error
|
||||||
|
|
||||||
|
|
||||||
|
# Step 4: Post out password
|
||||||
|
url = api_url + "self-service/settings?flow=" + flow
|
||||||
|
|
||||||
|
# Create POST data as form data
|
||||||
|
data = {
|
||||||
|
'method': 'password',
|
||||||
|
'password': password,
|
||||||
|
'csrf_token': csrf_token
|
||||||
|
}
|
||||||
|
data = urllib.parse.urlencode(data)
|
||||||
|
data = data.encode('ascii')
|
||||||
|
|
||||||
|
# POST the new password
|
||||||
|
try:
|
||||||
|
req = Request(url, data = data, headers={'Cookie':cookie}, method="POST")
|
||||||
|
opener = urllib.request.build_opener(RedirectFilter)
|
||||||
|
opener.open(req)
|
||||||
|
# If we do not have a 2xx status, urllib throws an error, as we "stopped"
|
||||||
|
# at our redirect, we expect a 3xx status
|
||||||
|
except urllib.error.HTTPError as http_error:
|
||||||
|
# Kratos pre-0.8 returned 302, kratos 0.8 returns 303
|
||||||
|
if http_error.status in (302, 303):
|
||||||
|
# Kratos only sends HTTP codes after our submission. We should
|
||||||
|
# now call the `settings` endpoint to see if our call
|
||||||
|
# succeeded, or else, if there are any messages about why it
|
||||||
|
# failed
|
||||||
|
try:
|
||||||
|
url = api_url + "/self-service/settings/flows?id=" + flow
|
||||||
|
|
||||||
|
req = Request(url, headers={'Cookie':cookie, "Accept": "application/json"})
|
||||||
|
opener = urllib.request.build_opener()
|
||||||
|
|
||||||
|
# Execute the request, read the data, decode the JSON
|
||||||
|
obj = json.loads(opener.open(req).read())
|
||||||
|
# If the 'state' has changed to 'success', the password was
|
||||||
|
# set successfully
|
||||||
|
if obj['state'] == 'success':
|
||||||
|
return True
|
||||||
|
# Failure: we check if there are error messages
|
||||||
|
for node in obj['ui']['nodes']:
|
||||||
|
if node['messages']:
|
||||||
|
print(f"Problems with field '{node['meta']['label']['text']}':")
|
||||||
|
for message in node['messages']:
|
||||||
|
print(message['text'])
|
||||||
|
raise BackendError("Password not set") from http_error
|
||||||
|
except Exception as error:
|
||||||
|
raise BackendError("Unable to get password reset UI") from error
|
||||||
|
return False
|
||||||
|
raise BackendError("Unable to set password by submitting form")
|
||||||
|
|
||||||
|
# Pylint complains about app not used. That is correct, but we will use that
|
||||||
|
# in the future. Ignore this error
|
||||||
|
# pylint: disable=unused-argument
|
||||||
|
def get_claims(self, app, roles, mapping=None) -> Dict[str, Dict[str, str]]:
|
||||||
|
"""Create openID Connect token
|
||||||
|
Use the userdata stored in the user object to create an OpenID Connect token.
|
||||||
|
The token returned by this function can be passed to Hydra,
|
||||||
|
which will store it and serve it to OpenID Connect Clients to retrieve user information.
|
||||||
|
If you need to relabel a field pass an array of tuples to mapping.
|
||||||
|
Example: getClaims('nextcloud', mapping=[("name", "username"),("roles", "groups")])
|
||||||
|
|
||||||
|
Attributes:
|
||||||
|
appname - Name or ID of app to connect to
|
||||||
|
roles - List of roles to add to the `stackspin_roles` claim
|
||||||
|
mapping - Mapping of the fields
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
OpenID Connect token of type dict
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Name should be set, however, we do not enforce this yet.
|
||||||
|
# if somebody does not set it's name, we use the email address
|
||||||
|
# as name
|
||||||
|
if self.name:
|
||||||
|
name = self.name
|
||||||
|
else:
|
||||||
|
name = self.email
|
||||||
|
|
||||||
|
if self.username:
|
||||||
|
username = self.username
|
||||||
|
else:
|
||||||
|
username = self.email
|
||||||
|
|
||||||
|
token = {
|
||||||
|
"name": name,
|
||||||
|
"preferred_username": username,
|
||||||
|
"email": self.email,
|
||||||
|
"stackspin_roles": roles,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
# Relabel field names
|
||||||
|
if mapping:
|
||||||
|
for old_field_name, new_field_name in mapping:
|
||||||
|
token[new_field_name] = token[old_field_name]
|
||||||
|
del token[old_field_name]
|
||||||
|
|
||||||
|
return dict(id_token=token)
|
384
backend/helpers/kubernetes.py
Normal file
384
backend/helpers/kubernetes.py
Normal file
|
@ -0,0 +1,384 @@
|
||||||
|
"""
|
||||||
|
List of functions to get data from Flux Kustomizations and Helmreleases
|
||||||
|
"""
|
||||||
|
import crypt
|
||||||
|
import secrets
|
||||||
|
import string
|
||||||
|
|
||||||
|
import jinja2
|
||||||
|
import yaml
|
||||||
|
from kubernetes import client, config
|
||||||
|
from kubernetes.client import api_client
|
||||||
|
from kubernetes.client.exceptions import ApiException
|
||||||
|
from kubernetes.utils import create_from_yaml
|
||||||
|
from kubernetes.utils.create_from_yaml import FailToCreateError
|
||||||
|
from flask import current_app
|
||||||
|
|
||||||
|
from config import LOAD_INCLUSTER_CONFIG
|
||||||
|
|
||||||
|
# Load the kube config once
|
||||||
|
#
|
||||||
|
# By default this loads whatever we define in the `KUBECONFIG` env variable,
|
||||||
|
# otherwise loads the config from default locations, similar to what kubectl
|
||||||
|
# does.
|
||||||
|
if LOAD_INCLUSTER_CONFIG:
|
||||||
|
config.load_incluster_config()
|
||||||
|
else:
|
||||||
|
config.load_kube_config()
|
||||||
|
|
||||||
|
def create_variables_secret(app_slug, variables_filepath):
|
||||||
|
"""Checks if a variables secret for app_name already exists, generates it if necessary.
|
||||||
|
|
||||||
|
If a secret already exists, loops through keys from the template, and adds
|
||||||
|
values for keys that miss in the Kubernetes secret, but are available in
|
||||||
|
the template.
|
||||||
|
|
||||||
|
:param app_slug: The slug of the app, used in the oauth secrets
|
||||||
|
:type app_slug: string
|
||||||
|
:param variables_filepath: The path to an existing jinja2 template
|
||||||
|
:type variables_filepath: string
|
||||||
|
:return: returns True, unless an exception gets raised by the Kubernetes API
|
||||||
|
:rtype: boolean
|
||||||
|
"""
|
||||||
|
new_secret_dict = read_template_to_dict(
|
||||||
|
variables_filepath,
|
||||||
|
{"app": app_slug})
|
||||||
|
secret_name, secret_namespace = get_secret_metadata(new_secret_dict)
|
||||||
|
current_secret_data = get_kubernetes_secret_data(
|
||||||
|
secret_name, secret_namespace
|
||||||
|
)
|
||||||
|
if current_secret_data is None:
|
||||||
|
# Create new secret
|
||||||
|
update_secret = False
|
||||||
|
elif current_secret_data.keys() != new_secret_dict["data"].keys():
|
||||||
|
# Update current secret with new keys
|
||||||
|
update_secret = True
|
||||||
|
current_app.logger.info(
|
||||||
|
f"Secret {secret_name} in namespace {secret_namespace}"
|
||||||
|
" already exists. Merging..."
|
||||||
|
)
|
||||||
|
# Merge dicts. Values from current_secret_data take precedence
|
||||||
|
new_secret_dict["data"] |= current_secret_data
|
||||||
|
else:
|
||||||
|
# Do Nothing
|
||||||
|
current_app.logger.info(
|
||||||
|
f"Secret {secret_name} in namespace {secret_namespace}"
|
||||||
|
" is already in a good state, doing nothing."
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
current_app.logger.info(
|
||||||
|
f"Storing secret {secret_name} in namespace"
|
||||||
|
f" {secret_namespace} in cluster."
|
||||||
|
)
|
||||||
|
store_kubernetes_secret(
|
||||||
|
new_secret_dict, secret_namespace, update=update_secret
|
||||||
|
)
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def get_secret_metadata(secret_dict):
|
||||||
|
"""
|
||||||
|
Returns secret name and namespace from metadata field in a yaml string.
|
||||||
|
|
||||||
|
:param secret_dict: Dictionary of the secret as returned by read_namespaced_secret
|
||||||
|
:type secret_dict: dict
|
||||||
|
:return: Tuple containing secret name and secret namespace
|
||||||
|
:rtype: tuple
|
||||||
|
"""
|
||||||
|
secret_name = secret_dict["metadata"]["name"]
|
||||||
|
# default namespace is flux-system, but other namespace can be
|
||||||
|
# provided in secret metadata
|
||||||
|
if "namespace" in secret_dict["metadata"]:
|
||||||
|
secret_namespace = secret_dict["metadata"]["namespace"]
|
||||||
|
else:
|
||||||
|
secret_namespace = "flux-system"
|
||||||
|
return secret_name, secret_namespace
|
||||||
|
|
||||||
|
|
||||||
|
def get_kubernetes_secret_data(secret_name, namespace):
|
||||||
|
"""
|
||||||
|
Get secret from Kubernetes
|
||||||
|
|
||||||
|
:param secret_name: Name of the secret
|
||||||
|
:type secret_name: string
|
||||||
|
:param namespace: Namespace of the secret
|
||||||
|
:type namespace: string
|
||||||
|
|
||||||
|
:return: The contents of a kubernetes secret or None if the secret does not exist.
|
||||||
|
:rtype: dict or None
|
||||||
|
"""
|
||||||
|
api_client_instance = api_client.ApiClient()
|
||||||
|
api_instance = client.CoreV1Api(api_client_instance)
|
||||||
|
try:
|
||||||
|
secret = api_instance.read_namespaced_secret(secret_name, namespace).data
|
||||||
|
except ApiException as ex:
|
||||||
|
# 404 is expected when the optional secret does not exist.
|
||||||
|
if ex.status != 404:
|
||||||
|
raise ex
|
||||||
|
return None
|
||||||
|
return secret
|
||||||
|
|
||||||
|
|
||||||
|
def get_kubernetes_config_map_data(config_map_name, namespace):
|
||||||
|
"""
|
||||||
|
Get ConfigMap from Kubernetes
|
||||||
|
|
||||||
|
:param config_map_name: Name of the ConfigMap
|
||||||
|
:type config_map_name: string
|
||||||
|
:param namespace: Namespace of the ConfigMap
|
||||||
|
:type namespace: string
|
||||||
|
|
||||||
|
:return: The contents of a kubernetes ConfigMap or None if the cm does not exist.
|
||||||
|
:rtype: dict or None
|
||||||
|
"""
|
||||||
|
api_instance = client.CoreV1Api()
|
||||||
|
try:
|
||||||
|
config_map = api_instance.read_namespaced_config_map(config_map_name, namespace).data
|
||||||
|
except ApiException as ex:
|
||||||
|
# 404 is expected when the optional secret does not exist.
|
||||||
|
if ex.status != 404:
|
||||||
|
raise ex
|
||||||
|
return None
|
||||||
|
return config_map
|
||||||
|
|
||||||
|
|
||||||
|
def store_kubernetes_secret(secret_dict, namespace, update=False):
|
||||||
|
"""
|
||||||
|
Stores either a new secret in the cluster, or updates an existing one.
|
||||||
|
|
||||||
|
:param secret_dict: Dictionary of the secret as returned by read_namespaced_secret
|
||||||
|
:type secret_dict: dict
|
||||||
|
:param namespace: Namespace of the secret
|
||||||
|
:type namespace: string
|
||||||
|
:param update: If True, use `patch_kubernetes_secret`,
|
||||||
|
otherwise use `create_from_yaml` (default: False)
|
||||||
|
:type update: boolean
|
||||||
|
|
||||||
|
:return: None
|
||||||
|
:rtype: None
|
||||||
|
"""
|
||||||
|
api_client_instance = api_client.ApiClient()
|
||||||
|
if update:
|
||||||
|
verb = "updated"
|
||||||
|
api_response = patch_kubernetes_secret(secret_dict, namespace)
|
||||||
|
else:
|
||||||
|
verb = "created"
|
||||||
|
try:
|
||||||
|
api_response = create_from_yaml(
|
||||||
|
api_client_instance,
|
||||||
|
yaml_objects=[secret_dict],
|
||||||
|
namespace=namespace
|
||||||
|
)
|
||||||
|
except FailToCreateError as ex:
|
||||||
|
current_app.logger.info(f"Secret not created because of exception {ex}")
|
||||||
|
raise ex
|
||||||
|
current_app.logger.info(f"Secret {verb} with api response: {api_response}")
|
||||||
|
|
||||||
|
|
||||||
|
def store_kustomization(kustomization_template_filepath, app_slug):
|
||||||
|
"""
|
||||||
|
Add a kustomization that installs app {app_slug} to the cluster.
|
||||||
|
|
||||||
|
:param kustomization_template_filepath: Path to the template that describes
|
||||||
|
the kustomization. The template should have an `{{ app }}` entry.
|
||||||
|
:type kustomization_template_filepath: string
|
||||||
|
:param app_slug: Slug for the app, used to replace `{{ app }}` in the
|
||||||
|
template
|
||||||
|
:return: True on success
|
||||||
|
:rtype: boolean
|
||||||
|
"""
|
||||||
|
kustomization_dict = read_template_to_dict(kustomization_template_filepath,
|
||||||
|
{"app": app_slug})
|
||||||
|
custom_objects_api = client.CustomObjectsApi()
|
||||||
|
try:
|
||||||
|
api_response = custom_objects_api.create_namespaced_custom_object(
|
||||||
|
group="kustomize.toolkit.fluxcd.io",
|
||||||
|
version="v1beta2",
|
||||||
|
namespace="flux-system",
|
||||||
|
plural="kustomizations",
|
||||||
|
body=kustomization_dict)
|
||||||
|
except FailToCreateError as ex:
|
||||||
|
current_app.logger.info(
|
||||||
|
f"Could not create {app_slug} Kustomization because of exception {ex}")
|
||||||
|
raise ex
|
||||||
|
current_app.logger.debug(f"Kustomization created with api response: {api_response}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
def delete_kustomization(kustomization_name):
|
||||||
|
"""
|
||||||
|
Deletes a kustomization.
|
||||||
|
|
||||||
|
Note that if the kustomization has `prune: true` in its spec, this will
|
||||||
|
trigger deletion of other elements generated by the Kustomizartion. See
|
||||||
|
App.uninstall() to learn what implications this has for what will and will
|
||||||
|
not be deleted by the kustomize-controller.
|
||||||
|
|
||||||
|
:param kustomization_name: name of the kustomization to delete
|
||||||
|
:type kustomization_name: string
|
||||||
|
|
||||||
|
:return: Response of delete API call
|
||||||
|
:rtype: dict
|
||||||
|
"""
|
||||||
|
custom_objects_api = client.CustomObjectsApi()
|
||||||
|
body = client.V1DeleteOptions()
|
||||||
|
try:
|
||||||
|
api_response = custom_objects_api.delete_namespaced_custom_object(
|
||||||
|
group="kustomize.toolkit.fluxcd.io",
|
||||||
|
version="v1beta2",
|
||||||
|
namespace="flux-system",
|
||||||
|
plural="kustomizations",
|
||||||
|
name=kustomization_name,
|
||||||
|
body=body)
|
||||||
|
except ApiException as ex:
|
||||||
|
current_app.logger.info(
|
||||||
|
f"Could not delete {kustomization_name} Kustomization because of exception {ex}")
|
||||||
|
raise ex
|
||||||
|
current_app.logger.debug(f"Kustomization deleted with api response: {api_response}")
|
||||||
|
return api_response
|
||||||
|
|
||||||
|
|
||||||
|
def read_template_to_dict(template_filepath, template_globals):
|
||||||
|
"""
|
||||||
|
Reads a Jinja2 template that contains yaml and turns it into a dict.
|
||||||
|
|
||||||
|
:param template_filepath: The path to an existing Jinja2 template
|
||||||
|
:type template_filepath: string
|
||||||
|
:param template_globals: The variables substituted in the template
|
||||||
|
:type template_globals: dict
|
||||||
|
:return: dict, or None if anything fails
|
||||||
|
"""
|
||||||
|
env = jinja2.Environment(
|
||||||
|
extensions=["jinja2_base64_filters.Base64Filters"])
|
||||||
|
env.filters["generate_password"] = generate_password
|
||||||
|
# Check if k8s secret already exists, if not, generate it
|
||||||
|
with open(template_filepath, encoding="UTF-8") as template_file:
|
||||||
|
lines = template_file.read()
|
||||||
|
templated_dict = yaml.safe_load(
|
||||||
|
env.from_string(lines, globals=template_globals).render()
|
||||||
|
)
|
||||||
|
return templated_dict
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def patch_kubernetes_secret(secret_dict, namespace):
|
||||||
|
"""
|
||||||
|
Patches secret in the cluster with new data.
|
||||||
|
|
||||||
|
Warning: currently ignores everything that's not in secret_dict["data"]
|
||||||
|
|
||||||
|
:param secret_dict: Dictionary of the secret as returned by read_namespaced_secret
|
||||||
|
:type secret_dict: dict
|
||||||
|
:param namespace: Namespace of the secret
|
||||||
|
:type namespace: string
|
||||||
|
:return: Response of the patch API call
|
||||||
|
"""
|
||||||
|
api_client_instance = api_client.ApiClient()
|
||||||
|
api_instance = client.CoreV1Api(api_client_instance)
|
||||||
|
name = secret_dict["metadata"]["name"]
|
||||||
|
body = {}
|
||||||
|
body["data"] = secret_dict["data"]
|
||||||
|
return api_instance.patch_namespaced_secret(name, namespace, body)
|
||||||
|
|
||||||
|
|
||||||
|
def generate_password(length):
|
||||||
|
"""
|
||||||
|
Generates a password with letters and digits.
|
||||||
|
|
||||||
|
:param length: The amount of characters in the password
|
||||||
|
:type length: int
|
||||||
|
:return: Generated password
|
||||||
|
:rtype: string
|
||||||
|
"""
|
||||||
|
length = int(length)
|
||||||
|
password = "".join((secrets.choice(string.ascii_letters + string.digits)
|
||||||
|
for i in range(length)))
|
||||||
|
return password
|
||||||
|
|
||||||
|
|
||||||
|
def gen_htpasswd(user, password):
|
||||||
|
"""
|
||||||
|
Generate htpasswd entry for user with password.
|
||||||
|
|
||||||
|
:param user: Username used in the htpasswd entry
|
||||||
|
:type user: string
|
||||||
|
:param password: Password for the user, will get encrypted.
|
||||||
|
:type password: string
|
||||||
|
:return: htpassword line entry
|
||||||
|
:rtype: string
|
||||||
|
"""
|
||||||
|
return f"{user}:{crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512))}"
|
||||||
|
|
||||||
|
|
||||||
|
def get_all_kustomizations(namespace='flux-system'):
|
||||||
|
"""
|
||||||
|
Returns all flux kustomizations in a namespace.
|
||||||
|
:param namespace: namespace that contains kustomizations. Default: `flux-system`
|
||||||
|
:type namespace: str
|
||||||
|
:return: 'items' in dict returned by CustomObjectsApi.list_namespaced_custom_object()
|
||||||
|
:rtype: dict[]
|
||||||
|
"""
|
||||||
|
api = client.CustomObjectsApi()
|
||||||
|
api_response = api.list_namespaced_custom_object(
|
||||||
|
group="kustomize.toolkit.fluxcd.io",
|
||||||
|
version="v1beta1",
|
||||||
|
plural="kustomizations",
|
||||||
|
namespace=namespace,
|
||||||
|
)
|
||||||
|
return api_response
|
||||||
|
|
||||||
|
|
||||||
|
def get_all_helmreleases(namespace='stackspin', label_selector=""):
|
||||||
|
"""
|
||||||
|
Lists all helmreleases in a certain namespace (stackspin by default)
|
||||||
|
|
||||||
|
:param namespace: namespace that contains helmreleases. Default: `stackspin-apps`
|
||||||
|
:type namespace: str
|
||||||
|
:param label_selector: a label selector to limit the list (optional)
|
||||||
|
:type label_selector: str
|
||||||
|
|
||||||
|
:return: List of helmreleases
|
||||||
|
:rtype: dict[]
|
||||||
|
"""
|
||||||
|
api_instance = client.CustomObjectsApi()
|
||||||
|
|
||||||
|
try:
|
||||||
|
api_response = api_instance.list_namespaced_custom_object(
|
||||||
|
group="helm.toolkit.fluxcd.io",
|
||||||
|
version="v2beta1",
|
||||||
|
namespace=namespace,
|
||||||
|
plural="helmreleases",
|
||||||
|
label_selector=label_selector)
|
||||||
|
except ApiException as error:
|
||||||
|
if error.status == 404:
|
||||||
|
return None
|
||||||
|
# Raise all non-404 errors
|
||||||
|
raise error
|
||||||
|
return api_response['items']
|
||||||
|
|
||||||
|
|
||||||
|
def get_kustomization(name, namespace='flux-system'):
|
||||||
|
"""
|
||||||
|
Returns all info of a Flux kustomization with name 'name'
|
||||||
|
|
||||||
|
:param name: Name of the kustomizatoin
|
||||||
|
:type name: string
|
||||||
|
:param namespace: Namespace of the kustomization
|
||||||
|
:type namespace: string
|
||||||
|
:return: kustomization as returned by the API
|
||||||
|
:rtype: dict
|
||||||
|
"""
|
||||||
|
api = client.CustomObjectsApi()
|
||||||
|
try:
|
||||||
|
resource = api.get_namespaced_custom_object(
|
||||||
|
group="kustomize.toolkit.fluxcd.io",
|
||||||
|
version="v1beta1",
|
||||||
|
name=name,
|
||||||
|
namespace=namespace,
|
||||||
|
plural="kustomizations",
|
||||||
|
)
|
||||||
|
except client.exceptions.ApiException as error:
|
||||||
|
if error.status == 404:
|
||||||
|
return None
|
||||||
|
# Raise all non-404 errors
|
||||||
|
raise error
|
||||||
|
return resource
|
1
backend/migrations/README
Normal file
1
backend/migrations/README
Normal file
|
@ -0,0 +1 @@
|
||||||
|
Single-database configuration for Flask.
|
50
backend/migrations/alembic.ini
Normal file
50
backend/migrations/alembic.ini
Normal file
|
@ -0,0 +1,50 @@
|
||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# template used to generate migration files
|
||||||
|
# file_template = %%(rev)s_%%(slug)s
|
||||||
|
|
||||||
|
# set to 'true' to run the environment during
|
||||||
|
# the 'revision' command, regardless of autogenerate
|
||||||
|
# revision_environment = false
|
||||||
|
|
||||||
|
|
||||||
|
# Logging configuration
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic,flask_migrate
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARN
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARN
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[logger_flask_migrate]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = flask_migrate
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
91
backend/migrations/env.py
Normal file
91
backend/migrations/env.py
Normal file
|
@ -0,0 +1,91 @@
|
||||||
|
from __future__ import with_statement
|
||||||
|
|
||||||
|
import logging
|
||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from flask import current_app
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
# this is the Alembic Config object, which provides
|
||||||
|
# access to the values within the .ini file in use.
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
# Interpret the config file for Python logging.
|
||||||
|
# This line sets up loggers basically.
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
logger = logging.getLogger('alembic.env')
|
||||||
|
|
||||||
|
# add your model's MetaData object here
|
||||||
|
# for 'autogenerate' support
|
||||||
|
# from myapp import mymodel
|
||||||
|
# target_metadata = mymodel.Base.metadata
|
||||||
|
config.set_main_option(
|
||||||
|
'sqlalchemy.url',
|
||||||
|
str(current_app.extensions['migrate'].db.get_engine().url).replace(
|
||||||
|
'%', '%%'))
|
||||||
|
target_metadata = current_app.extensions['migrate'].db.metadata
|
||||||
|
|
||||||
|
# other values from the config, defined by the needs of env.py,
|
||||||
|
# can be acquired:
|
||||||
|
# my_important_option = config.get_main_option("my_important_option")
|
||||||
|
# ... etc.
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline():
|
||||||
|
"""Run migrations in 'offline' mode.
|
||||||
|
|
||||||
|
This configures the context with just a URL
|
||||||
|
and not an Engine, though an Engine is acceptable
|
||||||
|
here as well. By skipping the Engine creation
|
||||||
|
we don't even need a DBAPI to be available.
|
||||||
|
|
||||||
|
Calls to context.execute() here emit the given string to the
|
||||||
|
script output.
|
||||||
|
|
||||||
|
"""
|
||||||
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
|
context.configure(
|
||||||
|
url=url, target_metadata=target_metadata, literal_binds=True
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online():
|
||||||
|
"""Run migrations in 'online' mode.
|
||||||
|
|
||||||
|
In this scenario we need to create an Engine
|
||||||
|
and associate a connection with the context.
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
# this callback is used to prevent an auto-migration from being generated
|
||||||
|
# when there are no changes to the schema
|
||||||
|
# reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html
|
||||||
|
def process_revision_directives(context, revision, directives):
|
||||||
|
if getattr(config.cmd_opts, 'autogenerate', False):
|
||||||
|
script = directives[0]
|
||||||
|
if script.upgrade_ops.is_empty():
|
||||||
|
directives[:] = []
|
||||||
|
logger.info('No changes in schema detected.')
|
||||||
|
|
||||||
|
connectable = current_app.extensions['migrate'].db.get_engine()
|
||||||
|
|
||||||
|
with connectable.connect() as connection:
|
||||||
|
context.configure(
|
||||||
|
connection=connection,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
process_revision_directives=process_revision_directives,
|
||||||
|
**current_app.extensions['migrate'].configure_args
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
24
backend/migrations/script.py.mako
Normal file
24
backend/migrations/script.py.mako
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = ${repr(up_revision)}
|
||||||
|
down_revision = ${repr(down_revision)}
|
||||||
|
branch_labels = ${repr(branch_labels)}
|
||||||
|
depends_on = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
${downgrades if downgrades else "pass"}
|
46
backend/migrations/versions/27761560bbcb_.py
Normal file
46
backend/migrations/versions/27761560bbcb_.py
Normal file
|
@ -0,0 +1,46 @@
|
||||||
|
"""empty message
|
||||||
|
|
||||||
|
Revision ID: 27761560bbcb
|
||||||
|
Revises:
|
||||||
|
Create Date: 2021-12-21 06:07:14.857940
|
||||||
|
|
||||||
|
"""
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = "27761560bbcb"
|
||||||
|
down_revision = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table(
|
||||||
|
"app",
|
||||||
|
sa.Column("id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("name", sa.String(length=64), nullable=True),
|
||||||
|
sa.Column("slug", sa.String(length=64), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
sa.UniqueConstraint("slug"),
|
||||||
|
)
|
||||||
|
op.create_table(
|
||||||
|
"app_role",
|
||||||
|
sa.Column("user_id", sa.String(length=64), nullable=False),
|
||||||
|
sa.Column("app_id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("role", sa.String(length=64), nullable=True),
|
||||||
|
sa.ForeignKeyConstraint(
|
||||||
|
["app_id"],
|
||||||
|
["app.id"],
|
||||||
|
),
|
||||||
|
sa.PrimaryKeyConstraint("user_id", "app_id"),
|
||||||
|
)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_table("app_role")
|
||||||
|
op.drop_table("app")
|
||||||
|
# ### end Alembic commands ###
|
|
@ -0,0 +1,25 @@
|
||||||
|
"""add-velero-as-app
|
||||||
|
|
||||||
|
Revision ID: 3fa0c38ea1ac
|
||||||
|
Revises: e08df0bef76f
|
||||||
|
Create Date: 2022-10-13 09:40:44.290319
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '3fa0c38ea1ac'
|
||||||
|
down_revision = 'e08df0bef76f'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# Add monitoring app
|
||||||
|
op.execute(f'INSERT IGNORE INTO app (`name`, `slug`) VALUES ("Velero","velero")')
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
pass
|
|
@ -0,0 +1,48 @@
|
||||||
|
"""convert role column to table
|
||||||
|
|
||||||
|
Revision ID: 5f462d2d9d25
|
||||||
|
Revises: 27761560bbcb
|
||||||
|
Create Date: 2022-04-13 15:00:27.182898
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy.dialects import mysql
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = "5f462d2d9d25"
|
||||||
|
down_revision = "27761560bbcb"
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
role_table = op.create_table(
|
||||||
|
"role",
|
||||||
|
sa.Column("id", sa.Integer(), nullable=False),
|
||||||
|
sa.Column("name", sa.String(length=64), nullable=True),
|
||||||
|
sa.PrimaryKeyConstraint("id"),
|
||||||
|
)
|
||||||
|
op.add_column("app_role", sa.Column("role_id", sa.Integer(), nullable=True))
|
||||||
|
op.create_foreign_key(None, "app_role", "role", ["role_id"], ["id"])
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
# Insert default role "admin" as ID 1
|
||||||
|
op.execute(sa.insert(role_table).values(id=1,name="admin"))
|
||||||
|
# Set role_id 1 to all current "admin" users
|
||||||
|
op.execute("UPDATE app_role SET role_id = 1 WHERE role = 'admin'")
|
||||||
|
|
||||||
|
# Drop old column
|
||||||
|
op.drop_column("app_role", "role")
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.add_column(
|
||||||
|
"app_role", sa.Column("role", mysql.VARCHAR(length=64), nullable=True)
|
||||||
|
)
|
||||||
|
op.drop_constraint(None, "app_role", type_="foreignkey")
|
||||||
|
op.drop_column("app_role", "role_id")
|
||||||
|
op.drop_table("role")
|
||||||
|
# ### end Alembic commands ###
|
76
backend/migrations/versions/b514cca2d47b_add_user_role.py
Normal file
76
backend/migrations/versions/b514cca2d47b_add_user_role.py
Normal file
|
@ -0,0 +1,76 @@
|
||||||
|
"""update apps and add 'user' and 'no access' role
|
||||||
|
|
||||||
|
Revision ID: b514cca2d47b
|
||||||
|
Revises: 5f462d2d9d25
|
||||||
|
Create Date: 2022-06-08 17:24:51.305129
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'b514cca2d47b'
|
||||||
|
down_revision = '5f462d2d9d25'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
# Check and update app table in DB
|
||||||
|
apps = {
|
||||||
|
"dashboard": "Dashboard",
|
||||||
|
"wekan": "Wekan",
|
||||||
|
"wordpress": "WordPress",
|
||||||
|
"nextcloud": "Nextcloud",
|
||||||
|
"zulip": "Zulip"
|
||||||
|
}
|
||||||
|
# app table
|
||||||
|
app_table = sa.table('app', sa.column('id', sa.Integer), sa.column(
|
||||||
|
'name', sa.String), sa.column('slug', sa.String))
|
||||||
|
|
||||||
|
existing_apps = op.get_bind().execute(app_table.select()).fetchall()
|
||||||
|
existing_app_slugs = [app['slug'] for app in existing_apps]
|
||||||
|
for app_slug in apps.keys():
|
||||||
|
if app_slug in existing_app_slugs:
|
||||||
|
op.execute(f'UPDATE app SET `name` = "{apps.get(app_slug)}" WHERE slug = "{app_slug}"')
|
||||||
|
else:
|
||||||
|
op.execute(f'INSERT INTO app (`name`, slug) VALUES ("{apps.get(app_slug)}","{app_slug}")')
|
||||||
|
|
||||||
|
# Fetch all apps including newly created
|
||||||
|
existing_apps = op.get_bind().execute(app_table.select()).fetchall()
|
||||||
|
# Insert role "user" as ID 2
|
||||||
|
op.execute("INSERT INTO `role` (id, `name`) VALUES (2, 'user')")
|
||||||
|
# Insert role "no access" as ID 3
|
||||||
|
op.execute("INSERT INTO `role` (id, `name`) VALUES (3, 'no access')")
|
||||||
|
# Set role_id 2 to all current "user" users which by have NULL role ID
|
||||||
|
op.execute("UPDATE app_role SET role_id = 2 WHERE role_id IS NULL")
|
||||||
|
|
||||||
|
# Add 'no access' role for all users that don't have any roles for specific apps
|
||||||
|
app_roles_table = sa.table('app_role', sa.column('user_id', sa.String), sa.column(
|
||||||
|
'app_id', sa.Integer), sa.column('role_id', sa.Integer))
|
||||||
|
|
||||||
|
app_ids = [app['id'] for app in existing_apps]
|
||||||
|
app_roles = op.get_bind().execute(app_roles_table.select()).fetchall()
|
||||||
|
user_ids = set([app_role['user_id'] for app_role in app_roles])
|
||||||
|
|
||||||
|
for user_id in user_ids:
|
||||||
|
existing_user_app_ids = [x['app_id'] for x in list(filter(lambda role: role['user_id'] == user_id, app_roles))]
|
||||||
|
missing_user_app_ids = [x for x in app_ids if x not in existing_user_app_ids]
|
||||||
|
|
||||||
|
if len(missing_user_app_ids) > 0:
|
||||||
|
values = [{'user_id': user_id, 'app_id': app_id, 'role_id': 3} for app_id in missing_user_app_ids]
|
||||||
|
op.bulk_insert(app_roles_table, values)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# Revert all users role_id to NULL where role is 'user'
|
||||||
|
op.execute("UPDATE app_role SET role_id = NULL WHERE role_id = 2")
|
||||||
|
# Delete role 'user' from roles
|
||||||
|
op.execute("DELETE FROM `role` WHERE id = 2")
|
||||||
|
|
||||||
|
# Delete all user app roles where role is 'no access' with role_id 3
|
||||||
|
op.execute("DELETE FROM app_role WHERE role_id = 3")
|
||||||
|
# Delete role 'no access' from roles
|
||||||
|
op.execute("DELETE FROM `role` WHERE id = 3")
|
33
backend/migrations/versions/e08df0bef76f_.py
Normal file
33
backend/migrations/versions/e08df0bef76f_.py
Normal file
|
@ -0,0 +1,33 @@
|
||||||
|
"""Add fields for external apps
|
||||||
|
|
||||||
|
Revision ID: e08df0bef76f
|
||||||
|
Revises: b514cca2d47b
|
||||||
|
Create Date: 2022-09-23 16:38:06.557307
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'e08df0bef76f'
|
||||||
|
down_revision = 'b514cca2d47b'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.add_column('app', sa.Column('external', sa.Boolean(), server_default='0', nullable=False))
|
||||||
|
op.add_column('app', sa.Column('url', sa.String(length=128), nullable=True))
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
# Add monitoring app
|
||||||
|
op.execute(f'INSERT IGNORE INTO app (`name`, `slug`) VALUES ("Monitoring","monitoring")')
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade():
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_column('app', 'url')
|
||||||
|
op.drop_column('app', 'external')
|
||||||
|
# ### end Alembic commands ###
|
26
backend/proxy/default.conf
Normal file
26
backend/proxy/default.conf
Normal file
|
@ -0,0 +1,26 @@
|
||||||
|
# Default server configuration
|
||||||
|
#
|
||||||
|
server {
|
||||||
|
listen 8081 default_server;
|
||||||
|
listen [::]:8081 default_server;
|
||||||
|
|
||||||
|
root /var/www/html;
|
||||||
|
|
||||||
|
index index.html;
|
||||||
|
|
||||||
|
server_name _;
|
||||||
|
|
||||||
|
# Flask app
|
||||||
|
location / {
|
||||||
|
proxy_pass http://flask_app:5000/;
|
||||||
|
proxy_redirect default;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
}
|
||||||
|
|
||||||
|
# Kratos Public
|
||||||
|
location /kratos/ {
|
||||||
|
proxy_pass http://kube_port_kratos_public:8080/;
|
||||||
|
proxy_redirect default;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
}
|
||||||
|
}
|
40
backend/requirements.txt
Normal file
40
backend/requirements.txt
Normal file
|
@ -0,0 +1,40 @@
|
||||||
|
attrs==21.4.0
|
||||||
|
black==22.1.0
|
||||||
|
certifi==2021.10.8
|
||||||
|
cffi==1.15.0
|
||||||
|
charset-normalizer==2.0.12
|
||||||
|
click==8.0.4
|
||||||
|
cryptography==36.0.2
|
||||||
|
Flask==2.0.3
|
||||||
|
Flask-Cors==3.0.10
|
||||||
|
flask-expects-json==1.7.0
|
||||||
|
Flask-JWT-Extended==4.3.1
|
||||||
|
gunicorn==20.1.0
|
||||||
|
idna==3.3
|
||||||
|
install==1.3.5
|
||||||
|
itsdangerous==2.1.1
|
||||||
|
jsonschema==4.4.0
|
||||||
|
Jinja2==3.0.3
|
||||||
|
jinja2-base64-filters==0.1.4
|
||||||
|
kubernetes==24.2.0
|
||||||
|
MarkupSafe==2.1.1
|
||||||
|
mypy-extensions==0.4.3
|
||||||
|
oauthlib==3.2.0
|
||||||
|
pathspec==0.9.0
|
||||||
|
platformdirs==2.5.1
|
||||||
|
pycparser==2.21
|
||||||
|
PyJWT==2.3.0
|
||||||
|
pyrsistent==0.18.1
|
||||||
|
regex==2022.3.15
|
||||||
|
requests==2.27.1
|
||||||
|
requests-oauthlib==1.3.1
|
||||||
|
six==1.16.0
|
||||||
|
tomli==1.2.3
|
||||||
|
typing-extensions==4.1.1
|
||||||
|
urllib3==1.26.8
|
||||||
|
Werkzeug==2.0.3
|
||||||
|
ory-kratos-client==0.9.0a2
|
||||||
|
pymysql
|
||||||
|
Flask-SQLAlchemy
|
||||||
|
hydra-client
|
||||||
|
Flask-Migrate
|
32
backend/run_app.sh
Executable file
32
backend/run_app.sh
Executable file
|
@ -0,0 +1,32 @@
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
export DATABASE_PASSWORD=$(kubectl get secret -n flux-system stackspin-single-sign-on-variables -o jsonpath --template '{.data.dashboard_database_password}' | base64 -d)
|
||||||
|
export DOMAIN=$(kubectl get secret -n flux-system stackspin-cluster-variables -o jsonpath --template '{.data.domain}' | base64 -d)
|
||||||
|
export HYDRA_CLIENT_SECRET=$(kubectl get secret -n flux-system stackspin-dashboard-local-oauth-variables -o jsonpath --template '{.data.client_secret}' | base64 -d)
|
||||||
|
export FLASK_SECRET_KEY=$(kubectl get secret -n flux-system stackspin-dashboard-variables -o jsonpath --template '{.data.backend_secret_key}' | base64 -d)
|
||||||
|
|
||||||
|
|
||||||
|
if [[ -z "$DATABASE_PASSWORD" ]]; then
|
||||||
|
echo "Could not find database password in stackspin-single-sign-on-variables secret"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -z "$DOMAIN" ]]; then
|
||||||
|
echo "Could not find domain name in stackspin-cluster-variables secret"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -z "$FLASK_SECRET_KEY" ]]; then
|
||||||
|
echo "Could not find backend_secret_key in stackspin-dashboard-variables secret"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -z "$HYDRA_CLIENT_SECRET" ]]; then
|
||||||
|
echo "Could not find client_secret in stackspin-dashboard-local-oauth-variables secret"
|
||||||
|
echo "make sure you add this secret following instructions in the dashboard-dev-overrides repository"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
KUBECTL_UID=${UID:-1001} KUBECTL_GID=${GID:-0} docker compose up
|
10
backend/web/__init__.py
Normal file
10
backend/web/__init__.py
Normal file
|
@ -0,0 +1,10 @@
|
||||||
|
import os
|
||||||
|
from flask import Blueprint
|
||||||
|
|
||||||
|
web = Blueprint(
|
||||||
|
"web",
|
||||||
|
__name__,
|
||||||
|
url_prefix="/web",
|
||||||
|
static_folder="static",
|
||||||
|
template_folder="templates",
|
||||||
|
)
|
1
backend/web/login/__init__.py
Normal file
1
backend/web/login/__init__.py
Normal file
|
@ -0,0 +1 @@
|
||||||
|
from .login import *
|
473
backend/web/login/login.py
Normal file
473
backend/web/login/login.py
Normal file
|
@ -0,0 +1,473 @@
|
||||||
|
"""Flask application which provides the interface of a login panel. The
|
||||||
|
application interacts with different backend, like the Kratos backend for users,
|
||||||
|
Hydra for OIDC sessions and MariaDB for application and role specifications.
|
||||||
|
The application provides also several command line options to interact with
|
||||||
|
the user entries in the database(s)"""
|
||||||
|
|
||||||
|
import urllib.parse
|
||||||
|
import urllib.request
|
||||||
|
import ast
|
||||||
|
|
||||||
|
import hydra_client
|
||||||
|
import ory_kratos_client
|
||||||
|
from ory_kratos_client.api import v0alpha2_api as kratos_api
|
||||||
|
from flask import abort, redirect, render_template, request, current_app
|
||||||
|
|
||||||
|
from database import db
|
||||||
|
from helpers import KratosUser
|
||||||
|
from config import *
|
||||||
|
from web import web
|
||||||
|
from areas.apps import AppRole, App
|
||||||
|
from areas.roles import RoleService
|
||||||
|
|
||||||
|
|
||||||
|
# This is a circular import and should be solved differently
|
||||||
|
# from app import db
|
||||||
|
|
||||||
|
# APIs
|
||||||
|
# Create HYDRA & KRATOS API interfaces
|
||||||
|
HYDRA = hydra_client.HydraAdmin(HYDRA_ADMIN_URL)
|
||||||
|
|
||||||
|
# Kratos has an admin and public end-point. We create an API for them
|
||||||
|
# both. The kratos implementation has bugs, which forces us to set
|
||||||
|
# the discard_unknown_keys to True.
|
||||||
|
kratos_admin_api_configuration = \
|
||||||
|
ory_kratos_client.Configuration(host=KRATOS_ADMIN_URL, discard_unknown_keys=True)
|
||||||
|
KRATOS_ADMIN = \
|
||||||
|
kratos_api.V0alpha2Api(ory_kratos_client.ApiClient(kratos_admin_api_configuration))
|
||||||
|
|
||||||
|
kratos_public_api_configuration = \
|
||||||
|
ory_kratos_client.Configuration(host=KRATOS_PUBLIC_URL, discard_unknown_keys=True)
|
||||||
|
KRATOS_PUBLIC = \
|
||||||
|
kratos_api.V0alpha2Api(ory_kratos_client.ApiClient(kratos_public_api_configuration))
|
||||||
|
ADMIN_ROLE_ID = 1
|
||||||
|
NO_ACCESS_ROLE_ID = 3
|
||||||
|
|
||||||
|
##############################################################################
|
||||||
|
# WEB ROUTES #
|
||||||
|
##############################################################################
|
||||||
|
|
||||||
|
|
||||||
|
@web.route("/recovery", methods=["GET", "POST"])
|
||||||
|
def recovery():
|
||||||
|
"""Start recovery flow
|
||||||
|
If no active flow, redirect to kratos to create a flow, otherwise render the
|
||||||
|
recovery template.
|
||||||
|
:param flow: flow as given by Kratos
|
||||||
|
:return: redirect or recovery page
|
||||||
|
"""
|
||||||
|
|
||||||
|
flow = request.args.get("flow")
|
||||||
|
if not flow:
|
||||||
|
return redirect(KRATOS_PUBLIC_URL + "self-service/recovery/browser")
|
||||||
|
|
||||||
|
return render_template("recover.html", api_url=KRATOS_PUBLIC_URL)
|
||||||
|
|
||||||
|
|
||||||
|
@web.route("/settings", methods=["GET", "POST"])
|
||||||
|
def settings():
|
||||||
|
"""Start settings flow
|
||||||
|
If no active flow, redirect to kratos to create a flow, otherwise render the
|
||||||
|
settings template.
|
||||||
|
:param flow: flow as given by Kratos
|
||||||
|
:return: redirect or settings page
|
||||||
|
"""
|
||||||
|
|
||||||
|
flow = request.args.get("flow")
|
||||||
|
if not flow:
|
||||||
|
return redirect(KRATOS_PUBLIC_URL + "self-service/settings/browser")
|
||||||
|
|
||||||
|
return render_template("settings.html", api_url=KRATOS_PUBLIC_URL)
|
||||||
|
|
||||||
|
|
||||||
|
@web.route("/error", methods=["GET"])
|
||||||
|
def error():
|
||||||
|
"""Show error messages from Kratos
|
||||||
|
|
||||||
|
Implements user-facing errors as described in
|
||||||
|
https://www.ory.sh/docs/kratos/self-service/flows/user-facing-errors
|
||||||
|
|
||||||
|
:param id: error ID as given by Kratos
|
||||||
|
:return: redirect or settings page
|
||||||
|
"""
|
||||||
|
|
||||||
|
error_id = request.args.get("id")
|
||||||
|
api_response = ""
|
||||||
|
try:
|
||||||
|
# Get Self-Service Errors
|
||||||
|
api_response = KRATOS_ADMIN.get_self_service_error(error_id)
|
||||||
|
except ory_kratos_client.ApiException as ex:
|
||||||
|
current_app.logger.error(
|
||||||
|
"Exception when calling V0alpha2Api->get_self_service_error: %s\n",
|
||||||
|
ex)
|
||||||
|
|
||||||
|
return render_template("error.html", error_message=api_response)
|
||||||
|
|
||||||
|
|
||||||
|
@web.route("/login", methods=["GET", "POST"])
|
||||||
|
def login():
|
||||||
|
"""Start login flow
|
||||||
|
If already logged in, shows the loggedin template. Otherwise creates a login
|
||||||
|
flow, if no active flow will redirect to kratos to create a flow.
|
||||||
|
|
||||||
|
:param flow: flow as given by Kratos
|
||||||
|
:return: redirect or login page
|
||||||
|
"""
|
||||||
|
|
||||||
|
# Check if we are logged in:
|
||||||
|
identity = get_auth()
|
||||||
|
|
||||||
|
if identity:
|
||||||
|
if 'name' in identity['traits']:
|
||||||
|
# Add a space in front of the "name" so the template can put it
|
||||||
|
# between "Welcome" and the comma
|
||||||
|
name = " " + identity['traits']['name']
|
||||||
|
else:
|
||||||
|
name = ""
|
||||||
|
return render_template("loggedin.html", api_url=KRATOS_PUBLIC_URL, name=name)
|
||||||
|
|
||||||
|
flow = request.args.get("flow")
|
||||||
|
|
||||||
|
# If we do not have a flow, get one.
|
||||||
|
if not flow:
|
||||||
|
return redirect(KRATOS_PUBLIC_URL + "self-service/login/browser")
|
||||||
|
|
||||||
|
return render_template("login.html", api_url=KRATOS_PUBLIC_URL)
|
||||||
|
|
||||||
|
|
||||||
|
@web.route("/auth", methods=["GET", "POST"])
|
||||||
|
def auth():
|
||||||
|
"""Authorize an user for an application
|
||||||
|
If an application authenticated against the IdP (Idenitity Provider), if
|
||||||
|
there are no active session, the user is forwarded to the login page.
|
||||||
|
This is the entry point for those authorization requests. The challenge
|
||||||
|
as provided, is verified. If an active user is logged in, the request
|
||||||
|
is accepted and the user is returned to the application. If the user is not
|
||||||
|
logged in yet, it redirects to the login page
|
||||||
|
:param challenge: challenge as given by Hydra
|
||||||
|
:return: redirect to login or application/idp
|
||||||
|
"""
|
||||||
|
|
||||||
|
challenge = None
|
||||||
|
|
||||||
|
# Retrieve the challenge id from the request. Depending on the method it is
|
||||||
|
# saved in the form (POST) or in a GET variable. If this variable is not set
|
||||||
|
# we can not continue.
|
||||||
|
if request.method == "GET":
|
||||||
|
challenge = request.args.get("login_challenge")
|
||||||
|
if request.method == "POST":
|
||||||
|
challenge = request.args.post("login_challenge")
|
||||||
|
|
||||||
|
if not challenge:
|
||||||
|
current_app.logger.error("No challenge given. Error in request")
|
||||||
|
abort(400, description="Challenge required when requesting authorization")
|
||||||
|
|
||||||
|
# Check if we are logged in:
|
||||||
|
identity = get_auth()
|
||||||
|
|
||||||
|
# If the user is not logged in yet, we redirect to the login page
|
||||||
|
# but before we do that, we set the "flow_state" cookie to auth.
|
||||||
|
# so the UI knows it has to redirect after a successful login.
|
||||||
|
# The redirect URL is back to this page (auth) with the same challenge
|
||||||
|
# so we can pickup the flow where we left off.
|
||||||
|
if not identity:
|
||||||
|
url = LOGIN_PANEL_URL + "/auth?login_challenge=" + challenge
|
||||||
|
url = urllib.parse.quote_plus(url)
|
||||||
|
|
||||||
|
current_app.logger.info("Redirecting to login. Setting flow_state cookies")
|
||||||
|
current_app.logger.info("auth_url: " + url)
|
||||||
|
|
||||||
|
response = redirect(LOGIN_PANEL_URL + "/login")
|
||||||
|
response.set_cookie("flow_state", "auth")
|
||||||
|
response.set_cookie("auth_url", url)
|
||||||
|
return response
|
||||||
|
|
||||||
|
current_app.logger.info("User is logged in. We can authorize the user")
|
||||||
|
|
||||||
|
try:
|
||||||
|
login_request = HYDRA.login_request(challenge)
|
||||||
|
except hydra_client.exceptions.NotFound:
|
||||||
|
current_app.logger.error(
|
||||||
|
f"Not Found. Login request not found. challenge={challenge}"
|
||||||
|
)
|
||||||
|
abort(404, description="Login request not found. Please try again.")
|
||||||
|
except hydra_client.exceptions.HTTPError:
|
||||||
|
current_app.logger.error(
|
||||||
|
f"Conflict. Login request has been used already. challenge={challenge}"
|
||||||
|
)
|
||||||
|
abort(503, description="Login request already used. Please try again.")
|
||||||
|
|
||||||
|
# Authorize the user
|
||||||
|
# False positive: pylint: disable=no-member
|
||||||
|
redirect_to = login_request.accept(
|
||||||
|
identity.id,
|
||||||
|
remember=True,
|
||||||
|
# Remember session for 7d
|
||||||
|
remember_for=60 * 60 * 24 * 7,
|
||||||
|
)
|
||||||
|
|
||||||
|
return redirect(redirect_to)
|
||||||
|
|
||||||
|
|
||||||
|
@web.route("/consent", methods=["GET", "POST"])
|
||||||
|
def consent():
|
||||||
|
"""Get consent
|
||||||
|
For now, it just allows every user. Eventually this function should check
|
||||||
|
the roles and settings of a user and provide that information to the
|
||||||
|
application.
|
||||||
|
:param consent_challenge: challenge as given by Hydra
|
||||||
|
:return: redirect to login or render error
|
||||||
|
"""
|
||||||
|
|
||||||
|
challenge = request.args.get("consent_challenge")
|
||||||
|
if not challenge:
|
||||||
|
abort(
|
||||||
|
403, description="Consent request required. Do not call this page directly"
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
consent_request = HYDRA.consent_request(challenge)
|
||||||
|
except hydra_client.exceptions.NotFound:
|
||||||
|
current_app.logger.error(f"Not Found. Consent request {challenge} not found")
|
||||||
|
abort(404, description="Consent request does not exist. Please try again")
|
||||||
|
except hydra_client.exceptions.HTTPError:
|
||||||
|
current_app.logger.error(f"Conflict. Consent request {challenge} already used")
|
||||||
|
abort(503, description="Consent request already used. Please try again")
|
||||||
|
|
||||||
|
# Get information about this consent request:
|
||||||
|
# False positive: pylint: disable=no-member
|
||||||
|
try:
|
||||||
|
consent_client = consent_request.client
|
||||||
|
|
||||||
|
# Some versions of Hydra module return a string object and need to be decoded
|
||||||
|
if isinstance(consent_client, str):
|
||||||
|
consent_client = ast.literal_eval(consent_client)
|
||||||
|
|
||||||
|
app_id = consent_client.get("client_id")
|
||||||
|
# False positive: pylint: disable=no-member
|
||||||
|
kratos_id = consent_request.subject
|
||||||
|
current_app.logger.info(f"Info: Found kratos_id {kratos_id}")
|
||||||
|
current_app.logger.info(f"Info: Found app_id {app_id}")
|
||||||
|
|
||||||
|
except Exception as ex:
|
||||||
|
current_app.logger.error(
|
||||||
|
"Error: Unable to extract information from consent request"
|
||||||
|
)
|
||||||
|
current_app.logger.error(f"Error: {ex}")
|
||||||
|
current_app.logger.error(f"Client: {consent_request.client}")
|
||||||
|
current_app.logger.error(f"Subject: {consent_request.subject}")
|
||||||
|
abort(501, description="Internal error occured")
|
||||||
|
|
||||||
|
# Get the related user object
|
||||||
|
current_app.logger.info(f"Info: Getting user from admin {kratos_id}")
|
||||||
|
user = KratosUser(KRATOS_ADMIN, kratos_id)
|
||||||
|
if not user:
|
||||||
|
current_app.logger.error(f"User not found in database: {kratos_id}")
|
||||||
|
abort(401, description="User not found. Please try again.")
|
||||||
|
|
||||||
|
# Get role on dashboard
|
||||||
|
dashboard_app = db.session.query(App).filter(
|
||||||
|
App.slug == 'dashboard').first()
|
||||||
|
if dashboard_app:
|
||||||
|
role_object = (
|
||||||
|
db.session.query(AppRole)
|
||||||
|
.filter(AppRole.app_id == dashboard_app.id)
|
||||||
|
.filter(AppRole.user_id == user.uuid)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
# If the user is dashboard admin admin is for all
|
||||||
|
if role_object is not None and role_object.role_id == ADMIN_ROLE_ID:
|
||||||
|
current_app.logger.info(f"Info: User has admin dashboard role")
|
||||||
|
current_app.logger.info(f"Providing consent to {app_id} for {kratos_id}")
|
||||||
|
current_app.logger.info(f"{kratos_id} was granted admin access to {app_id}")
|
||||||
|
# Get claims for this user, provided the current app
|
||||||
|
claims = user.get_claims(app_id, ['admin'])
|
||||||
|
return redirect(
|
||||||
|
consent_request.accept(
|
||||||
|
grant_scope=consent_request.requested_scope,
|
||||||
|
grant_access_token_audience=consent_request.requested_access_token_audience,
|
||||||
|
session=claims,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
# Get role on this app
|
||||||
|
app_obj = db.session.query(App).filter(App.slug == app_id).first()
|
||||||
|
|
||||||
|
# Default access level
|
||||||
|
roles = []
|
||||||
|
if app_obj:
|
||||||
|
role_object = (
|
||||||
|
db.session.query(AppRole)
|
||||||
|
.filter(AppRole.app_id == app_obj.id)
|
||||||
|
.filter(AppRole.user_id == user.uuid)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
# Role ID 3 is always "No access" due to migration b514cca2d47b
|
||||||
|
if role_object is None or role_object.role_id is None or role_object.role_id == NO_ACCESS_ROLE_ID:
|
||||||
|
# If there is no role in app_roles or the role_id for an app is null user has no permissions
|
||||||
|
current_app.logger.error(f"User has no access for: {app_obj.name}")
|
||||||
|
return redirect(
|
||||||
|
consent_request.reject(
|
||||||
|
error="No access",
|
||||||
|
error_description="The user has no access for app",
|
||||||
|
error_hint="Contact your administrator",
|
||||||
|
status_code=401,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
roles.append(role_object.role.name)
|
||||||
|
|
||||||
|
current_app.logger.info(f"Using '{roles}' when applying consent for {kratos_id}")
|
||||||
|
|
||||||
|
# Get claims for this user, provided the current app
|
||||||
|
claims = user.get_claims(app_id, roles)
|
||||||
|
|
||||||
|
# pylint: disable=fixme
|
||||||
|
# TODO: Need to implement checking claims here, once the backend for that is
|
||||||
|
# developed
|
||||||
|
current_app.logger.info(f"Providing consent to {app_id} for {kratos_id}")
|
||||||
|
current_app.logger.info(f"{kratos_id} was granted access to {app_id}")
|
||||||
|
|
||||||
|
# False positive: pylint: disable=no-member
|
||||||
|
return redirect(
|
||||||
|
consent_request.accept(
|
||||||
|
grant_scope=consent_request.requested_scope,
|
||||||
|
grant_access_token_audience=consent_request.requested_access_token_audience,
|
||||||
|
session=claims,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@web.route("/status", methods=["GET", "POST"])
|
||||||
|
def status():
|
||||||
|
"""Get status of current session
|
||||||
|
Show if there is an user is logged in. If not shows: not-auth
|
||||||
|
"""
|
||||||
|
|
||||||
|
auth_status = get_auth()
|
||||||
|
|
||||||
|
if auth_status:
|
||||||
|
return auth_status.id
|
||||||
|
return "not-auth"
|
||||||
|
|
||||||
|
|
||||||
|
def get_auth():
|
||||||
|
"""Checks if user is logged in
|
||||||
|
Queries the cookies. If an authentication cookie is found, it
|
||||||
|
checks with Kratos if the cookie is still valid. If so,
|
||||||
|
the profile is returned. Otherwise False is returned.
|
||||||
|
:return: Profile or False if not logged in
|
||||||
|
"""
|
||||||
|
|
||||||
|
cookie = get_kratos_cookie()
|
||||||
|
if not cookie:
|
||||||
|
return False
|
||||||
|
|
||||||
|
# Given a cookie, check if it is valid and get the profile
|
||||||
|
try:
|
||||||
|
api_response = KRATOS_PUBLIC.to_session(cookie=cookie)
|
||||||
|
|
||||||
|
# Get all traits from ID
|
||||||
|
return api_response.identity
|
||||||
|
|
||||||
|
except ory_kratos_client.ApiException as ex:
|
||||||
|
current_app.logger.error(
|
||||||
|
f"Exception when calling V0alpha2Api->to_session(): {ex}\n"
|
||||||
|
)
|
||||||
|
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def get_kratos_cookie():
|
||||||
|
"""Retrieves the Kratos cookie from the session.
|
||||||
|
|
||||||
|
Returns False if the cookie does not exist or is corrupted.
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
cookie = request.cookies.get("ory_kratos_session")
|
||||||
|
cookie = "ory_kratos_session=" + cookie
|
||||||
|
except TypeError:
|
||||||
|
current_app.logger.info("User not logged in or cookie corrupted")
|
||||||
|
cookie = False
|
||||||
|
return cookie
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
@web.route("/prelogout", methods=["GET"])
|
||||||
|
def prelogout():
|
||||||
|
"""Handles the Hydra OpenID Connect Logout flow
|
||||||
|
|
||||||
|
Steps:
|
||||||
|
1. Hydra's /oauth2/sessions/logout endpoint is called by an application
|
||||||
|
2. Hydra calls this endpoint with a `logout_challenge` get parameter
|
||||||
|
3. We retrieve the logout request using the challenge
|
||||||
|
4. We accept the Hydra logout request
|
||||||
|
5. We redirect to Hydra to clean-up cookies.
|
||||||
|
6. Hyrda calls back to us with a post logout handle (/logout)
|
||||||
|
|
||||||
|
|
||||||
|
Args:
|
||||||
|
logout_challenge (string): Reference to a Hydra logout challenge object
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Redirect to the url that is provided by the LogoutRequest object.
|
||||||
|
"""
|
||||||
|
challenge = request.args.get("logout_challenge")
|
||||||
|
current_app.logger.info("Logout request: challenge=%s", challenge)
|
||||||
|
if not challenge:
|
||||||
|
abort(403)
|
||||||
|
try:
|
||||||
|
logout_request = HYDRA.logout_request(challenge)
|
||||||
|
except hydra_client.exceptions.NotFound:
|
||||||
|
current_app.logger.error("Logout request with challenge '%s' not found", challenge)
|
||||||
|
abort(404, "Hydra session invalid or not found")
|
||||||
|
except hydra_client.exceptions.HTTPError:
|
||||||
|
current_app.logger.error(
|
||||||
|
"Conflict. Logout request with challenge '%s' has been used already.",
|
||||||
|
challenge)
|
||||||
|
abort(503)
|
||||||
|
|
||||||
|
current_app.logger.info("Logout request hydra, subject %s", logout_request.subject)
|
||||||
|
|
||||||
|
# Accept logout request and direct to hydra to remove cookies
|
||||||
|
try:
|
||||||
|
hydra_return = logout_request.accept(subject=logout_request.subject)
|
||||||
|
if hydra_return:
|
||||||
|
return redirect(hydra_return)
|
||||||
|
|
||||||
|
except Exception as ex:
|
||||||
|
current_app.logger.info("Error logging out hydra: %s", str(ex))
|
||||||
|
|
||||||
|
|
||||||
|
current_app.logger.info("Hydra logout not completed. Redirecting to kratos logout, maybe user removed cookies manually")
|
||||||
|
return redirect("logout")
|
||||||
|
|
||||||
|
|
||||||
|
@web.route("/logout", methods=["GET"])
|
||||||
|
def logout():
|
||||||
|
"""Handles the Kratos Logout flow
|
||||||
|
|
||||||
|
Steps:
|
||||||
|
1. We got here from hyrda
|
||||||
|
2. We retrieve the Kratos cookie from the browser
|
||||||
|
3. We generate a Kratos logout URL
|
||||||
|
4. We redirect to the Kratos logout URIL
|
||||||
|
"""
|
||||||
|
|
||||||
|
kratos_cookie = get_kratos_cookie()
|
||||||
|
if not kratos_cookie:
|
||||||
|
# No kratos cookie, already logged out
|
||||||
|
current_app.logger.info("Expected kratos cookie but not found. Redirecting to login");
|
||||||
|
return redirect("login")
|
||||||
|
|
||||||
|
try:
|
||||||
|
# Create a Logout URL for Browsers
|
||||||
|
kratos_api_response = \
|
||||||
|
KRATOS_ADMIN.create_self_service_logout_flow_url_for_browsers(
|
||||||
|
cookie=kratos_cookie)
|
||||||
|
current_app.logger.info(kratos_api_response)
|
||||||
|
except ory_kratos_client.ApiException as ex:
|
||||||
|
current_app.logger.error("Exception when calling"
|
||||||
|
" V0alpha2Api->create_self_service_logout_flow_url_for_browsers: %s\n",
|
||||||
|
ex)
|
||||||
|
return redirect(kratos_api_response.logout_url)
|
||||||
|
|
0
backend/web/static/.gitkeep
Normal file
0
backend/web/static/.gitkeep
Normal file
404
backend/web/static/base.js
vendored
Normal file
404
backend/web/static/base.js
vendored
Normal file
|
@ -0,0 +1,404 @@
|
||||||
|
/* base.js
|
||||||
|
This is the base JS file to render the user interfaces of kratos and provide
|
||||||
|
the end user with flows for login, recovery etc.
|
||||||
|
|
||||||
|
check_flow_*():
|
||||||
|
These functions check the status of the flow and based on the status do some
|
||||||
|
action to get a better experience for the end user. Usually this is a
|
||||||
|
redirect based on the state
|
||||||
|
|
||||||
|
flow_*():
|
||||||
|
execute / render all UI elements in a flow. Kratos expects you to work on
|
||||||
|
to query kratos which provides you with the UI elements needed to be
|
||||||
|
rendered. This querying and rendering is done exectly by those function.
|
||||||
|
Based on what kratos provides or the state of the flow, elements are maybe
|
||||||
|
hidden or shown
|
||||||
|
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Check if an auth flow is configured and redirect to auth page in that
|
||||||
|
// case.
|
||||||
|
function check_flow_auth() {
|
||||||
|
var state = Cookies.get('flow_state');
|
||||||
|
var url = Cookies.get('auth_url');
|
||||||
|
|
||||||
|
if (state == 'auth') {
|
||||||
|
Cookies.set('flow_state', '');
|
||||||
|
window.location.href = url;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there if the flow is expired, if so, reset the cookie
|
||||||
|
function check_flow_expired() {
|
||||||
|
var state = Cookies.get('flow_state');
|
||||||
|
|
||||||
|
if (state == 'flow_expired') {
|
||||||
|
Cookies.set('flow_state', '');
|
||||||
|
$('#contentFlowExpired').show();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The script executed on login flows
|
||||||
|
function flow_login() {
|
||||||
|
var flow = $.urlParam('flow');
|
||||||
|
var uri = api_url + 'self-service/login/flows?id=' + flow;
|
||||||
|
|
||||||
|
// Query the Kratos backend to know what fields to render for the
|
||||||
|
// current flow
|
||||||
|
$.ajax({
|
||||||
|
type: 'GET',
|
||||||
|
url: uri,
|
||||||
|
success: function (data) {
|
||||||
|
// Render login form (group: password)
|
||||||
|
var form_html = render_form(data, 'password');
|
||||||
|
$('#contentLogin').html(form_html);
|
||||||
|
|
||||||
|
var messages_html = render_messages(data);
|
||||||
|
$('#contentMessages').html(messages_html);
|
||||||
|
},
|
||||||
|
complete: function (obj) {
|
||||||
|
// If we get a 410, the flow is expired, need to refresh the flow
|
||||||
|
if (obj.status == 410) {
|
||||||
|
Cookies.set('flow_state', 'flow_expired');
|
||||||
|
// If we call the page without arguments, we get a new flow
|
||||||
|
window.location.href = 'login';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is called after a POST on settings. It tells if the save was
|
||||||
|
// successful and display / handles based on that outcome
|
||||||
|
function flow_settings_validate() {
|
||||||
|
var flow = $.urlParam('flow');
|
||||||
|
var uri = api_url + 'self-service/settings/flows?id=' + flow;
|
||||||
|
|
||||||
|
$.ajax({
|
||||||
|
type: 'GET',
|
||||||
|
url: uri,
|
||||||
|
success: function (data) {
|
||||||
|
// We had success. We save that fact in our flow_state
|
||||||
|
// cookie and regenerate a new flow
|
||||||
|
if (data.state == 'success') {
|
||||||
|
Cookies.set('flow_state', 'settings_saved');
|
||||||
|
|
||||||
|
// Redirect to generate new flow ID
|
||||||
|
window.location.href = 'settings';
|
||||||
|
} else {
|
||||||
|
// There was an error, Kratos does not specify what is
|
||||||
|
// wrong. So we just show the general error message and
|
||||||
|
// let the user figure it out. We can re-use the flow-id
|
||||||
|
$('#contentProfileSaveFailed').show();
|
||||||
|
|
||||||
|
// For now, this code assumes that only the password can fail
|
||||||
|
// validation. Other forms might need to be added in the future.
|
||||||
|
html = render_form(data, 'password');
|
||||||
|
$('#contentPassword').html(html);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render the settings flow, this is where users can change their personal
|
||||||
|
// settings, like name and password. The form contents are defined by Kratos
|
||||||
|
function flow_settings() {
|
||||||
|
// Get the details from the current flow from kratos
|
||||||
|
var flow = $.urlParam('flow');
|
||||||
|
var uri = api_url + 'self-service/settings/flows?id=' + flow;
|
||||||
|
$.ajax({
|
||||||
|
type: 'GET',
|
||||||
|
url: uri,
|
||||||
|
success: function (data) {
|
||||||
|
var state = Cookies.get('flow_state');
|
||||||
|
|
||||||
|
// If we have confirmation the settings are saved, show the
|
||||||
|
// notification
|
||||||
|
if (state == 'settings_saved') {
|
||||||
|
$('#contentProfileSaved').show();
|
||||||
|
Cookies.set('flow_state', 'settings');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hide prfile section if we are in recovery state
|
||||||
|
// so the user is not confused by other fields. The user
|
||||||
|
// probably want to setup a password only first.
|
||||||
|
if (state == 'recovery') {
|
||||||
|
$('#contentProfile').hide();
|
||||||
|
}
|
||||||
|
|
||||||
|
// Render the password & profile form based on the fields we got
|
||||||
|
// from the API
|
||||||
|
var html = render_form(data, 'password');
|
||||||
|
$('#contentPassword').html(html);
|
||||||
|
|
||||||
|
html = render_form(data, 'profile');
|
||||||
|
$('#contentProfile').html(html);
|
||||||
|
|
||||||
|
// If the submit button is hit, execute the POST with Ajax.
|
||||||
|
$('#formpassword').submit(function (e) {
|
||||||
|
// avoid to execute the actual submit of the form.
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
var form = $(this);
|
||||||
|
var url = form.attr('action');
|
||||||
|
|
||||||
|
$.ajax({
|
||||||
|
type: 'POST',
|
||||||
|
url: url,
|
||||||
|
data: form.serialize(),
|
||||||
|
complete: function (obj) {
|
||||||
|
// Validate the settings
|
||||||
|
flow_settings_validate();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
complete: function (obj) {
|
||||||
|
// If we get a 410, the flow is expired, need to refresh the flow
|
||||||
|
if (obj.status == 410) {
|
||||||
|
Cookies.set('flow_state', 'flow_expired');
|
||||||
|
window.location.href = 'settings';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function flow_recover() {
|
||||||
|
var flow = $.urlParam('flow');
|
||||||
|
var uri = api_url + 'self-service/recovery/flows?id=' + flow;
|
||||||
|
|
||||||
|
$.ajax({
|
||||||
|
type: 'GET',
|
||||||
|
url: uri,
|
||||||
|
success: function (data) {
|
||||||
|
// Render the recover form, method 'link'
|
||||||
|
var html = render_form(data, 'link');
|
||||||
|
$('#contentRecover').html(html);
|
||||||
|
|
||||||
|
// Do form post as an AJAX call
|
||||||
|
$('#formlink').submit(function (e) {
|
||||||
|
// avoid to execute the actual submit of the form.
|
||||||
|
e.preventDefault();
|
||||||
|
|
||||||
|
var form = $(this);
|
||||||
|
var url = form.attr('action');
|
||||||
|
|
||||||
|
// keep stat we are in recovery
|
||||||
|
Cookies.set('flow_state', 'recovery');
|
||||||
|
$.ajax({
|
||||||
|
type: 'POST',
|
||||||
|
url: url,
|
||||||
|
data: form.serialize(), // serializes the form's elements.
|
||||||
|
success: function (data) {
|
||||||
|
// Show the request is sent out
|
||||||
|
$('#contentRecover').hide();
|
||||||
|
$('#contentRecoverRequested').show();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
complete: function (obj) {
|
||||||
|
// If we get a 410, the flow is expired, need to refresh the flow
|
||||||
|
if (obj.status == 410) {
|
||||||
|
Cookies.set('flow_state', 'flow_expired');
|
||||||
|
window.location.href = 'recovery';
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Based on Kratos UI data and a group name, get the full form for that group.
|
||||||
|
// kratos groups elements which belongs together in a group and should be posted
|
||||||
|
// at once. The elements in the default group should be part of all other
|
||||||
|
// groups.
|
||||||
|
//
|
||||||
|
// data: data object as returned form the API
|
||||||
|
// group: group to render.
|
||||||
|
function render_form(data, group) {
|
||||||
|
// Create form
|
||||||
|
var action = data.ui.action;
|
||||||
|
var method = data.ui.method;
|
||||||
|
var form = "<form id='form" + group + "' method='" + method + "' action='" + action + "'>";
|
||||||
|
|
||||||
|
for (const node of data.ui.nodes) {
|
||||||
|
var name = node.attributes.name;
|
||||||
|
var type = node.attributes.type;
|
||||||
|
var value = node.attributes.value;
|
||||||
|
var messages = node.messages;
|
||||||
|
|
||||||
|
if (node.group == 'default' || node.group == group) {
|
||||||
|
var elm = getFormElement(type, name, value, messages);
|
||||||
|
form += elm;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
form += '</form>';
|
||||||
|
return form;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if there are any general messages to show to the user and render them
|
||||||
|
function render_messages(data) {
|
||||||
|
var messages = data.ui.messages;
|
||||||
|
if (messages == []) {
|
||||||
|
return '';
|
||||||
|
}
|
||||||
|
var html = '<ul>';
|
||||||
|
messages.forEach((message) => {
|
||||||
|
html += '<li>';
|
||||||
|
html += message.text;
|
||||||
|
html += '</li>';
|
||||||
|
});
|
||||||
|
html += '</ul>';
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return form element based on name, including help text (sub), placeholder etc.
|
||||||
|
// Kratos give us form names and types and specifies what to render. However
|
||||||
|
// it does not provide labels or translations. This function returns a HTML
|
||||||
|
// form element based on the fields provided by Kratos with proper names and
|
||||||
|
// labels
|
||||||
|
// type: input type, usual "input", "hidden" or "submit". But bootstrap types
|
||||||
|
// like "email" are also supported
|
||||||
|
// name: name of the field. Used when posting data
|
||||||
|
// value: If there is already a value known, show it
|
||||||
|
// messages: error messages related to the field
|
||||||
|
function getFormElement(type, name, value, messages) {
|
||||||
|
console.log('Getting form element', type, name, value, messages);
|
||||||
|
|
||||||
|
if (value == undefined) {
|
||||||
|
value = '';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof messages == 'undefined') {
|
||||||
|
messages = [];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name == 'email' || name == 'traits.email') {
|
||||||
|
return getFormInput(
|
||||||
|
'email',
|
||||||
|
name,
|
||||||
|
value,
|
||||||
|
'E-mail address',
|
||||||
|
'Please enter your e-mail address here',
|
||||||
|
'Please provide your e-mail address. We will send a recovery link to that e-mail address.',
|
||||||
|
messages,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name == 'traits.username') {
|
||||||
|
return getFormInput('name', name, value, 'Username', 'Please provide an username', null, messages);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name == 'traits.name') {
|
||||||
|
return getFormInput('name', name, value, 'Full name', 'Please provide your full name', null, messages);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name == 'identifier') {
|
||||||
|
return getFormInput(
|
||||||
|
'email',
|
||||||
|
name,
|
||||||
|
value,
|
||||||
|
'E-mail address',
|
||||||
|
'Please provide your e-mail address to log in',
|
||||||
|
null,
|
||||||
|
messages,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (name == 'password') {
|
||||||
|
return getFormInput('password', name, value, 'Password', 'Please provide your password', null, messages);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == 'hidden' || name == 'traits.uuid') {
|
||||||
|
return (
|
||||||
|
`
|
||||||
|
<input type="hidden" class="form-control" id="` +
|
||||||
|
name +
|
||||||
|
`"
|
||||||
|
name="` +
|
||||||
|
name +
|
||||||
|
`" value='` +
|
||||||
|
value +
|
||||||
|
`'>`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (type == 'submit') {
|
||||||
|
return (
|
||||||
|
`<div class="form-group">
|
||||||
|
<input type="hidden" name="` +
|
||||||
|
name +
|
||||||
|
`" value="` +
|
||||||
|
value +
|
||||||
|
`">
|
||||||
|
<button type="submit" class="btn btn-primary">Go!</button>
|
||||||
|
</div>`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return getFormInput('input', name, value, name, null, null, messages);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Usually called by getFormElement, generic function to generate an
|
||||||
|
// input box.
|
||||||
|
// param type: type of input, like 'input', 'email', 'password'
|
||||||
|
// param name: name of form field, used when posting the form
|
||||||
|
// param value: preset value of the field
|
||||||
|
// param label: Label to display above field
|
||||||
|
// param placeHolder: Label to display in field if empty
|
||||||
|
// param help: Additional help text, displayed below the field in small font
|
||||||
|
// param messages: Message about failed input
|
||||||
|
function getFormInput(type, name, value, label, placeHolder, help, messages) {
|
||||||
|
if (typeof help == 'undefined' || help == null) {
|
||||||
|
help = '';
|
||||||
|
}
|
||||||
|
console.log('Messages: ', messages);
|
||||||
|
|
||||||
|
// Id field for help element
|
||||||
|
var nameHelp = name + 'Help';
|
||||||
|
|
||||||
|
var element = '<div class="form-group">';
|
||||||
|
element += '<label for="' + name + '">' + label + '</label>';
|
||||||
|
element += '<input type="' + type + '" class="form-control" id="' + name + '" name="' + name + '" ';
|
||||||
|
|
||||||
|
// messages get appended to help info
|
||||||
|
if (messages.length) {
|
||||||
|
for (message in messages) {
|
||||||
|
console.log('adding message', messages[message]);
|
||||||
|
help += messages[message]['text'];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we are a password field, add a eye icon to reveal password
|
||||||
|
if (value) {
|
||||||
|
element += 'value="' + value + '" ';
|
||||||
|
}
|
||||||
|
if (help) {
|
||||||
|
element += 'aria-describedby="' + nameHelp + '" ';
|
||||||
|
}
|
||||||
|
if (placeHolder) {
|
||||||
|
element += 'placeholder="' + placeHolder + '" ';
|
||||||
|
}
|
||||||
|
element += '>';
|
||||||
|
|
||||||
|
if (help) {
|
||||||
|
element +=
|
||||||
|
`<small id="` +
|
||||||
|
nameHelp +
|
||||||
|
`" class="form-text text-muted">` +
|
||||||
|
help +
|
||||||
|
`
|
||||||
|
</small>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
element += '</div>';
|
||||||
|
|
||||||
|
return element;
|
||||||
|
}
|
||||||
|
|
||||||
|
// $.urlParam get parameters from the URI. Example: id = $.urlParam('id');
|
||||||
|
$.urlParam = function (name) {
|
||||||
|
var results = new RegExp('[?&]' + name + '=([^&#]*)').exec(window.location.href);
|
||||||
|
if (results == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return decodeURI(results[1]) || 0;
|
||||||
|
};
|
2050
backend/web/static/css/bootstrap-grid.css
vendored
Normal file
2050
backend/web/static/css/bootstrap-grid.css
vendored
Normal file
File diff suppressed because it is too large
Load diff
1
backend/web/static/css/bootstrap-grid.css.map
Normal file
1
backend/web/static/css/bootstrap-grid.css.map
Normal file
File diff suppressed because one or more lines are too long
7
backend/web/static/css/bootstrap-grid.min.css
vendored
Normal file
7
backend/web/static/css/bootstrap-grid.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
backend/web/static/css/bootstrap-grid.min.css.map
Normal file
1
backend/web/static/css/bootstrap-grid.min.css.map
Normal file
File diff suppressed because one or more lines are too long
330
backend/web/static/css/bootstrap-reboot.css
vendored
Normal file
330
backend/web/static/css/bootstrap-reboot.css
vendored
Normal file
|
@ -0,0 +1,330 @@
|
||||||
|
/*!
|
||||||
|
* Bootstrap Reboot v4.0.0 (https://getbootstrap.com)
|
||||||
|
* Copyright 2011-2018 The Bootstrap Authors
|
||||||
|
* Copyright 2011-2018 Twitter, Inc.
|
||||||
|
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
|
||||||
|
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
|
||||||
|
*/
|
||||||
|
*,
|
||||||
|
*::before,
|
||||||
|
*::after {
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
html {
|
||||||
|
font-family: sans-serif;
|
||||||
|
line-height: 1.15;
|
||||||
|
-webkit-text-size-adjust: 100%;
|
||||||
|
-ms-text-size-adjust: 100%;
|
||||||
|
-ms-overflow-style: scrollbar;
|
||||||
|
-webkit-tap-highlight-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
@-ms-viewport {
|
||||||
|
width: device-width;
|
||||||
|
}
|
||||||
|
|
||||||
|
article, aside, dialog, figcaption, figure, footer, header, hgroup, main, nav, section {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
|
||||||
|
font-size: 1rem;
|
||||||
|
font-weight: 400;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: #212529;
|
||||||
|
text-align: left;
|
||||||
|
background-color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
[tabindex="-1"]:focus {
|
||||||
|
outline: 0 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
hr {
|
||||||
|
box-sizing: content-box;
|
||||||
|
height: 0;
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1, h2, h3, h4, h5, h6 {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 0.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
p {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
abbr[title],
|
||||||
|
abbr[data-original-title] {
|
||||||
|
text-decoration: underline;
|
||||||
|
-webkit-text-decoration: underline dotted;
|
||||||
|
text-decoration: underline dotted;
|
||||||
|
cursor: help;
|
||||||
|
border-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
address {
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
font-style: normal;
|
||||||
|
line-height: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
ol,
|
||||||
|
ul,
|
||||||
|
dl {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
ol ol,
|
||||||
|
ul ul,
|
||||||
|
ol ul,
|
||||||
|
ul ol {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
dt {
|
||||||
|
font-weight: 700;
|
||||||
|
}
|
||||||
|
|
||||||
|
dd {
|
||||||
|
margin-bottom: .5rem;
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
blockquote {
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
dfn {
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
b,
|
||||||
|
strong {
|
||||||
|
font-weight: bolder;
|
||||||
|
}
|
||||||
|
|
||||||
|
small {
|
||||||
|
font-size: 80%;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub,
|
||||||
|
sup {
|
||||||
|
position: relative;
|
||||||
|
font-size: 75%;
|
||||||
|
line-height: 0;
|
||||||
|
vertical-align: baseline;
|
||||||
|
}
|
||||||
|
|
||||||
|
sub {
|
||||||
|
bottom: -.25em;
|
||||||
|
}
|
||||||
|
|
||||||
|
sup {
|
||||||
|
top: -.5em;
|
||||||
|
}
|
||||||
|
|
||||||
|
a {
|
||||||
|
color: #007bff;
|
||||||
|
text-decoration: none;
|
||||||
|
background-color: transparent;
|
||||||
|
-webkit-text-decoration-skip: objects;
|
||||||
|
}
|
||||||
|
|
||||||
|
a:hover {
|
||||||
|
color: #0056b3;
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
a:not([href]):not([tabindex]) {
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
a:not([href]):not([tabindex]):hover, a:not([href]):not([tabindex]):focus {
|
||||||
|
color: inherit;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
a:not([href]):not([tabindex]):focus {
|
||||||
|
outline: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
pre,
|
||||||
|
code,
|
||||||
|
kbd,
|
||||||
|
samp {
|
||||||
|
font-family: monospace, monospace;
|
||||||
|
font-size: 1em;
|
||||||
|
}
|
||||||
|
|
||||||
|
pre {
|
||||||
|
margin-top: 0;
|
||||||
|
margin-bottom: 1rem;
|
||||||
|
overflow: auto;
|
||||||
|
-ms-overflow-style: scrollbar;
|
||||||
|
}
|
||||||
|
|
||||||
|
figure {
|
||||||
|
margin: 0 0 1rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
img {
|
||||||
|
vertical-align: middle;
|
||||||
|
border-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
svg:not(:root) {
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
}
|
||||||
|
|
||||||
|
caption {
|
||||||
|
padding-top: 0.75rem;
|
||||||
|
padding-bottom: 0.75rem;
|
||||||
|
color: #6c757d;
|
||||||
|
text-align: left;
|
||||||
|
caption-side: bottom;
|
||||||
|
}
|
||||||
|
|
||||||
|
th {
|
||||||
|
text-align: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
display: inline-block;
|
||||||
|
margin-bottom: .5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
border-radius: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:focus {
|
||||||
|
outline: 1px dotted;
|
||||||
|
outline: 5px auto -webkit-focus-ring-color;
|
||||||
|
}
|
||||||
|
|
||||||
|
input,
|
||||||
|
button,
|
||||||
|
select,
|
||||||
|
optgroup,
|
||||||
|
textarea {
|
||||||
|
margin: 0;
|
||||||
|
font-family: inherit;
|
||||||
|
font-size: inherit;
|
||||||
|
line-height: inherit;
|
||||||
|
}
|
||||||
|
|
||||||
|
button,
|
||||||
|
input {
|
||||||
|
overflow: visible;
|
||||||
|
}
|
||||||
|
|
||||||
|
button,
|
||||||
|
select {
|
||||||
|
text-transform: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
button,
|
||||||
|
html [type="button"],
|
||||||
|
[type="reset"],
|
||||||
|
[type="submit"] {
|
||||||
|
-webkit-appearance: button;
|
||||||
|
}
|
||||||
|
|
||||||
|
button::-moz-focus-inner,
|
||||||
|
[type="button"]::-moz-focus-inner,
|
||||||
|
[type="reset"]::-moz-focus-inner,
|
||||||
|
[type="submit"]::-moz-focus-inner {
|
||||||
|
padding: 0;
|
||||||
|
border-style: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="radio"],
|
||||||
|
input[type="checkbox"] {
|
||||||
|
box-sizing: border-box;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
input[type="date"],
|
||||||
|
input[type="time"],
|
||||||
|
input[type="datetime-local"],
|
||||||
|
input[type="month"] {
|
||||||
|
-webkit-appearance: listbox;
|
||||||
|
}
|
||||||
|
|
||||||
|
textarea {
|
||||||
|
overflow: auto;
|
||||||
|
resize: vertical;
|
||||||
|
}
|
||||||
|
|
||||||
|
fieldset {
|
||||||
|
min-width: 0;
|
||||||
|
padding: 0;
|
||||||
|
margin: 0;
|
||||||
|
border: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
legend {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 100%;
|
||||||
|
padding: 0;
|
||||||
|
margin-bottom: .5rem;
|
||||||
|
font-size: 1.5rem;
|
||||||
|
line-height: inherit;
|
||||||
|
color: inherit;
|
||||||
|
white-space: normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
progress {
|
||||||
|
vertical-align: baseline;
|
||||||
|
}
|
||||||
|
|
||||||
|
[type="number"]::-webkit-inner-spin-button,
|
||||||
|
[type="number"]::-webkit-outer-spin-button {
|
||||||
|
height: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
[type="search"] {
|
||||||
|
outline-offset: -2px;
|
||||||
|
-webkit-appearance: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
[type="search"]::-webkit-search-cancel-button,
|
||||||
|
[type="search"]::-webkit-search-decoration {
|
||||||
|
-webkit-appearance: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-file-upload-button {
|
||||||
|
font: inherit;
|
||||||
|
-webkit-appearance: button;
|
||||||
|
}
|
||||||
|
|
||||||
|
output {
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
summary {
|
||||||
|
display: list-item;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
template {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
[hidden] {
|
||||||
|
display: none !important;
|
||||||
|
}
|
||||||
|
/*# sourceMappingURL=bootstrap-reboot.css.map */
|
1
backend/web/static/css/bootstrap-reboot.css.map
Normal file
1
backend/web/static/css/bootstrap-reboot.css.map
Normal file
File diff suppressed because one or more lines are too long
8
backend/web/static/css/bootstrap-reboot.min.css
vendored
Normal file
8
backend/web/static/css/bootstrap-reboot.min.css
vendored
Normal file
|
@ -0,0 +1,8 @@
|
||||||
|
/*!
|
||||||
|
* Bootstrap Reboot v4.0.0 (https://getbootstrap.com)
|
||||||
|
* Copyright 2011-2018 The Bootstrap Authors
|
||||||
|
* Copyright 2011-2018 Twitter, Inc.
|
||||||
|
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
|
||||||
|
* Forked from Normalize.css, licensed MIT (https://github.com/necolas/normalize.css/blob/master/LICENSE.md)
|
||||||
|
*/*,::after,::before{box-sizing:border-box}html{font-family:sans-serif;line-height:1.15;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;-ms-overflow-style:scrollbar;-webkit-tap-highlight-color:transparent}@-ms-viewport{width:device-width}article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}body{margin:0;font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol";font-size:1rem;font-weight:400;line-height:1.5;color:#212529;text-align:left;background-color:#fff}[tabindex="-1"]:focus{outline:0!important}hr{box-sizing:content-box;height:0;overflow:visible}h1,h2,h3,h4,h5,h6{margin-top:0;margin-bottom:.5rem}p{margin-top:0;margin-bottom:1rem}abbr[data-original-title],abbr[title]{text-decoration:underline;-webkit-text-decoration:underline dotted;text-decoration:underline dotted;cursor:help;border-bottom:0}address{margin-bottom:1rem;font-style:normal;line-height:inherit}dl,ol,ul{margin-top:0;margin-bottom:1rem}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}dt{font-weight:700}dd{margin-bottom:.5rem;margin-left:0}blockquote{margin:0 0 1rem}dfn{font-style:italic}b,strong{font-weight:bolder}small{font-size:80%}sub,sup{position:relative;font-size:75%;line-height:0;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}a{color:#007bff;text-decoration:none;background-color:transparent;-webkit-text-decoration-skip:objects}a:hover{color:#0056b3;text-decoration:underline}a:not([href]):not([tabindex]){color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus,a:not([href]):not([tabindex]):hover{color:inherit;text-decoration:none}a:not([href]):not([tabindex]):focus{outline:0}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}pre{margin-top:0;margin-bottom:1rem;overflow:auto;-ms-overflow-style:scrollbar}figure{margin:0 0 1rem}img{vertical-align:middle;border-style:none}svg:not(:root){overflow:hidden}table{border-collapse:collapse}caption{padding-top:.75rem;padding-bottom:.75rem;color:#6c757d;text-align:left;caption-side:bottom}th{text-align:inherit}label{display:inline-block;margin-bottom:.5rem}button{border-radius:0}button:focus{outline:1px dotted;outline:5px auto -webkit-focus-ring-color}button,input,optgroup,select,textarea{margin:0;font-family:inherit;font-size:inherit;line-height:inherit}button,input{overflow:visible}button,select{text-transform:none}[type=reset],[type=submit],button,html [type=button]{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{padding:0;border-style:none}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=date],input[type=datetime-local],input[type=month],input[type=time]{-webkit-appearance:listbox}textarea{overflow:auto;resize:vertical}fieldset{min-width:0;padding:0;margin:0;border:0}legend{display:block;width:100%;max-width:100%;padding:0;margin-bottom:.5rem;font-size:1.5rem;line-height:inherit;color:inherit;white-space:normal}progress{vertical-align:baseline}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{outline-offset:-2px;-webkit-appearance:none}[type=search]::-webkit-search-cancel-button,[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{font:inherit;-webkit-appearance:button}output{display:inline-block}summary{display:list-item;cursor:pointer}template{display:none}[hidden]{display:none!important}
|
||||||
|
/*# sourceMappingURL=bootstrap-reboot.min.css.map */
|
1
backend/web/static/css/bootstrap-reboot.min.css.map
Normal file
1
backend/web/static/css/bootstrap-reboot.min.css.map
Normal file
File diff suppressed because one or more lines are too long
8975
backend/web/static/css/bootstrap.css
vendored
Normal file
8975
backend/web/static/css/bootstrap.css
vendored
Normal file
File diff suppressed because it is too large
Load diff
1
backend/web/static/css/bootstrap.css.map
Normal file
1
backend/web/static/css/bootstrap.css.map
Normal file
File diff suppressed because one or more lines are too long
7
backend/web/static/css/bootstrap.min.css
vendored
Normal file
7
backend/web/static/css/bootstrap.min.css
vendored
Normal file
File diff suppressed because one or more lines are too long
1
backend/web/static/css/bootstrap.min.css.map
Normal file
1
backend/web/static/css/bootstrap.min.css.map
Normal file
File diff suppressed because one or more lines are too long
6328
backend/web/static/js/bootstrap.bundle.js
vendored
Normal file
6328
backend/web/static/js/bootstrap.bundle.js
vendored
Normal file
File diff suppressed because it is too large
Load diff
1
backend/web/static/js/bootstrap.bundle.js.map
Normal file
1
backend/web/static/js/bootstrap.bundle.js.map
Normal file
File diff suppressed because one or more lines are too long
7
backend/web/static/js/bootstrap.bundle.min.js
vendored
Normal file
7
backend/web/static/js/bootstrap.bundle.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
backend/web/static/js/bootstrap.bundle.min.js.map
Normal file
1
backend/web/static/js/bootstrap.bundle.min.js.map
Normal file
File diff suppressed because one or more lines are too long
3894
backend/web/static/js/bootstrap.js
vendored
Normal file
3894
backend/web/static/js/bootstrap.js
vendored
Normal file
File diff suppressed because it is too large
Load diff
1
backend/web/static/js/bootstrap.js.map
Normal file
1
backend/web/static/js/bootstrap.js.map
Normal file
File diff suppressed because one or more lines are too long
7
backend/web/static/js/bootstrap.min.js
vendored
Normal file
7
backend/web/static/js/bootstrap.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
1
backend/web/static/js/bootstrap.min.js.map
Normal file
1
backend/web/static/js/bootstrap.min.js.map
Normal file
File diff suppressed because one or more lines are too long
2
backend/web/static/js/jquery-3.6.0.min.js
vendored
Normal file
2
backend/web/static/js/jquery-3.6.0.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
2
backend/web/static/js/js.cookie.min.js
vendored
Normal file
2
backend/web/static/js/js.cookie.min.js
vendored
Normal file
|
@ -0,0 +1,2 @@
|
||||||
|
/*! js-cookie v3.0.1 | MIT */
|
||||||
|
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e=e||self,function(){var n=e.Cookies,o=e.Cookies=t();o.noConflict=function(){return e.Cookies=n,o}}())}(this,(function(){"use strict";function e(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)e[o]=n[o]}return e}return function t(n,o){function r(t,r,i){if("undefined"!=typeof document){"number"==typeof(i=e({},o,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),t=encodeURIComponent(t).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var c="";for(var u in i)i[u]&&(c+="; "+u,!0!==i[u]&&(c+="="+i[u].split(";")[0]));return document.cookie=t+"="+n.write(r,t)+c}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var t=document.cookie?document.cookie.split("; "):[],o={},r=0;r<t.length;r++){var i=t[r].split("="),c=i.slice(1).join("=");try{var u=decodeURIComponent(i[0]);if(o[u]=n.read(c,u),e===u)break}catch(e){}}return e?o[e]:o}},remove:function(t,n){r(t,"",e({},n,{expires:-1}))},withAttributes:function(n){return t(this.converter,e({},this.attributes,n))},withConverter:function(n){return t(e({},this.converter,n),this.attributes)}},{attributes:{value:Object.freeze(o)},converter:{value:Object.freeze(n)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"})}));
|
9
backend/web/static/logo.svg
Normal file
9
backend/web/static/logo.svg
Normal file
|
@ -0,0 +1,9 @@
|
||||||
|
<svg width="151" height="44" viewBox="0 0 151 44" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||||
|
<rect width="151" height="44" fill="transparent"/>
|
||||||
|
<path d="M40.8246 11.7373C37.2206 11.7373 34.89 13.5633 34.89 16.6388C34.89 19.7142 36.8842 20.8915 40.4162 21.6604L40.9688 21.7805C43.1312 22.2611 44.2604 22.7416 44.2604 24.1351C44.2604 25.4806 43.1792 26.4417 41.0168 26.4417C38.8544 26.4417 37.5329 25.4326 37.5329 23.4143V23.1741H34.4094V23.4143C34.4094 27.0664 37.1245 29.2288 41.0168 29.2288C44.9092 29.2288 47.3839 27.1145 47.3839 24.039C47.3839 20.9636 45.1014 19.7142 41.5214 18.9454L40.9688 18.8252C38.9025 18.3687 38.0135 17.7921 38.0135 16.5427C38.0135 15.2933 38.9025 14.5244 40.8246 14.5244C42.7468 14.5244 43.9241 15.2933 43.9241 17.2154V17.5998H47.0476V17.2154C47.0476 13.5633 44.4286 11.7373 40.8246 11.7373ZM47.5746 19.4259H50.554V26.2015C50.554 27.8353 51.6112 28.8925 53.1969 28.8925H56.5607V26.4417H54.2541C53.8216 26.4417 53.5814 26.2015 53.5814 25.7209V19.4259H56.849V16.9752H53.5814V13.275H50.554V16.9752H47.5746V19.4259ZM69.9725 28.8925V16.9752H66.9932V18.5849H66.7529C66.0321 17.5518 64.8788 16.6388 62.8125 16.6388C59.9774 16.6388 57.4305 19.0415 57.4305 22.9338C57.4305 26.8261 59.9774 29.2288 62.8125 29.2288C64.8788 29.2288 66.0321 28.3158 66.7529 27.2827H66.9932V28.8925H69.9725ZM63.7256 26.6339C61.8515 26.6339 60.4579 25.2884 60.4579 22.9338C60.4579 20.5792 61.8515 19.2337 63.7256 19.2337C65.5996 19.2337 66.9932 20.5792 66.9932 22.9338C66.9932 25.2884 65.5996 26.6339 63.7256 26.6339ZM71.4505 22.9338C71.4505 26.6339 74.1896 29.2288 77.6495 29.2288C80.9892 29.2288 82.9354 27.2827 83.6081 24.6637L80.6768 23.967C80.4126 25.5047 79.5236 26.5859 77.6975 26.5859C75.8715 26.5859 74.4779 25.2404 74.4779 22.9338C74.4779 20.6272 75.8715 19.2817 77.6975 19.2817C79.5236 19.2817 80.4126 20.435 80.5807 21.8766L83.512 21.2519C82.9834 18.5849 80.9652 16.6388 77.6495 16.6388C74.1896 16.6388 71.4505 19.2337 71.4505 22.9338ZM97.4406 16.9752H92.9716L88.0221 21.348V12.0737H84.9947V28.8925H88.0221V25.0241L89.68 23.6066L93.6204 28.8925H97.3445L91.8424 21.7565L97.4406 16.9752ZM98.2594 20.3149C98.2594 22.6695 100.23 23.5345 102.728 24.015L103.353 24.1351C104.843 24.4235 105.516 24.7839 105.516 25.5527C105.516 26.3216 104.843 26.9223 103.449 26.9223C102.056 26.9223 100.926 26.3456 100.614 24.6157L97.8269 25.3365C98.2354 27.8353 100.326 29.2288 103.449 29.2288C106.477 29.2288 108.447 27.8112 108.447 25.3125C108.447 22.8137 106.429 22.1409 103.738 21.6123L103.113 21.4922C101.863 21.2519 101.191 20.9156 101.191 20.1227C101.191 19.4019 101.815 18.9454 102.969 18.9454C104.122 18.9454 104.939 19.4259 105.227 20.7233L107.966 19.8824C107.39 17.9603 105.636 16.6388 102.969 16.6388C100.134 16.6388 98.2594 17.9603 98.2594 20.3149ZM109.985 33.6978H113.012V27.3547H113.252C113.925 28.3158 115.078 29.2288 117.145 29.2288C119.98 29.2288 122.527 26.8261 122.527 22.9338C122.527 19.0415 119.98 16.6388 117.145 16.6388C115.078 16.6388 113.925 17.5518 113.204 18.5849H112.964V16.9752H109.985V33.6978ZM116.231 26.6339C114.357 26.6339 112.964 25.2884 112.964 22.9338C112.964 20.5792 114.357 19.2337 116.231 19.2337C118.106 19.2337 119.499 20.5792 119.499 22.9338C119.499 25.2884 118.106 26.6339 116.231 26.6339ZM123.38 13.5153C123.38 14.7407 124.317 15.5816 125.518 15.5816C126.72 15.5816 127.657 14.7407 127.657 13.5153C127.657 12.2899 126.72 11.449 125.518 11.449C124.317 11.449 123.38 12.2899 123.38 13.5153ZM127.032 16.9752H124.005V28.8925H127.032V16.9752ZM129.249 16.9752V28.8925H132.277V22.7416C132.277 20.5311 133.358 19.2337 135.208 19.2337C136.842 19.2337 137.755 20.1227 137.755 21.9247V28.8925H140.782V21.7805C140.782 18.8252 138.932 16.7829 136.145 16.7829C133.958 16.7829 132.949 17.744 132.469 18.7531H132.228V16.9752H129.249Z" fill="#2D535A"/>
|
||||||
|
<path d="M0 35.1171C0 39.0948 4.18188 41.6853 7.74332 39.9138L22.8687 32.39C24.0424 31.8062 24.7844 30.6083 24.7844 29.2975V20.9534L1.64288 32.4649C0.636359 32.9656 0 33.9929 0 35.1171Z" fill="#2D535A"/>
|
||||||
|
<path d="M0 22.8091C0 27.6308 5.06914 30.7709 9.38621 28.6235L24.7844 20.9641C24.7844 16.1423 19.7151 13.0021 15.398 15.1496L0 22.8091Z" fill="#54C6CC"/>
|
||||||
|
<path d="M2.2161 21.7068C0.858395 22.3821 -0.103566 23.8187 0.458285 25.2271C1.79955 28.5895 5.84578 30.3846 9.38621 28.6235L24.7844 20.9641C24.7844 16.1423 19.7151 13.0021 15.398 15.1496L2.2161 21.7068Z" fill="#2D535A"/>
|
||||||
|
<path d="M2.2161 21.7068C0.858395 22.3821 -0.103566 23.8187 0.458285 25.2271C1.79955 28.5895 5.84578 30.3846 9.38621 28.6235L22.5683 22.0664C23.926 21.3911 24.888 19.9545 24.3261 18.546C22.9848 15.1836 18.9385 13.3884 15.398 15.1496L2.2161 21.7068Z" fill="#1E8290"/>
|
||||||
|
<path d="M0 22.8121L23.3077 11.2182C24.2124 10.7682 24.7844 9.8448 24.7844 8.83432C24.7844 4.77111 20.5126 2.12495 16.8747 3.93462L2.25625 11.2064C0.873945 11.894 0 13.3048 0 14.8487V22.8121Z" fill="#54C6CC"/>
|
||||||
|
</svg>
|
Before Width: | Height: | Size: 4.7 KiB After Width: | Height: | Size: 4.7 KiB |
12
backend/web/static/style.css
vendored
Normal file
12
backend/web/static/style.css
vendored
Normal file
|
@ -0,0 +1,12 @@
|
||||||
|
|
||||||
|
|
||||||
|
div.loginpanel {
|
||||||
|
width: 644px;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
margin-top: 100px;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
margin-top: 10px;
|
||||||
|
}
|
40
backend/web/templates/base.html
Normal file
40
backend/web/templates/base.html
Normal file
|
@ -0,0 +1,40 @@
|
||||||
|
<!doctype html>
|
||||||
|
<html>
|
||||||
|
<link rel="stylesheet" href="static/css/bootstrap.min.css">
|
||||||
|
<link rel="stylesheet" href="static/style.css">
|
||||||
|
<script src="static/js/bootstrap.bundle.min.js"></script>
|
||||||
|
<script src="static/js/jquery-3.6.0.min.js"></script>
|
||||||
|
<script src="static/js/js.cookie.min.js"></script>
|
||||||
|
<script src="static/base.js"></script>
|
||||||
|
<title>Stackspin Account</title>
|
||||||
|
</html>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var api_url = '{{ api_url }}';
|
||||||
|
|
||||||
|
// Actions
|
||||||
|
$(document).ready(function() {
|
||||||
|
check_flow_expired();
|
||||||
|
});
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<div class="loginpanel">
|
||||||
|
|
||||||
|
<div id="contentFlowExpired"
|
||||||
|
class='alert alert-warning'
|
||||||
|
style='display:none'>Your request is expired. Please resubmit your request faster.</div>
|
||||||
|
|
||||||
|
|
||||||
|
<img src='static/logo.svg'/><br/><br/>
|
||||||
|
|
||||||
|
{% block content %}{% endblock %}
|
||||||
|
|
||||||
|
|
||||||
|
</div>
|
23
backend/web/templates/error.html
Normal file
23
backend/web/templates/error.html
Normal file
|
@ -0,0 +1,23 @@
|
||||||
|
{% extends 'base.html' %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var api_url = '{{ api_url }}';
|
||||||
|
|
||||||
|
// Actions
|
||||||
|
$(document).ready(function() {
|
||||||
|
flow_settings();
|
||||||
|
});
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<h2>Error: {{ error_message['error']['status'] }}</h2>
|
||||||
|
|
||||||
|
|
||||||
|
<div class=error-div>
|
||||||
|
{{ error_message['error']['message'] }}
|
||||||
|
{{ error_message['error']['reason'] }}
|
||||||
|
</div>
|
||||||
|
{% endblock %}
|
||||||
|
|
24
backend/web/templates/loggedin.html
Normal file
24
backend/web/templates/loggedin.html
Normal file
|
@ -0,0 +1,24 @@
|
||||||
|
{% extends 'base.html' %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var api_url = '{{ api_url }}';
|
||||||
|
|
||||||
|
// Actions
|
||||||
|
$(document).ready(function() {
|
||||||
|
//flow_login();
|
||||||
|
check_flow_auth();
|
||||||
|
});
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<div id="contentMessages"></div>
|
||||||
|
<div id="contentWelcome">
|
||||||
|
Welcome{{ name }}, you are logged in.
|
||||||
|
</div>
|
||||||
|
|
||||||
|
|
||||||
|
{% endblock %}
|
25
backend/web/templates/login.html
Normal file
25
backend/web/templates/login.html
Normal file
|
@ -0,0 +1,25 @@
|
||||||
|
|
||||||
|
|
||||||
|
{% extends 'base.html' %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var api_url = '{{ api_url }}';
|
||||||
|
|
||||||
|
// Actions
|
||||||
|
$(document).ready(function() {
|
||||||
|
flow_login();
|
||||||
|
});
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<div id="contentMessages"></div>
|
||||||
|
<div id="contentLogin"></div>
|
||||||
|
<div id="contentHelp">
|
||||||
|
<a href='recovery'>Set new password</a> | <a href='https://stackspin.net'>About stackspin</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% endblock %}
|
29
backend/web/templates/recover.html
Normal file
29
backend/web/templates/recover.html
Normal file
|
@ -0,0 +1,29 @@
|
||||||
|
|
||||||
|
|
||||||
|
{% extends 'base.html' %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var api_url = '{{ api_url }}';
|
||||||
|
|
||||||
|
// Actions
|
||||||
|
$(document).ready(function() {
|
||||||
|
flow_recover();
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<div id="contentMessages"></div>
|
||||||
|
<div id="contentRecover"></div>
|
||||||
|
<div id="contentRecoverRequested" style='display:none'>
|
||||||
|
Thank you for your request. We have sent you an email to recover
|
||||||
|
your account. Please check your e-mail and complete the account
|
||||||
|
recovery. You have limited time to complete this</div>
|
||||||
|
|
||||||
|
<div id="contentHelp">
|
||||||
|
<a href='login'>Back to login page</a> | <a href='https://stackspin.org'>About stackspin</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% endblock %}
|
30
backend/web/templates/settings.html
Normal file
30
backend/web/templates/settings.html
Normal file
|
@ -0,0 +1,30 @@
|
||||||
|
|
||||||
|
|
||||||
|
{% extends 'base.html' %}
|
||||||
|
|
||||||
|
{% block content %}
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var api_url = '{{ api_url }}';
|
||||||
|
|
||||||
|
// Actions
|
||||||
|
$(document).ready(function() {
|
||||||
|
flow_settings();
|
||||||
|
});
|
||||||
|
|
||||||
|
</script>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
<div id="contentMessages"></div>
|
||||||
|
<div id="contentProfileSaved"
|
||||||
|
class='alert alert-success'
|
||||||
|
style='display:none'>Successfuly saved new settings.</div>
|
||||||
|
<div id="contentProfileSaveFailed"
|
||||||
|
class='alert alert-danger'
|
||||||
|
style='display:none'>Your changes are not saved. Please check the fields for errors.</div>
|
||||||
|
<div id="contentProfile"></div>
|
||||||
|
<div id="contentPassword"></div>
|
||||||
|
|
||||||
|
|
||||||
|
{% endblock %}
|
Loading…
Reference in a new issue