Compare commits

..

No commits in common. "main" and "chart" have entirely different histories.
main ... chart

41 changed files with 555 additions and 5171 deletions

View File

@ -1,8 +1,5 @@
FROM golang:alpine as builder
ARG HOSTNAME=http://localhost
ARG NAME=local
WORKDIR /app
COPY . .

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) <year> <copyright holders>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@ -1,660 +0,0 @@
# GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
## Preamble
The GNU 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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 <https://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 <https://www.gnu.org/licenses/>.

Binary file not shown.

View File

@ -1,9 +0,0 @@
{
"port": 8080,
"MONGO_URL":"mongodb://localhost:27017/",
"MONGO_DATABASE":"DC_myDC",
"natsurl":"http://localhost:4080",
"login":"admin",
"password":"admin",
"oidcserver":"http://localhost:8080"
}

View File

@ -3,26 +3,10 @@ package conf
import "sync"
type Config struct {
AdminRole string
PublicKeyPath string
PrivateKeyPath string
LDAPEndpoints string
LDAPBindDN string
LDAPBindPW string
LDAPBaseDN string
LDAPRoleBaseDN string
ClientSecret string
Auth string
AuthConnectorHost string
AuthConnectorPort int
AuthConnectorAdminPort int
PermissionConnectorHost string
PermissionConnectorPort int
PermissionConnectorAdminPort int
NatsUrl string
NatsLogin string
NatsPassword string
OidcUrl string
}
var instance *Config

60
controllers/auth.go Normal file
View File

@ -0,0 +1,60 @@
package controllers
import (
"fmt"
beego "github.com/beego/beego/v2/server/web"
)
// Operations about auth
type AuthController struct {
beego.Controller
}
// @Title Create
// @Description create auths
// @Param body body []models.auth true "The auth content"
// @Success 200 {string} models.auth.Id
// @Failure 403 body is empty
// @router / [post]
func (o *AuthController) Post() {
// store and return Id or post with UUID
o.Data["json"] = map[string]string{"Id": "?"}
o.ServeJSON()
}
// @Title Get
// @Description find auth by authid
// @Param authId path string true "the authid you want to get"
// @Success 200 {auth} models.auth
// @Failure 403 :authId is empty
// @router /:authId [get]
func (o *AuthController) Get() {
authId := o.Ctx.Input.Param(":authId")
fmt.Println(authId)
o.ServeJSON()
}
// @Title Find
// @Description find auths with query
// @Param query path string true "the keywords you need"
// @Success 200 {auths} []models.auth
// @Failure 403
// @router /find/:query [get]
func (o *AuthController) Find() {
query := o.Ctx.Input.Param(":query")
fmt.Println(query)
o.ServeJSON()
}
// @Title Delete
// @Description delete the auth
// @Param authId path string true "The authId you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 authId is empty
// @router /:authId [delete]
func (o *AuthController) Delete() {
authId := o.Ctx.Input.Param(":authId")
fmt.Println(authId)
o.ServeJSON()
}

View File

@ -1,192 +0,0 @@
package controllers
import (
"encoding/json"
"fmt"
"net/http"
"oc-auth/infrastructure"
auth_connectors "oc-auth/infrastructure/auth_connector"
"regexp"
"strings"
oclib "cloud.o-forge.io/core/oc-lib"
model "cloud.o-forge.io/core/oc-lib/models/peer"
beego "github.com/beego/beego/v2/server/web"
)
// Operations about auth
type OAuthController struct {
beego.Controller
}
// @Title Logout
// @Description unauthenticate user
// @Param Authorization header string false "auth token"
// @Success 200 {string}
// @router /ldap/logout [delete]
func (o *OAuthController) LogOutLDAP() {
// authorize user
reqToken := o.Ctx.Request.Header.Get("Authorization")
splitToken := strings.Split(reqToken, "Bearer ")
if len(splitToken) < 2 {
reqToken = ""
} else {
reqToken = splitToken[1]
}
var res auth_connectors.Token
json.Unmarshal(o.Ctx.Input.CopyBody(10000000), &res)
token, err := infrastructure.GetAuthConnector().Logout(reqToken)
if err != nil || token == nil {
o.Data["json"] = err
} else {
o.Data["json"] = token
}
o.ServeJSON()
}
// @Title Login
// @Description authenticate user
// @Param body body models.workflow true "The workflow content"
// @Success 200 {string}
// @router /ldap/login [post]
func (o *OAuthController) LoginLDAP() {
// authorize user
var res auth_connectors.Token
json.Unmarshal(o.Ctx.Input.CopyBody(10000000), &res)
ldap := auth_connectors.New()
found, err := ldap.Authenticate(o.Ctx.Request.Context(), res.Username, res.Password)
if err != nil || !found {
o.Data["json"] = err
o.Ctx.ResponseWriter.WriteHeader(401)
o.ServeJSON()
return
}
token, err := infrastructure.GetAuthConnector().Login(res.Username,
&http.Cookie{ // open a session
Name: "csrf_token",
Value: o.XSRFToken(),
})
if err != nil || token == nil {
o.Data["json"] = err
o.Ctx.ResponseWriter.WriteHeader(401)
} else {
o.Data["json"] = token
}
o.ServeJSON()
}
// @Title Introspection
// @Description introspect token
// @Param body body models.Token true "The token info"
// @Success 200 {string}
// @router /refresh [post]
func (o *OAuthController) Refresh() {
var token auth_connectors.Token
json.Unmarshal(o.Ctx.Input.CopyBody(100000), &token)
// refresh token
newToken, err := infrastructure.GetAuthConnector().Refresh(&token)
if err != nil || newToken == nil {
o.Data["json"] = err
o.Ctx.ResponseWriter.WriteHeader(401)
} else {
o.Data["json"] = newToken
}
o.ServeJSON()
}
// @Title Introspection
// @Description introspect token
// @Param Authorization header string false "auth token"
// @Success 200 {string}
// @router /introspect [get]
func (o *OAuthController) Introspect() {
reqToken := o.Ctx.Request.Header.Get("Authorization")
splitToken := strings.Split(reqToken, "Bearer ")
if len(splitToken) < 2 {
reqToken = ""
} else {
reqToken = splitToken[1]
}
token, err := infrastructure.GetAuthConnector().Introspect(reqToken)
if err != nil || !token {
o.Data["json"] = err
o.Ctx.ResponseWriter.WriteHeader(401)
}
o.ServeJSON()
}
var whitelist = []string{
"/login",
"/refresh",
"/introspect",
}
// @Title AuthForward
// @Description auth forward
// @Param Authorization header string false "auth token"
// @Success 200 {string}
// @router /forward [get]
func (o *OAuthController) InternalAuthForward() {
fmt.Println("InternalAuthForward")
reqToken := o.Ctx.Request.Header.Get("Authorization")
if reqToken == "" {
for _, w := range whitelist {
if strings.Contains(o.Ctx.Request.Header.Get("X-Forwarded-Uri"), w) {
o.Ctx.ResponseWriter.WriteHeader(200)
o.ServeJSON()
return
}
}
o.Ctx.ResponseWriter.WriteHeader(401)
o.ServeJSON()
return
}
splitToken := strings.Split(reqToken, "Bearer ")
if len(splitToken) < 2 {
reqToken = ""
} else {
reqToken = splitToken[1]
}
origin, publicKey, external := o.extractOrigin()
if !infrastructure.GetAuthConnector().CheckAuthForward( //reqToken != "" &&
reqToken, publicKey, origin,
o.Ctx.Request.Header.Get("X-Forwarded-Method"),
o.Ctx.Request.Header.Get("X-Forwarded-Uri"), external) && origin != "" && publicKey != "" {
o.Ctx.ResponseWriter.WriteHeader(401)
o.ServeJSON()
return
}
o.ServeJSON()
}
func (o *OAuthController) extractOrigin() (string, string, bool) {
external := true
publicKey := ""
origin := o.Ctx.Request.Header.Get("X-Forwarded-Host")
if origin == "" {
origin = o.Ctx.Request.Header.Get("Origin")
}
searchStr := origin
r := regexp.MustCompile("(:[0-9]+)")
t := r.FindString(searchStr)
if t != "" {
searchStr = strings.Replace(searchStr, t, "", -1)
}
peer := oclib.Search(nil, searchStr, oclib.LibDataEnum(oclib.PEER))
if peer.Code != 200 || len(peer.Data) == 0 { // TODO: add state of partnership
return "", "", external
}
p := peer.Data[0].(*model.Peer)
publicKey = p.PublicKey
origin = p.Url
if origin != "" { // is external
if strings.Contains(origin, "localhost") || strings.Contains(origin, "127.0.0.1") || p.State == model.SELF {
external = false
}
} else {
external = false
}
return origin, publicKey, external
}

View File

@ -1,192 +0,0 @@
package controllers
import (
"oc-auth/infrastructure"
beego "github.com/beego/beego/v2/server/web"
)
// Operations about auth
type PermissionController struct {
beego.Controller
}
// @Title GetAll
// @Description find permissions
// @Success 200 {permission} string
// @router / [get]
func (o *PermissionController) GetAll() {
role, err := infrastructure.GetPermissionConnector().GetPermission("", "")
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title GetByRole
// @Description find permission by role id
// @Param id path string true "the id you want to get"
// @Success 200 {auth} string
// @router /role/:id [get]
func (o *PermissionController) GetByRole() {
id := o.Ctx.Input.Param(":id")
role, err := infrastructure.GetPermissionConnector().GetPermissionByRole(id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title GetByUser
// @Description find permission by user id
// @Param id path string true "the id you want to get"
// @Success 200 {auth} string
// @router /user/:id [get]
func (o *PermissionController) GetByUser() {
id := o.Ctx.Input.Param(":id")
role, err := infrastructure.GetPermissionConnector().GetPermissionByUser(id, true)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Get
// @Description find auth by permission
// @Param id path string true "the permission you want to get"
// @Success 200 {auth} models.auth
// @router /:id/:relation [get]
func (o *PermissionController) Get() {
id := o.Ctx.Input.Param(":id")
rel := o.Ctx.Input.Param(":relation")
role, err := infrastructure.GetPermissionConnector().GetPermission(id, rel)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Clear
// @Description clear the permission
// @Success 200 {string} delete success!
// @router /clear [delete]
func (o *PermissionController) Clear() {
role, code, err := infrastructure.GetPermissionConnector().DeletePermission("", "", true)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Bind
// @Description bind the permission to role
// @Param role_id path string true "The role_id you want to bind"
// @Param method path string true "The method you want to relate role & permission"
// @Param permission_id path string true "The permission_id you want to bind"
// @Success 200 {string} bind success!
// @router /:permission_id/:role_id/:relation [post]
func (o *PermissionController) Bind() {
permission_id := o.Ctx.Input.Param(":permission_id")
role_id := o.Ctx.Input.Param(":role_id")
rel := o.Ctx.Input.Param(":relation")
role, code, err := infrastructure.GetPermissionConnector().BindPermission(role_id, permission_id, rel)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title UnBind
// @Description unbind the permission to role
// @Param role_id path string true "The role_id you want to unbind"
// @Param relation path string true "The method you want to unrelate role & permission"
// @Param permission_id path string true "The permission_id you want to unbind"
// @Success 200 {string} bind success!
// @router /:permission_id/:role_id/:relation [delete]
func (o *PermissionController) UnBind() {
permission_id := o.Ctx.Input.Param(":permission_id")
role_id := o.Ctx.Input.Param(":role_id")
rel := o.Ctx.Input.Param(":relation")
role, code, err := infrastructure.GetPermissionConnector().UnBindPermission(role_id, permission_id, rel)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}

View File

@ -0,0 +1,52 @@
package controllers
import (
"encoding/json"
"log"
"oc-auth/models"
"strings"
beego "github.com/beego/beego/v2/server/web"
"github.com/nats-io/nats.go"
)
// Operations about auth
type RegistrationController struct {
beego.Controller
}
// @Title Create
// @Description create auths
// @Param body body models.Application true "The app info"
// @Success 200 {string} models.auth.Id
// @Failure 403 body is empty
// @router / [post]
func (o *RegistrationController) Post() {
var app models.Application
// Store the app info in the nats server
err := json.Unmarshal(o.Ctx.Input.RequestBody, &app)
if err != nil {
log.Fatal(err)
}
servers := []string{"nats://127.0.0.1:1222", "nats://127.0.0.1:1223", "nats://127.0.0.1:1224"}
nc, err := nats.Connect(strings.Join(servers, ","))
if err != nil {
log.Fatal(err)
}
defer nc.Close()
js, err := nc.JetStream(nats.PublishAsyncMaxPending(256))
if err != nil {
log.Fatal(err)
}
kv, err := js.KeyValue("auth")
if err != nil {
log.Fatal(err)
}
kv.Put(app.ClientId, o.Ctx.Input.RequestBody)
// register to OIDC server
// store and return Id or post with UUID
o.Data["json"] = map[string]string{"Id": "?"}
o.ServeJSON()
}

View File

@ -1,213 +0,0 @@
package controllers
import (
"oc-auth/infrastructure"
beego "github.com/beego/beego/v2/server/web"
)
// Operations about auth
type RoleController struct {
beego.Controller
}
// @Title Create
// @Description create role
// @Param id path string true "the id you want to get"
// @Success 200 {auth} create success!
// @router /:id [post]
func (o *RoleController) Post() {
// store and return Id or post with UUID
id := o.Ctx.Input.Param(":id")
role, code, err := infrastructure.GetPermissionConnector().CreateRole(id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title GetByUser
// @Description find role by user id
// @Param id path string true "the id you want to get"
// @Success 200 {auth} string
// @router /user/:id [get]
func (o *RoleController) GetByUser() {
id := o.Ctx.Input.Param(":id")
role, err := infrastructure.GetPermissionConnector().GetRoleByUser(id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title GetAll
// @Description find roles
// @Success 200 {role} string
// @router / [get]
func (o *RoleController) GetAll() {
role, err := infrastructure.GetPermissionConnector().GetRole("")
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Get
// @Description find role by id
// @Param id path string true "the id you want to get"
// @Success 200 {role} string
// @router /:id [get]
func (o *RoleController) Get() {
id := o.Ctx.Input.Param(":id")
role, err := infrastructure.GetPermissionConnector().GetRole(id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": 200,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Delete
// @Description delete the role
// @Param id path string true "The id you want to delete"
// @Success 200 {string} delete success!
// @router /:id [delete]
func (o *RoleController) Delete() {
id := o.Ctx.Input.Param(":id")
role, code, err := infrastructure.GetPermissionConnector().DeleteRole(id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Clear
// @Description clear the role
// @Success 200 {string} delete success!
// @router /clear [delete]
func (o *RoleController) Clear() {
role, code, err := infrastructure.GetPermissionConnector().DeleteRole("")
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title Bind
// @Description bind the role to user
// @Param user_id path string true "The user_id you want to bind"
// @Param role_id path string true "The role_id you want to bind"
// @Success 200 {string} bind success!
// @router /:user_id/:role_id [post]
func (o *RoleController) Bind() {
user_id := o.Ctx.Input.Param(":user_id")
role_id := o.Ctx.Input.Param(":role_id")
role, code, err := infrastructure.GetPermissionConnector().BindRole(user_id, role_id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}
// @Title UnBind
// @Description unbind the role to user
// @Param role_id path string true "The role_id you want to unbind"
// @Param user_id path string true "The user_id you want to unbind"
// @Success 200 {string} bind success!
// @router /:user_id/:role_id [delete]
func (o *RoleController) UnBind() {
user_id := o.Ctx.Input.Param(":user_id")
role_id := o.Ctx.Input.Param(":role_id")
role, code, err := infrastructure.GetPermissionConnector().UnBindRole(user_id, role_id)
if err != nil {
o.Data["json"] = map[string]interface{}{
"data": nil,
"error": err.Error(),
"code": code,
}
} else {
o.Data["json"] = map[string]interface{}{
"data": role,
"error": nil,
"code": 200,
}
}
o.ServeJSON()
}

View File

@ -17,12 +17,3 @@ func (c *VersionController) GetAll() {
c.Data["json"] = map[string]string{"version": "1"}
c.ServeJSON()
}
// @Title Get
// @Description get version
// @Success 200
// @router /discovery [get]
func (c *VersionController) Get() {
c.Data["json"] = map[string]string{"version": "1"}
c.ServeJSON()
}

View File

@ -1,41 +1,10 @@
version: '3.4'
services:
traefik:
image: traefik:v2.10.4
container_name: traefik
networks:
- catalog
command:
- "--api.insecure=true"
- "--providers.docker=true"
- "--providers.docker.exposedbydefault=false"
- "--entrypoints.web.address=:80"
- "--log.level=DEBUG"
ocauth:
image: 'ocauth:latest'
ports:
- "8080:80"
- "8082:8080"
volumes:
- /var/run/docker.sock:/var/run/docker.sock
oc-auth:
image: 'oc-auth:latest'
ports:
- 8094:8080
container_name: oc-auth
labels:
- "traefik.enable=true"
- "traefik.http.middlewares.auth.forwardauth.address=http://oc-auth:8080/oc/forward"
- "traefik.http.routers.workflow.rule=PathPrefix(/auth)"
environment:
LDAP_ENDPOINTS: ldap:389
LDAP_BINDDN: cn=admin,dc=example,dc=com
LDAP_BINDPW: password
LDAP_BASEDN: "dc=example,dc=com"
LDAP_ROLE_BASEDN: "ou=AppRoles,dc=example,dc=com"
networks:
- catalog
volumes:
- ./pem:/etc/oc/pem
networks:
catalog:
external: true
- 8088:8080
container_name: ocauth

View File

@ -1,10 +1,6 @@
{
"MONGO_URL":"mongodb://mongo:27017/",
"MONGO_DATABASE":"DC_myDC",
"NATS_URL": "nats://nats:4222",
"PORT" : 8080,
"AUTH_CONNECTOR_HOST": "hydra",
"PRIVATE_KEY_PATH": "/etc/oc/pem/private.pem",
"PUBLIC_KEY_PATH": "/etc/oc/pem/public.pem",
"LDAP_ENDPOINTS": "ldap:389"
"natsurl":"http://localhost:4080",
"login":"admin",
"password":"admin",
"oidcserver":"http://localhost:8080"
}

141
go.mod
View File

@ -1,134 +1,41 @@
module oc-auth
go 1.22.0
go 1.19
require (
cloud.o-forge.io/core/oc-lib v0.0.0-20241108104423-7fd44a55cb28
github.com/beego/beego/v2 v2.3.1
github.com/nats-io/nats.go v1.37.0
github.com/ory/hydra-client-go v1.11.8
github.com/beego/beego v1.12.11
github.com/beego/beego/v2 v2.0.7
github.com/goraz/onion v0.1.3
github.com/nats-io/nats.go v1.36.0
github.com/smartystreets/goconvey v1.7.2
go.uber.org/zap v1.27.0
golang.org/x/oauth2 v0.23.0
)
require (
github.com/Azure/go-ntlmssp v0.0.0-20221128193559-754e69321358 // indirect
github.com/asaskevich/govalidator v0.0.0-20230301143203-a9d515a09cc2 // indirect
github.com/cenkalti/backoff/v4 v4.2.1 // indirect
github.com/dgraph-io/ristretto v0.1.1 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/felixge/httpsnoop v1.0.3 // indirect
github.com/fsnotify/fsnotify v1.6.0 // indirect
github.com/go-asn1-ber/asn1-ber v1.5.5 // indirect
github.com/go-jose/go-jose/v3 v3.0.3 // indirect
github.com/go-logr/logr v1.2.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/gobuffalo/pop/v6 v6.0.8 // indirect
github.com/gofrs/uuid v4.3.0+incompatible // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/glog v1.2.0 // indirect
github.com/golang/mock v1.6.0 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/grpc-ecosystem/grpc-gateway/v2 v2.16.2 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-retryablehttp v0.7.7 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/goveralls v0.0.12 // indirect
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826 // indirect
github.com/openzipkin/zipkin-go v0.4.1 // indirect
github.com/ory/go-acc v0.2.9-0.20230103102148-6b1c9a70dbbe // indirect
github.com/ory/go-convenience v0.1.0 // indirect
github.com/ory/x v0.0.575 // indirect
github.com/pelletier/go-toml/v2 v2.0.9 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/seatgeek/logrus-gelf-formatter v0.0.0-20210414080842-5b05eb8ff761 // indirect
github.com/sirupsen/logrus v1.9.0 // indirect
github.com/spf13/afero v1.9.5 // indirect
github.com/spf13/cast v1.5.1 // indirect
github.com/spf13/cobra v1.7.0 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/spf13/viper v1.16.0 // indirect
github.com/subosito/gotenv v1.4.2 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.42.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.42.0 // indirect
go.opentelemetry.io/contrib/propagators/b3 v1.17.0 // indirect
go.opentelemetry.io/contrib/propagators/jaeger v1.17.0 // indirect
go.opentelemetry.io/contrib/samplers/jaegerremote v0.11.0 // indirect
go.opentelemetry.io/otel v1.16.0 // indirect
go.opentelemetry.io/otel/exporters/jaeger v1.16.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/internal/retry v1.16.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.16.0 // indirect
go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.16.0 // indirect
go.opentelemetry.io/otel/exporters/zipkin v1.16.0 // indirect
go.opentelemetry.io/otel/metric v1.16.0 // indirect
go.opentelemetry.io/otel/sdk v1.16.0 // indirect
go.opentelemetry.io/otel/trace v1.16.0 // indirect
go.opentelemetry.io/proto/otlp v1.0.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.10.0 // indirect
golang.org/x/mod v0.17.0 // indirect
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d // indirect
google.golang.org/genproto v0.0.0-20240227224415-6ceb2ff114de // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240227224415-6ceb2ff114de // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240227224415-6ceb2ff114de // indirect
google.golang.org/grpc v1.63.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)
require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/coocood/freecache v1.2.4
github.com/gabriel-vasile/mimetype v1.4.6 // indirect
github.com/go-ldap/ldap/v3 v3.4.8
github.com/go-playground/locales v0.14.1 // indirect
github.com/go-playground/universal-translator v0.18.1 // indirect
github.com/go-playground/validator/v10 v10.22.1 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 // indirect
github.com/goraz/onion v0.1.3 // indirect
github.com/hashicorp/golang-lru v1.0.2 // indirect
github.com/i-core/rlog v1.0.0
github.com/hashicorp/golang-lru v0.5.4 // indirect
github.com/jtolds/gls v4.20.0+incompatible // indirect
github.com/justinas/nosurf v1.1.1
github.com/kelseyhightower/envconfig v1.4.0
github.com/klauspost/compress v1.17.11 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/klauspost/compress v1.17.2 // indirect
github.com/kr/pretty v0.3.1 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/montanaflynn/stats v0.7.1 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/nats-io/nkeys v0.4.7 // indirect
github.com/nats-io/nuid v1.0.1 // indirect
github.com/ory/fosite v0.47.0
github.com/prometheus/client_golang v1.20.5 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.60.1 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/purnaresa/bulwark v0.0.0-20201001150757-1cec324746b2
github.com/robfig/cron/v3 v3.0.1 // indirect
github.com/rs/zerolog v1.33.0 // indirect
github.com/shiena/ansicolor v0.0.0-20230509054315-a9deabde6e02 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/prometheus/client_golang v1.14.0 // indirect
github.com/prometheus/client_model v0.3.0 // indirect
github.com/prometheus/common v0.41.0 // indirect
github.com/prometheus/procfs v0.9.0 // indirect
github.com/shiena/ansicolor v0.0.0-20200904210342-c7312218db18 // indirect
github.com/smartystreets/assertions v1.2.0 // indirect
github.com/xdg-go/pbkdf2 v1.0.0 // indirect
github.com/xdg-go/scram v1.1.2 // indirect
github.com/xdg-go/stringprep v1.0.4 // indirect
github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect
go.mongodb.org/mongo-driver v1.17.1 // indirect
golang.org/x/crypto v0.28.0 // indirect
golang.org/x/net v0.30.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.26.0 // indirect
golang.org/x/text v0.19.0 // indirect
google.golang.org/appengine v1.6.8 // indirect
google.golang.org/protobuf v1.35.1 // indirect
github.com/stretchr/testify v1.8.1 // indirect
golang.org/x/crypto v0.18.0 // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/sys v0.16.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)

1017
go.sum

File diff suppressed because it is too large Load Diff

View File

@ -1,12 +0,0 @@
Hostname: a3ff4096def1
IP: 127.0.0.1
IP: 172.18.0.16
RemoteAddr: 172.18.0.1:46314
GET / HTTP/1.1
Host: localhost:5000
User-Agent: Wget/1.20.3 (linux-gnu)
Accept: */*
Accept-Encoding: identity
Connection: Keep-Alive
X-Auth-Token: eaaafd18-0fed-4b3a-81b4-663c99ec1cbb

View File

@ -1,41 +0,0 @@
package auth_connectors
import (
"net/http"
"oc-auth/conf"
"cloud.o-forge.io/core/oc-lib/tools"
)
type AuthConnector interface {
Status() tools.State
Login(username string, cookies ...*http.Cookie) (*Token, error)
Logout(token string, cookies ...*http.Cookie) (*Token, error)
Introspect(token string, cookie ...*http.Cookie) (bool, error)
Refresh(token *Token) (*Token, error)
CheckAuthForward(reqToken string, publicKey string, host string, method string, forward string, external bool) bool
}
type Token struct {
Active bool `json:"active"`
AccessToken string `json:"access_token"`
ExpiresIn int64 `json:"expires_in"`
TokenType string `json:"token_type"`
Username string `json:"username,omitempty"`
Password string `json:"password,omitempty"`
}
type Redirect struct {
RedirectTo string `json:"redirect_to"`
}
var a = map[string]AuthConnector{
"hydra": HydraConnector{
Caller: tools.NewHTTPCaller(map[tools.DataType]map[tools.METHOD]string{}),
State: "12345678", ResponseType: "token", Scopes: "openid profile email roles"}, // base url
}
func GetAuthConnector() AuthConnector {
return a[conf.GetConfig().Auth]
}

View File

@ -1,280 +0,0 @@
package auth_connectors
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"oc-auth/conf"
"oc-auth/infrastructure/claims"
"regexp"
"strconv"
"strings"
"time"
oclib "cloud.o-forge.io/core/oc-lib"
"cloud.o-forge.io/core/oc-lib/models/peer"
"cloud.o-forge.io/core/oc-lib/tools"
)
type HydraConnector struct {
State string `json:"state"`
Scopes string `json:"scope"`
ClientID string `json:"client_id"`
ResponseType string `json:"response_type"`
Caller *tools.HTTPCaller
}
func (a HydraConnector) Status() tools.State {
caller := tools.NewHTTPCaller(map[tools.DataType]map[tools.METHOD]string{})
var responseBody map[string]interface{}
host := conf.GetConfig().AuthConnectorHost
port := fmt.Sprintf("%v", conf.GetConfig().AuthConnectorPort)
resp, err := caller.CallGet("http://"+host+":"+port, "/health/ready")
if err != nil {
return tools.DEAD
}
err = json.Unmarshal(resp, &responseBody)
if err != nil || responseBody["status"] != "ok" {
return tools.DEAD
}
return tools.ALIVE
}
// urlFormat formats the URL of the peer with the data type API function
func (a *HydraConnector) urlFormat(url string, replaceWith string) string {
// localhost is replaced by the local peer URL
// because localhost must collide on a web request security protocol
r := regexp.MustCompile("(http://[a-z]+:[0-9]+)/oauth2")
t := r.FindString(url)
if t != "" {
url = strings.Replace(url, t, replaceWith, -1)
}
return url
}
func (a HydraConnector) challenge(username string, url string, challenge string, cookies ...*http.Cookie) (*Redirect, string, []*http.Cookie, error) {
body := map[string]interface{}{
"remember_for": 0,
"remember": true,
}
if challenge != "consent" {
body["subject"] = username
}
s := strings.Split(url, challenge+"_challenge=")
resp, err := a.Caller.CallRaw(http.MethodPut,
a.getPath(true, true), "/auth/requests/"+challenge+"/accept?"+challenge+"_challenge="+s[1],
body, "application/json", true, cookies...) // "remember": true, "subject": username
if err != nil {
return nil, s[1], cookies, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, s[1], cookies, err
}
var token Redirect
err = json.Unmarshal(b, &token)
if err != nil {
return nil, s[1], cookies, err
}
return &token, s[1], cookies, nil
}
func (a HydraConnector) Refresh(token *Token) (*Token, error) {
access := strings.Split(token.AccessToken, ".")
if len(access) > 2 {
token.AccessToken = strings.Join(access[0:2], ".")
}
isValid, err := a.Introspect(token.AccessToken)
if err != nil || !isValid {
return nil, err
}
_, err = a.Logout(token.AccessToken)
if err != nil {
return nil, err
}
return a.Login(token.Username)
}
func (a HydraConnector) tryLog(username string, url string, subpath string, challenge string, cookies ...*http.Cookie) (*Redirect, string, []*http.Cookie, error) {
resp, err := a.Caller.CallRaw(http.MethodGet, url, subpath,
map[string]interface{}{}, "application/json", true, cookies...)
if err != nil || resp.Request.Response == nil || resp.Request.Response.Header["Set-Cookie"] == nil {
return nil, "", cookies, err
}
cc := resp.Request.Response.Header["Set-Cookie"] // retrieve oauth2 csrf token cookie
if len(cc) > 0 {
for _, c := range cc {
first := strings.Split(c, ";")
cookies = append(cookies, &http.Cookie{
Name: strings.Split(first[0], "=")[0],
Value: strings.ReplaceAll(first[0], strings.Split(first[0], "=")[0]+"=", ""),
})
}
}
return a.challenge(username, resp.Request.URL.String(), challenge, cookies...)
}
func (a HydraConnector) getClient() string {
resp, err := a.Caller.CallGet(a.getPath(true, false), "/clients")
if err != nil {
return ""
}
var clients []interface{}
err = json.Unmarshal(resp, &clients)
if err != nil || len(clients) == 0 {
return ""
}
return clients[0].(map[string]interface{})["client_id"].(string)
}
func (a HydraConnector) Login(username string, cookies ...*http.Cookie) (t *Token, err error) {
clientID := a.getClient()
redirect, _, cookies, err := a.tryLog(username, a.getPath(false, true),
"/auth?client_id="+clientID+"&response_type="+strings.ReplaceAll(a.ResponseType, " ", "%20")+"&scope="+strings.ReplaceAll(a.Scopes, " ", "%20")+"&state="+a.State,
"login", cookies...)
if err != nil || redirect == nil {
return nil, err
}
redirect, _, cookies, err = a.tryLog(username, a.urlFormat(redirect.RedirectTo, a.getPath(false, true)), "", "consent", cookies...)
if err != nil || redirect == nil {
return nil, err
}
// problem with consent THERE we need to accept the consent challenge && get the token
_, err = a.Caller.CallRaw(http.MethodGet, a.urlFormat(redirect.RedirectTo, a.getPath(false, true)), "", map[string]interface{}{},
"application/json", true, cookies...)
if err != nil {
s := strings.Split(err.Error(), "\"")
if len(s) > 1 && strings.Contains(s[1], "access_token") {
err = nil
} else {
return nil, err
}
}
token := &Token{
Username: username,
}
urls := url.Values{}
urls.Add("client_id", clientID)
urls.Add("client_secret", conf.GetConfig().ClientSecret)
urls.Add("grant_type", "client_credentials")
resp, err := a.Caller.CallForm(http.MethodPost, a.getPath(false, true), "/token", urls,
"application/x-www-form-urlencoded", true, cookies...)
var m map[string]interface{}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
err = json.Unmarshal(b, &token)
if err != nil {
return nil, err
}
json.Unmarshal(b, &m)
pp := oclib.Search(nil, strconv.Itoa(peer.SELF.EnumIndex()), oclib.LibDataEnum(oclib.PEER))
if len(pp.Data) == 0 || pp.Code >= 300 || pp.Err != "" {
return nil, errors.New("peer not found")
}
now := time.Now().UTC()
now = now.Add(time.Duration(token.ExpiresIn) * time.Second)
unix := now.Unix()
c := claims.GetClaims().AddClaimsToToken(username, pp.Data[0].(*peer.Peer).Url)
c.Session.AccessToken["exp"] = unix
b, _ = json.Marshal(c)
token.AccessToken = strings.ReplaceAll(token.AccessToken, "ory_at_", "") + "." + base64.StdEncoding.EncodeToString(b)
token.Active = true
return token, nil
}
func (a HydraConnector) Logout(token string, cookies ...*http.Cookie) (*Token, error) {
access := strings.Split(token, ".")
if len(access) > 2 {
token = strings.Join(access[0:2], ".")
}
p := a.getPath(false, true) + "/revoke"
urls := url.Values{}
urls.Add("token", token)
urls.Add("client_id", a.getClient())
urls.Add("client_secret", conf.GetConfig().ClientSecret)
_, err := a.Caller.CallForm(http.MethodPost, p, "", urls, "application/x-www-form-urlencoded", true)
if err != nil {
return nil, err
}
return &Token{
AccessToken: token,
Active: false,
}, nil
}
func (a HydraConnector) Introspect(token string, cookie ...*http.Cookie) (bool, error) {
// check validity of the token by calling introspect endpoint
// if token is not active, we need to re-authenticate by sending the user to the login page
access := strings.Split(token, ".")
if len(access) > 2 {
token = strings.Join(access[0:2], ".")
}
urls := url.Values{}
urls.Add("token", token)
resp, err := a.Caller.CallForm(http.MethodPost, a.getPath(true, true), "/introspect", urls,
"application/x-www-form-urlencoded", true, cookie...)
if err != nil || resp.StatusCode >= 300 {
return false, err
}
defer resp.Body.Close()
b, err := io.ReadAll(resp.Body)
if err != nil {
return false, err
}
var introspect Token
err = json.Unmarshal(b, &introspect)
if err != nil {
return false, err
}
introspect.AccessToken = token
return introspect.Active, nil
}
func (a HydraConnector) getPath(isAdmin bool, isOauth bool) string {
host := conf.GetConfig().AuthConnectorHost
port := fmt.Sprintf("%v", conf.GetConfig().AuthConnectorPort)
if isAdmin {
port = fmt.Sprintf("%v", conf.GetConfig().AuthConnectorAdminPort) + "/admin"
}
oauth := ""
if isOauth {
oauth = "/oauth2"
}
return "http://" + host + ":" + port + oauth
}
func (a HydraConnector) CheckAuthForward(reqToken string, publicKey string, host string, method string, forward string, external bool) bool {
if forward == "" || method == "" {
return false
}
var c claims.Claims
token := strings.Split(reqToken, ".")
if len(token) > 2 {
bytes, err := base64.StdEncoding.DecodeString(token[2])
if err != nil {
return false
}
err = json.Unmarshal(bytes, &c)
if err != nil {
return false
}
}
// ask keto for permission is in claims
ok, err := claims.GetClaims().DecodeClaimsInToken(host, method, forward, c, publicKey, external)
if err != nil {
fmt.Println("Failed to decode claims", err)
}
return ok
}

View File

@ -1,385 +0,0 @@
package auth_connectors
import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net"
"oc-auth/conf"
"strings"
"sync"
"time"
"github.com/coocood/freecache"
"github.com/go-ldap/ldap/v3"
"github.com/i-core/rlog"
"go.uber.org/zap"
)
var (
// errInvalidCredentials is an error that happens when a user's password is invalid.
errInvalidCredentials = fmt.Errorf("invalid credentials")
// errConnectionTimeout is an error that happens when no one LDAP endpoint responds.
errConnectionTimeout = fmt.Errorf("connection timeout")
// errMissedUsername is an error that happens
errMissedUsername = errors.New("username is missed")
// errUnknownUsername is an error that happens
errUnknownUsername = errors.New("unknown username")
)
type conn interface {
Bind(bindDN, password string) error
SearchUser(user string, attrs ...string) ([]map[string]interface{}, error)
SearchUserRoles(user string, attrs ...string) ([]map[string]interface{}, error)
Close() error
}
type connector interface {
Connect(ctx context.Context, addr string) (conn, error)
}
// Config is a LDAP configuration.
type Config struct {
Endpoints []string `envconfig:"endpoints" required:"true" desc:"a LDAP's server URLs as \"<address>:<port>\""`
BindDN string `envconfig:"binddn" desc:"a LDAP bind DN"`
BindPass string `envconfig:"bindpw" json:"-" desc:"a LDAP bind password"`
BaseDN string `envconfig:"basedn" required:"true" desc:"a LDAP base DN for searching users"`
AttrClaims map[string]string `envconfig:"attr_claims" default:"name:name,sn:family_name,givenName:given_name,mail:email" desc:"a mapping of LDAP attributes to OpenID connect claims"`
RoleBaseDN string `envconfig:"role_basedn" required:"true" desc:"a LDAP base DN for searching roles"`
RoleAttr string `envconfig:"role_attr" default:"description" desc:"a LDAP group's attribute that contains a role's name"`
RoleClaim string `envconfig:"role_claim" default:"https://github.com/i-core/werther/claims/roles" desc:"a name of an OpenID Connect claim that contains user roles"`
CacheSize int `envconfig:"cache_size" default:"512" desc:"a user info cache's size in KiB"`
CacheTTL time.Duration `envconfig:"cache_ttl" default:"30m" desc:"a user info cache TTL"`
IsTLS bool `envconfig:"is_tls" default:"false" desc:"should LDAP connection be established via TLS"`
FlatRoleClaims bool `envconfig:"flat_role_claims" desc:"add roles claim as single list"`
}
// New creates a new LDAP client.
func New() *Client {
cnf := Config{
Endpoints: strings.Split(conf.GetConfig().LDAPEndpoints, ","),
BindDN: conf.GetConfig().LDAPBindDN,
BindPass: conf.GetConfig().LDAPBindPW,
BaseDN: conf.GetConfig().LDAPBaseDN,
RoleBaseDN: conf.GetConfig().LDAPRoleBaseDN,
}
return &Client{
Config: cnf,
connector: &ldapConnector{BaseDN: cnf.BaseDN, RoleBaseDN: cnf.RoleBaseDN, IsTLS: cnf.IsTLS},
cache: freecache.NewCache(cnf.CacheSize * 1024),
}
}
type Client struct {
Config
connector connector
cache *freecache.Cache
}
func (cli *Client) Authenticate(ctx context.Context, username, password string) (bool, error) {
if username == "" || password == "" {
return false, nil
}
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(ctx)
cn, ok := <-cli.connect(ctx)
cancel()
if !ok {
return false, errConnectionTimeout
}
defer cn.Close()
// Find a user DN by his or her username.
details, err := cli.findBasicUserDetails(cn, username, []string{"dn"})
if err != nil {
return false, err
}
if details == nil {
return false, nil
}
if err := cn.Bind(details["dn"].(string), password); err != nil {
if err == errInvalidCredentials {
return false, nil
}
return false, err
}
// Clear the claims' cache because of possible re-authentication. We don't want stale claims after re-login.
if ok := cli.cache.Del([]byte(username)); ok {
log := rlog.FromContext(ctx)
log.Debug("Cleared user's OIDC claims in the cache")
}
return true, nil
}
// Claim is the FindOIDCClaims result struct
type LDAPClaim struct {
Code string // the root claim name
Name string // the claim name
Value interface{} // the value
}
// FindOIDCClaims finds all OIDC claims for a user.
func (cli *Client) FindOIDCClaims(ctx context.Context, username string) ([]LDAPClaim, error) {
if username == "" {
return nil, errMissedUsername
}
log := rlog.FromContext(ctx).Sugar()
// Retrieving from LDAP is slow. So, we try to get claims for the given username from the cache.
switch cdata, err := cli.cache.Get([]byte(username)); err {
case nil:
var claims []LDAPClaim
if err = json.Unmarshal(cdata, &claims); err != nil {
log.Info("Failed to unmarshal user's OIDC claims", zap.Error(err), "data", cdata)
return nil, err
}
log.Debugw("Retrieved user's OIDC claims from the cache", "claims", claims)
return claims, nil
case freecache.ErrNotFound:
log.Debug("User's OIDC claims is not found in the cache")
default:
log.Infow("Failed to retrieve user's OIDC claims from the cache", zap.Error(err))
}
// Try to make multiple TCP connections to the LDAP server for getting claims.
// Accept the first one, and cancel others.
var cancel context.CancelFunc
ctx, cancel = context.WithCancel(ctx)
cn, ok := <-cli.connect(ctx)
cancel()
if !ok {
return nil, errConnectionTimeout
}
defer cn.Close()
// We need to find LDAP attribute's names for all required claims.
attrs := []string{"dn"}
for k := range cli.AttrClaims {
attrs = append(attrs, k)
}
// Find the attributes in the LDAP server.
details, err := cli.findBasicUserDetails(cn, username, attrs)
if err != nil {
return nil, err
}
if details == nil {
return nil, errUnknownUsername
}
log.Infow("Retrieved user's info from LDAP", "details", details)
// Transform the retrieved attributes to corresponding claims.
claims := make([]LDAPClaim, 0, len(details))
for attr, v := range details {
if claim, ok := cli.AttrClaims[attr]; ok {
claims = append(claims, LDAPClaim{claim, claim, v})
}
}
// User's roles is stored in LDAP as groups. We find all groups in a role's DN
// that include the user as a member.
entries, err := cn.SearchUserRoles(fmt.Sprintf("%s", details["dn"]), "dn", cli.RoleAttr)
if err != nil {
return nil, err
}
roles := make(map[string]interface{})
for _, entry := range entries {
roleDN, ok := entry["dn"].(string)
if !ok || roleDN == "" {
log.Infow("No required LDAP attribute for a role", "ldapAttribute", "dn", "entry", entry)
continue
}
if entry[cli.RoleAttr] == nil {
log.Infow("No required LDAP attribute for a role", "ldapAttribute", cli.RoleAttr, "roleDN", roleDN)
continue
}
// Ensure that a role's DN is inside of the role's base DN.
// It's sufficient to compare the DN's suffix with the base DN.
n, k := len(roleDN), len(cli.RoleBaseDN)
if n < k || !strings.EqualFold(roleDN[n-k:], cli.RoleBaseDN) {
panic("You should never see that")
}
// The DN without the role's base DN must contain a CN and OU
// where the CN is for uniqueness only, and the OU is an application id.
path := strings.Split(roleDN[:n-k-1], ",")
if len(path) != 2 {
log.Infow("A role's DN without the role's base DN must contain two nodes only",
"roleBaseDN", cli.RoleBaseDN, "roleDN", roleDN)
continue
}
appID := path[1][len("OU="):]
var appRoles []interface{}
if v := roles[appID]; v != nil {
appRoles = v.([]interface{})
}
appRoles = append(appRoles, entry[cli.RoleAttr])
roles[appID] = appRoles
}
claims = append(claims, LDAPClaim{cli.RoleClaim, cli.RoleClaim, roles})
if cli.FlatRoleClaims {
for appID, appRoles := range roles {
claims = append(claims, LDAPClaim{cli.RoleClaim, cli.RoleClaim + "/" + appID, appRoles})
}
}
// Save the claims in the cache for future queries.
cdata, err := json.Marshal(claims)
if err != nil {
log.Infow("Failed to marshal user's OIDC claims for caching", zap.Error(err), "claims", claims)
}
if err = cli.cache.Set([]byte(username), cdata, int(cli.CacheTTL.Seconds())); err != nil {
log.Infow("Failed to store user's OIDC claims into the cache", zap.Error(err), "claims", claims)
}
return claims, nil
}
func (cli *Client) connect(ctx context.Context) <-chan conn {
var (
wg sync.WaitGroup
ch = make(chan conn)
)
wg.Add(len(cli.Endpoints))
for _, addr := range cli.Endpoints {
go func(addr string) {
defer wg.Done()
cn, err := cli.connector.Connect(ctx, addr)
if err != nil {
fmt.Println("Failed to create a LDAP connection", "address", addr)
return
}
select {
case <-ctx.Done():
cn.Close()
fmt.Println("a LDAP connection is cancelled", "address", addr)
return
case ch <- cn:
}
}(addr)
}
go func() {
wg.Wait()
close(ch)
}()
return ch
}
// findBasicUserDetails finds user's LDAP attributes that were specified. It returns nil if no such user.
func (cli *Client) findBasicUserDetails(cn conn, username string, attrs []string) (map[string]interface{}, error) {
if cli.BindDN != "" {
// We need to login to a LDAP server with a service account for retrieving user data.
if err := cn.Bind(cli.BindDN, cli.BindPass); err != nil {
return nil, errors.New(err.Error() + " : failed to login to a LDAP woth a service account")
}
}
entries, err := cn.SearchUser(username, attrs...)
if err != nil {
return nil, err
}
if len(entries) != 1 {
// We didn't find the user.
return nil, nil
}
var (
entry = entries[0]
details = make(map[string]interface{})
)
for _, attr := range attrs {
if v, ok := entry[attr]; ok {
details[attr] = v
}
}
return details, nil
}
type ldapConnector struct {
BaseDN string
RoleBaseDN string
IsTLS bool
}
func (c *ldapConnector) Connect(ctx context.Context, addr string) (conn, error) {
d := net.Dialer{Timeout: ldap.DefaultTimeout}
tcpcn, err := d.DialContext(ctx, "tcp", addr)
if err != nil {
return nil, err
}
if c.IsTLS {
tlscn, err := tls.DialWithDialer(&d, "tcp", addr, nil)
if err != nil {
return nil, err
}
tcpcn = tlscn
}
ldapcn := ldap.NewConn(tcpcn, c.IsTLS)
ldapcn.Start()
return &ldapConn{Conn: ldapcn, BaseDN: c.BaseDN, RoleBaseDN: c.RoleBaseDN}, nil
}
type ldapConn struct {
*ldap.Conn
BaseDN string
RoleBaseDN string
}
func (c *ldapConn) Bind(bindDN, password string) error {
err := c.Conn.Bind(bindDN, password)
if ldapErr, ok := err.(*ldap.Error); ok && ldapErr.ResultCode == ldap.LDAPResultInvalidCredentials {
return errInvalidCredentials
}
return err
}
func (c *ldapConn) SearchUser(user string, attrs ...string) ([]map[string]interface{}, error) {
query := fmt.Sprintf(
"(&(|(objectClass=organizationalPerson)(objectClass=inetOrgPerson))"+
"(|(uid=%[1]s)(mail=%[1]s)(userPrincipalName=%[1]s)(sAMAccountName=%[1]s)))", user)
return c.searchEntries(c.BaseDN, query, attrs)
}
func (c *ldapConn) SearchUserRoles(user string, attrs ...string) ([]map[string]interface{}, error) {
query := fmt.Sprintf("(|"+
"(&(|(objectClass=group)(objectClass=groupOfNames))(member=%[1]s))"+
"(&(objectClass=groupOfUniqueNames)(uniqueMember=%[1]s))"+
")", user)
return c.searchEntries(c.RoleBaseDN, query, attrs)
}
// searchEntries executes a LDAP query, and returns a result as entries where each entry is mapping of LDAP attributes.
func (c *ldapConn) searchEntries(baseDN, query string, attrs []string) ([]map[string]interface{}, error) {
req := ldap.NewSearchRequest(baseDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, query, attrs, nil)
res, err := c.Search(req)
if err != nil {
return nil, err
}
var entries []map[string]interface{}
for _, v := range res.Entries {
entry := map[string]interface{}{"dn": v.DN}
for _, attr := range v.Attributes {
// We need the first value only for the named attribute.
entry[attr.Name] = attr.Values[0]
}
entries = append(entries, entry)
}
return entries, nil
}

View File

@ -1,28 +0,0 @@
package claims
import "oc-auth/conf"
// Tokenizer interface
type ClaimService interface {
AddClaimsToToken(userId string, host string) Claims
DecodeClaimsInToken(host string, method string, forward string, sessionClaims Claims, publicKey string, external bool) (bool, error)
}
// SessionClaims struct
type SessionClaims struct {
AccessToken map[string]interface{} `json:"access_token"`
IDToken map[string]interface{} `json:"id_token"`
}
// Claims struct
type Claims struct {
Session SessionClaims `json:"session"`
}
var t = map[string]ClaimService{
"hydra": HydraClaims{},
}
func GetClaims() ClaimService {
return t[conf.GetConfig().Auth]
}

View File

@ -1,129 +0,0 @@
package claims
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"errors"
"log"
)
func SignDefault(plaintext, privateKey []byte) (signature string, err error) {
client, err := New(privateKey, nil)
if err != nil {
log.Println(err)
return
}
signatureByte, err := client.Sign(plaintext)
if err != nil {
log.Println(err)
return
}
signature = base64.StdEncoding.EncodeToString(signatureByte)
return
}
func VerifyDefault(plaintext, publicKey []byte, signature string) (err error) {
publicKeys := make(map[string][]byte)
publicKeys["default"] = publicKey
client, err := New(nil, publicKeys)
if err != nil {
log.Println(err)
return
}
signatureByte, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
log.Println(err)
return
}
err = client.Verify(plaintext, signatureByte, "default")
if err != nil {
log.Println(err)
return
}
return
}
func (c *Client) Sign(plaintext []byte) (signature []byte, err error) {
var opts rsa.PSSOptions
opts.SaltLength = rsa.PSSSaltLengthAuto
newhash := crypto.SHA256
pssh := newhash.New()
pssh.Write(plaintext)
hashed := pssh.Sum(nil)
signature, err = rsa.SignPSS(
rand.Reader,
c.PrivateKey,
newhash,
hashed,
&opts,
)
return
}
func (c *Client) Verify(plaintext, signature []byte, target string) (err error) {
var opts rsa.PSSOptions
opts.SaltLength = rsa.PSSSaltLengthAuto
newhash := crypto.SHA256
pssh := newhash.New()
pssh.Write(plaintext)
hashed := pssh.Sum(nil)
err = rsa.VerifyPSS(
c.PublicKeys[target],
newhash,
hashed,
signature,
&opts,
)
return
}
func init() {
log.SetFlags(log.LstdFlags | log.Lshortfile)
}
type Client struct {
PrivateKey *rsa.PrivateKey
PublicKeys map[string]*rsa.PublicKey
}
func New(privateKey []byte, publicKeys map[string][]byte) (client *Client, err error) {
client = &Client{}
if privateKey != nil {
validPrivateKey, errPrivate := x509.ParsePKCS1PrivateKey(privateKey)
if errPrivate != nil {
err = errPrivate
log.Println(err)
return
}
client.PrivateKey = validPrivateKey
}
if publicKeys != nil {
validPublicKeysMap := make(map[string]*rsa.PublicKey)
for k, v := range publicKeys {
validPublicKey, errPublic := x509.ParsePKCS1PublicKey(v)
if errPublic != nil {
err = errPublic
log.Println(err)
return
}
if validPublicKey == nil {
err = errors.New("Invalid Public Key Type")
log.Println(err)
return
}
validPublicKeysMap[k] = validPublicKey
}
client.PublicKeys = validPublicKeysMap
}
return
}

View File

@ -1,151 +0,0 @@
package claims
import (
"crypto/sha256"
"encoding/pem"
"errors"
"oc-auth/conf"
"oc-auth/infrastructure/perms_connectors"
"oc-auth/infrastructure/utils"
"os"
"strings"
"time"
"cloud.o-forge.io/core/oc-lib/tools"
)
type HydraClaims struct{}
func (h HydraClaims) generateKey(relation string, path string) (string, error) {
method, err := utils.ExtractMethod(relation, true)
if err != nil {
return "", err
}
p := strings.ReplaceAll(strings.ToUpper(path), "/", "_")
return strings.ToLower(method.String()) + "_" + strings.ReplaceAll(p, ":", ""), nil
}
// decode key expect to extract method and path from key
func (h HydraClaims) decodeKey(key string, external bool) (tools.METHOD, string, error) {
s := strings.Split(key, "_")
if len(s) < 2 {
return tools.GET, "", errors.New("invalid key")
}
if strings.Contains(strings.ToUpper(s[0]), "INTERNAL") && external {
return tools.GET, "", errors.New("external ask for internal key")
}
meth, err := utils.ExtractMethod(s[0], false)
if err != nil {
return meth, "", err
}
p := strings.ReplaceAll(strings.ToLower(s[1]), "_", "/")
return meth, p, nil
}
func (h HydraClaims) DecodeSignature(host string, signature string, publicKey string) (bool, error) {
hashed := sha256.Sum256([]byte(host))
spkiBlock, _ := pem.Decode([]byte(publicKey)) // get public key into a variable
err := VerifyDefault(hashed[:], spkiBlock.Bytes, signature)
if err != nil {
return false, err
}
return true, nil
}
func (h HydraClaims) encodeSignature(host string) (string, error) {
hashed := sha256.Sum256([]byte(host))
// READ FILE TO GET PRIVATE KEY FROM PVK PEM PATH
content, err := os.ReadFile(conf.GetConfig().PrivateKeyPath)
if err != nil {
return "", err
}
privateKey := string(content)
spkiBlock, _ := pem.Decode([]byte(privateKey))
return SignDefault(hashed[:], spkiBlock.Bytes)
}
func (h HydraClaims) clearBlank(path []string) []string {
// clear blank
newPath := []string{}
for _, p := range path {
if p != "" {
newPath = append(newPath, p)
}
}
return newPath
}
func (a HydraClaims) CheckExpiry(exp int64) bool {
now := time.Now().UTC().Unix()
return now <= exp
}
func (h HydraClaims) DecodeClaimsInToken(host string, method string, forward string, sessionClaims Claims, publicKey string, external bool) (bool, error) {
idTokenClaims := sessionClaims.Session.IDToken
if idTokenClaims["signature"] == nil {
return false, errors.New("no signature found")
}
signature := idTokenClaims["signature"].(string)
if ok, err := h.DecodeSignature(host, signature, publicKey); !ok {
return false, err
}
claims := sessionClaims.Session.AccessToken
path := strings.ReplaceAll(forward, "http://"+host, "")
splittedPath := h.clearBlank(strings.Split(path, "/"))
if _, ok := claims["exp"].(float64); !ok || !h.CheckExpiry(int64(claims["exp"].(float64))) {
return false, errors.New("token is expired")
}
for m, p := range claims {
match := true
splittedP := h.clearBlank(strings.Split(p.(string), "/"))
if len(splittedP) != len(splittedPath) {
continue
}
for i, v := range splittedP {
if strings.Contains(v, ":") { // is a param
continue
} else if v != splittedPath[i] {
match = false
break
}
}
if match {
meth, _, err := h.decodeKey(m, external)
if err != nil {
continue
}
perm := perms_connectors.Permission{
Relation: "permits" + strings.ToUpper(meth.String()),
Object: p.(string),
}
return perms_connectors.GetPermissionConnector().CheckPermission(perm, nil, true), nil
}
}
return false, errors.New("no permission found")
}
// add claims to token method of HydraTokenizer
func (h HydraClaims) AddClaimsToToken(userId string, host string) Claims {
claims := Claims{}
perms, err := perms_connectors.KetoConnector{}.GetPermissionByUser(userId, true)
if err != nil {
return claims
}
claims.Session.AccessToken = make(map[string]interface{})
claims.Session.IDToken = make(map[string]interface{})
for _, perm := range perms {
key, err := h.generateKey(strings.ReplaceAll(perm.Relation, "permits", ""), perm.Subject)
if err != nil {
continue
}
claims.Session.AccessToken[key] = perm.Subject
}
sign, err := h.encodeSignature(host)
if err != nil {
return claims
}
claims.Session.IDToken["signature"] = sign
return claims
}
// add signature in the token MISSING

View File

@ -1,19 +0,0 @@
package infrastructure
import (
auth_connectors "oc-auth/infrastructure/auth_connector"
"oc-auth/infrastructure/claims"
"oc-auth/infrastructure/perms_connectors"
)
func GetAuthConnector() auth_connectors.AuthConnector {
return auth_connectors.GetAuthConnector()
}
func GetPermissionConnector() perms_connectors.PermConnector {
return perms_connectors.GetPermissionConnector()
}
func GetClaims() claims.ClaimService {
return claims.GetClaims()
}

View File

@ -1,358 +0,0 @@
package perms_connectors
import (
"encoding/json"
"errors"
"fmt"
"oc-auth/conf"
"oc-auth/infrastructure/utils"
oclib "cloud.o-forge.io/core/oc-lib"
"cloud.o-forge.io/core/oc-lib/tools"
)
type KetoConnector struct{}
func (k KetoConnector) namespace() string {
return "open-cloud"
}
func (k KetoConnector) scope() string {
return "oc-auth"
}
func (f KetoConnector) permToQuery(perm Permission, permDependancies *Permission) string {
n := "?namespace=" + perm.Namespace()
if perm.Object != "" {
n += "&object=" + perm.Object
}
if perm.Subject != "" {
n += "&subject_id=" + perm.Subject
}
if perm.Relation != "" {
n += "&relation=" + perm.Relation
}
if permDependancies != nil {
n += "&subject_set.namespace=" + perm.Namespace()
if permDependancies.Object != "" {
n += "&subject_set.object=" + permDependancies.Object
}
if permDependancies.Subject != "" {
n += "&subject_set.subject_id=" + permDependancies.Subject
}
if permDependancies.Relation != "" {
n += "&subject_set.relation=" + permDependancies.Relation
}
}
return n
}
func (k KetoConnector) Status() tools.State {
caller := tools.NewHTTPCaller(map[tools.DataType]map[tools.METHOD]string{})
var responseBody map[string]interface{}
host := conf.GetConfig().PermissionConnectorHost
port := fmt.Sprintf("%v", conf.GetConfig().PermissionConnectorPort)
resp, err := caller.CallGet("http://"+host+":"+port, "/health/ready")
if err != nil {
return tools.DEAD
}
err = json.Unmarshal(resp, &responseBody)
if err != nil || responseBody["status"] != "ok" {
return tools.DEAD
}
return tools.ALIVE
}
func (k KetoConnector) CheckPermission(perm Permission, permDependancies *Permission, internal bool) bool {
if (perm.Object == k.scope() || perm.Subject == k.scope()) && !internal {
log := oclib.GetLogger()
log.Error().Msg("Permission denied : Ask illegal permission")
return false
}
perms, err := k.GetPermission(perm.Object, perm.Relation)
if err != nil {
log := oclib.GetLogger()
log.Error().Msg(err.Error())
return false
}
return len(perms) > 0
}
func (k KetoConnector) DeleteRole(roleID string) (string, int, error) {
k.deleteRelationShip("", "", roleID, nil)
_, code, err := k.deleteRelationShip(roleID, "", k.scope(), nil)
if err != nil {
return "", code, err
}
return roleID, 200, nil
}
func (k KetoConnector) DeletePermission(permID string, relation string, internal bool) (string, int, error) {
meth, err := utils.ExtractMethod(relation, internal)
if err != nil {
for _, method := range []tools.METHOD{tools.GET, tools.PUT, tools.POST, tools.DELETE} {
k.DeletePermission("", method.String(), internal)
}
return "", 200, err
}
k.deleteRelationShip("", "", permID, nil)
_, code, err := k.deleteRelationShip(permID, "permits"+meth.String(), k.scope(), nil)
if err != nil {
return "", code, err
}
return permID, 200, nil
}
func (k KetoConnector) CreateRole(roleID string) (string, int, error) {
p, code, err := k.createRelationShip(roleID, "is", k.scope(), nil)
if err != nil {
return "", code, err
}
return p.Object, 200, nil
}
func (k KetoConnector) CreatePermission(permID string, relation string, internal bool) (string, int, error) {
meth, err := utils.ExtractMethod(relation, internal)
if err != nil {
return "", 422, err
}
k.BindPermission("admin", permID, "permits"+meth.String())
p, code, err := k.createRelationShip(permID, "permits"+meth.String(), k.scope(), nil)
if err != nil {
return "", code, err
}
return p.Object, 200, nil
}
func (k KetoConnector) GetRole(roleID string) ([]string, error) {
arr := []string{}
roles, err := k.get(roleID, "is", k.scope())
if err != nil {
return arr, err
}
for _, role := range roles {
arr = append(arr, role.Object)
}
return arr, nil
}
func (k KetoConnector) GetRoleByUser(userID string) ([]string, error) {
arr := []string{}
roles, err := k.get("", "member", userID)
if err != nil {
return arr, err
}
for _, role := range roles {
arr = append(arr, role.Object)
}
return arr, nil
}
func (k KetoConnector) GetPermission(permID string, relation string) ([]Permission, error) {
meth, err := utils.ExtractMethod(relation, true)
if err != nil {
p := []Permission{}
for _, method := range []tools.METHOD{tools.GET, tools.PUT, tools.POST, tools.DELETE,
tools.STRICT_INTERNAL_DELETE, tools.STRICT_INTERNAL_GET, tools.STRICT_INTERNAL_POST, tools.STRICT_INTERNAL_PUT} {
perms, err := k.get(permID, "permits"+method.String(), k.scope())
if err == nil && len(perms) > 0 {
p = append(p, perms...)
}
}
return p, nil
}
return k.get(permID, "permits"+meth.String(), k.scope())
}
func (k KetoConnector) GetPermissionByRole(roleID string) ([]Permission, error) {
p := []Permission{}
for _, method := range []tools.METHOD{tools.GET, tools.PUT, tools.POST, tools.DELETE,
tools.STRICT_INTERNAL_DELETE, tools.STRICT_INTERNAL_GET, tools.STRICT_INTERNAL_POST, tools.STRICT_INTERNAL_PUT} {
perms, err := k.get(roleID, "permits"+method.String(), "")
if err == nil && len(perms) > 0 {
p = append(p, perms...)
}
}
return p, nil
}
func (k KetoConnector) GetPermissionByUser(userID string, internal bool) ([]Permission, error) {
roles, err := k.get("", "member", userID)
if err != nil {
return nil, err
}
p := []Permission{}
meths := []tools.METHOD{tools.GET, tools.PUT, tools.POST, tools.DELETE}
if internal {
meths = append(meths, []tools.METHOD{tools.STRICT_INTERNAL_DELETE, tools.STRICT_INTERNAL_GET, tools.STRICT_INTERNAL_POST, tools.STRICT_INTERNAL_PUT}...)
}
for _, role := range roles {
for _, method := range meths {
perms, err := k.get(role.Object, "permits"+method.String(), "")
if err == nil && len(perms) > 0 {
p = append(p, perms...)
}
}
}
return p, nil
}
func (k KetoConnector) get(object string, relation string, subject string) ([]Permission, error) {
t := []Permission{}
caller := tools.NewHTTPCaller(map[tools.DataType]map[tools.METHOD]string{})
host := conf.GetConfig().PermissionConnectorHost
port := fmt.Sprintf("%v", conf.GetConfig().PermissionConnectorPort)
resp, err := caller.CallGet("http://"+host+":"+port, "/relation-tuples"+k.permToQuery(
Permission{Object: object, Relation: relation, Subject: subject}, nil))
if err != nil {
return t, err
}
var data map[string]interface{}
err = json.Unmarshal(resp, &data)
if err != nil {
return t, err
}
if data["relation_tuples"] != nil {
for _, v := range data["relation_tuples"].([]interface{}) {
t = append(t, Permission{
Relation: v.(map[string]interface{})["relation"].(string),
Subject: v.(map[string]interface{})["subject_id"].(string),
Object: v.(map[string]interface{})["object"].(string),
})
}
}
return t, nil
}
func (k KetoConnector) BindRole(userID string, roleID string) (string, int, error) {
_, code, err := k.createRelationShip(roleID, "member", userID, nil)
if err != nil {
return roleID, code, err
}
return roleID, 200, nil
}
func (k KetoConnector) BindPermission(roleID string, permID string, relation string) (*Permission, int, error) {
perms, err := k.GetPermission(permID, relation)
if err != nil || len(perms) != 1 {
if len(perms) == 0 {
return nil, 404, errors.New("Permission not found")
} else if len(perms) > 1 {
return nil, 409, errors.New("Multiple permission found")
}
}
_, code, err := k.createRelationShip(roleID, perms[0].Relation, permID, nil)
if err != nil {
return nil, code, err
}
return &Permission{
Object: roleID,
Relation: perms[0].Relation,
Subject: permID,
}, 200, nil
}
func (k KetoConnector) UnBindRole(userID string, roleID string) (string, int, error) {
_, code, err := k.deleteRelationShip(roleID, "member", userID, nil)
if err != nil {
return roleID, code, err
}
return roleID, 200, nil
}
func (k KetoConnector) UnBindPermission(roleID string, permID string, relation string) (*Permission, int, error) {
meth, err := utils.ExtractMethod(relation, false)
if err != nil {
return nil, 422, err
}
perms, err := k.GetPermission(permID, meth.String())
if err != nil || len(perms) != 1 {
if len(perms) == 0 {
return nil, 404, errors.New("Permission not found")
} else if len(perms) > 1 {
return nil, 409, errors.New("Multiple permission found")
}
}
_, code, err := k.deleteRelationShip(roleID, perms[0].Relation, permID, nil)
if err != nil {
return nil, code, err
}
return &Permission{
Object: roleID,
Relation: perms[0].Relation,
Subject: permID,
}, 200, nil
}
func (k KetoConnector) createRelationShip(object string, relation string, subject string, subPerm *Permission) (*Permission, int, error) {
exist, err := k.get(object, relation, subject)
if err == nil && len(exist) > 0 {
return nil, 409, errors.New("Relation already exist")
}
caller := tools.NewHTTPCaller(map[tools.DataType]map[tools.METHOD]string{})
body := map[string]interface{}{"namespace": k.namespace(), "object": object, "relation": relation, "subject_id": subject}
if subPerm != nil {
s, code, err := k.createRelationShip(subPerm.Object, subPerm.Relation, subPerm.Subject, nil)
if err != nil {
return nil, code, err
}
body["subject_set"] = map[string]interface{}{"namespace": s.Namespace(), "object": s.Object, "relation": s.Relation, "subject_id": s.Subject}
}
host := conf.GetConfig().PermissionConnectorHost
port := fmt.Sprintf("%v", conf.GetConfig().PermissionConnectorAdminPort)
b, err := caller.CallPut("http://"+host+":"+port, "/relation-tuples", body)
if err != nil {
log := oclib.GetLogger()
log.Error().Msg(err.Error())
return nil, 500, err
}
var data map[string]interface{}
err = json.Unmarshal(b, &data)
if err != nil {
log := oclib.GetLogger()
log.Error().Msg(err.Error())
return nil, 500, err
}
perm := &Permission{
Object: data["object"].(string),
Relation: data["relation"].(string),
Subject: data["subject_id"].(string),
}
if data["subject_set"] != nil {
sub := data["subject_set"].(map[string]interface{})
perm.SubPermission = &Permission{
Object: sub["object"].(string),
Relation: sub["relation"].(string),
Subject: sub["subject_id"].(string),
}
}
return perm, 200, nil
}
func (k KetoConnector) deleteRelationShip(object string, relation string, subject string, subPerm *Permission) (*Permission, int, error) {
exist, err := k.get(object, relation, subject)
if err == nil && len(exist) == 0 {
return nil, 409, errors.New("Relation does not exist")
}
caller := tools.NewHTTPCaller(map[tools.DataType]map[tools.METHOD]string{})
n := k.permToQuery(Permission{Object: object, Relation: relation, Subject: subject}, subPerm)
host := conf.GetConfig().PermissionConnectorHost
port := fmt.Sprintf("%v", conf.GetConfig().PermissionConnectorAdminPort)
b, err := caller.CallDelete("http://"+host+":"+port, "/relation-tuples"+n)
if err != nil {
log := oclib.GetLogger()
log.Error().Msg(err.Error())
return nil, 500, err
}
var data map[string]interface{}
err = json.Unmarshal(b, &data)
if err == nil && data["code"].(int) > 300 {
return nil, data["code"].(int), errors.New("Error while deleting relation")
}
return &Permission{
Object: object,
Relation: relation,
Subject: subject,
SubPermission: subPerm,
}, 200, nil
}

View File

@ -1,52 +0,0 @@
package perms_connectors
import (
"oc-auth/conf"
"cloud.o-forge.io/core/oc-lib/tools"
)
type Permission struct {
Object string `json:"object,omitempty"`
Relation string `json:"relation,omitempty"`
Subject string `json:"subject,omitempty"`
SubPermission *Permission `json:"sub_perm,omitempty"`
}
func (p Permission) Namespace() string {
return "open-cloud"
}
func (k Permission) Scope() string {
return "oc-auth"
}
type PermConnector interface {
Status() tools.State
CheckPermission(perm Permission, permDependancies *Permission, internal bool) bool
BindRole(userID string, roleID string) (string, int, error)
BindPermission(roleID string, permID string, relation string) (*Permission, int, error)
UnBindRole(userID string, roleID string) (string, int, error)
UnBindPermission(roleID string, permID string, relation string) (*Permission, int, error)
CreateRole(roleID string) (string, int, error)
CreatePermission(permID string, relation string, internal bool) (string, int, error)
DeleteRole(roleID string) (string, int, error)
DeletePermission(permID string, relation string, internal bool) (string, int, error)
GetRoleByUser(userID string) ([]string, error)
GetPermissionByRole(roleID string) ([]Permission, error)
GetPermissionByUser(userID string, internal bool) ([]Permission, error)
GetRole(roleID string) ([]string, error)
GetPermission(permID string, relation string) ([]Permission, error)
}
var c = map[string]PermConnector{
"keto": KetoConnector{},
}
func GetPermissionConnector() PermConnector {
return c[conf.GetConfig().PermissionConnectorHost]
}

View File

@ -1,21 +0,0 @@
package utils
import (
"errors"
"strings"
"cloud.o-forge.io/core/oc-lib/tools"
)
func ExtractMethod(relation string, internal bool) (tools.METHOD, error) {
meths := []tools.METHOD{tools.GET, tools.PUT, tools.POST, tools.DELETE}
if internal {
meths = append(meths, []tools.METHOD{tools.STRICT_INTERNAL_GET, tools.STRICT_INTERNAL_POST, tools.STRICT_INTERNAL_POST, tools.STRICT_INTERNAL_DELETE}...)
}
for _, method := range meths {
if (!internal && strings.Contains(strings.ToUpper(relation), strings.ToUpper(method.String()))) || (internal && strings.ToUpper(relation) == strings.ToUpper(method.String())) {
return method, nil
}
}
return tools.GET, errors.New("method not found")
}

View File

@ -1,21 +0,0 @@
version: '3.4'
services:
keto:
image: oryd/keto:v0.7.0-alpha.1-sqlite
ports:
- "4466:4466"
- "4467:4467"
command: serve -c /home/ory/keto.yml
restart: on-failure
volumes:
- type: bind
source: .
target: /home/ory
container_name: keto
networks:
- catalog
networks:
catalog:
external: true

View File

@ -1,18 +0,0 @@
version: v0.6.0-alpha.1
log:
level: debug
namespaces:
- id: 0
name: open-cloud
dsn: memory
serve:
read:
host: 0.0.0.0
port: 4466
write:
host: 0.0.0.0
port: 4467

View File

@ -1,79 +0,0 @@
version: "3"
services:
hydra-client:
image: oryd/hydra:v2.2.0
container_name: hydra-client
environment:
HYDRA_ADMIN_URL: http://hydra:4445
ORY_SDK_URL: http://hydra:4445
command:
- create
- oauth2-client
- --skip-tls-verify
- --name
- test-client
- --secret
- oc-auth-got-secret
- --response-type
- id_token,token,code
- --grant-type
- implicit,refresh_token,authorization_code,client_credentials
- --scope
- openid,profile,email,roles
- --token-endpoint-auth-method
- client_secret_post
- --redirect-uri
- http://localhost:3000
networks:
- hydra-net
- catalog
deploy:
restart_policy:
condition: none
depends_on:
- hydra
healthcheck:
test: ["CMD", "curl", "-f", "http://hydra:4445"]
interval: 10s
timeout: 10s
retries: 10
hydra:
container_name: hydra
image: oryd/hydra:v2.2.0
environment:
SECRETS_SYSTEM: oc-auth-got-secret
LOG_LEAK_SENSITIVE_VALUES: true
# OAUTH2_TOKEN_HOOK_URL: http://oc-auth:8080/oc/claims
URLS_SELF_ISSUER: http://hydra:4444
URLS_SELF_PUBLIC: http://hydra:4444
WEBFINGER_OIDC_DISCOVERY_SUPPORTED_SCOPES: profile,email,phone,roles
WEBFINGER_OIDC_DISCOVERY_SUPPORTED_CLAIMS: name,family_name,given_name,nickname,email,phone_number
DSN: memory
command: serve all --dev
networks:
- hydra-net
- catalog
ports:
- "4444:4444"
- "4445:4445"
deploy:
restart_policy:
condition: on-failure
ldap:
image: pgarrett/ldap-alpine
container_name: ldap
volumes:
- "./ldap.ldif:/ldif/ldap.ldif"
networks:
- hydra-net
- catalog
ports:
- "390:389"
deploy:
restart_policy:
condition: on-failure
networks:
hydra-net:
catalog:
external: true

View File

@ -1,24 +0,0 @@
dn: uid=admin,ou=Users,dc=example,dc=com
objectClass: inetOrgPerson
cn: Admin
sn: Istrator
uid: admin
userPassword: admin
mail: admin@example.com
ou: Users
dn: ou=AppRoles,dc=example,dc=com
objectClass: organizationalunit
ou: AppRoles
description: AppRoles
dn: ou=App1,ou=AppRoles,dc=example,dc=com
objectClass: organizationalunit
ou: App1
description: App1
dn: cn=traveler,ou=App1,ou=AppRoles,dc=example,dc=com
objectClass: groupofnames
cn: traveler
description: traveler
member: uid=admin,ou=Users,dc=example,dc=com

139
main.go
View File

@ -1,115 +1,54 @@
package main
import (
"errors"
"fmt"
"oc-auth/conf"
"oc-auth/infrastructure"
_ "oc-auth/routers"
"os"
"strconv"
"strings"
oclib "cloud.o-forge.io/core/oc-lib"
peer "cloud.o-forge.io/core/oc-lib/models/peer"
"cloud.o-forge.io/core/oc-lib/models/utils"
"cloud.o-forge.io/core/oc-lib/tools"
"github.com/beego/beego/logs"
beego "github.com/beego/beego/v2/server/web"
"github.com/goraz/onion"
)
const appname = "oc-auth"
const defaultConfigFile = "/etc/oc/auth.json"
const localConfigFile = "./auth.json"
// @securityDefinitions.apikey Bearer
// @in header
// @name Authorization
// @description Type "Bearer" followed by a space and JWT token.
func main() {
// Init the oc-lib
oclib.Init(appname)
// Load the right config file
o := oclib.GetConfLoader()
log := logs.NewLogger(10000)
log.SetLogger("console")
conf.GetConfig().AdminRole = o.GetStringDefault("ADMIN_ROLE", "admin")
conf.GetConfig().PublicKeyPath = o.GetStringDefault("PUBLIC_KEY_PATH", "./pem/public.pem")
conf.GetConfig().PrivateKeyPath = o.GetStringDefault("PRIVATE_KEY_PATH", "./pem/private.pem")
conf.GetConfig().ClientSecret = o.GetStringDefault("CLIENT_SECRET", "oc-auth-got-secret")
conf.GetConfig().Auth = o.GetStringDefault("AUTH", "hydra")
conf.GetConfig().AuthConnectorHost = o.GetStringDefault("AUTH_CONNECTOR_HOST", "localhost")
conf.GetConfig().AuthConnectorPort = o.GetIntDefault("AUTH_CONNECTOR_PORT", 4444)
conf.GetConfig().AuthConnectorAdminPort = o.GetIntDefault("AUTH_CONNECTOR_ADMIN_PORT", 4445)
conf.GetConfig().PermissionConnectorHost = o.GetStringDefault("PERMISSION_CONNECTOR_HOST", "keto")
conf.GetConfig().PermissionConnectorPort = o.GetIntDefault("PERMISSION_CONNECTOR_PORT", 4466)
conf.GetConfig().PermissionConnectorAdminPort = o.GetIntDefault("PERMISSION_CONNECTOR_ADMIN_PORT", 4467)
// config LDAP
conf.GetConfig().LDAPEndpoints = o.GetStringDefault("LDAP_ENDPOINTS", "ldap:389")
conf.GetConfig().LDAPBindDN = o.GetStringDefault("LDAP_BINDDN", "cn=admin,dc=example,dc=com")
conf.GetConfig().LDAPBindPW = o.GetStringDefault("LDAP_BINDPW", "password")
conf.GetConfig().LDAPBaseDN = o.GetStringDefault("LDAP_BASEDN", "dc=example,dc=com")
conf.GetConfig().LDAPRoleBaseDN = o.GetStringDefault("LDAP_ROLE_BASEDN", "ou=AppRoles,dc=example,dc=com")
err := generateSelfPeer()
if err != nil {
panic(err)
configFile := ""
var o *onion.Onion
l3 := onion.NewEnvLayerPrefix("_", "OCAUTH_")
l2, err := onion.NewFileLayer(defaultConfigFile, nil)
if err == nil {
logs.Info("Config file found : " + defaultConfigFile)
configFile = defaultConfigFile
}
discovery()
l1, err := onion.NewFileLayer(localConfigFile, nil)
if err == nil {
logs.Info("Local config file found " + localConfigFile + ", overriding default file")
configFile = localConfigFile
}
if configFile == "" {
logs.Info("No config file found, using env")
o = onion.New(l3)
} else if l1 == nil && l2 == nil {
o = onion.New(l1, l2, l3)
} else if l1 == nil {
o = onion.New(l2, l3)
} else if l2 == nil {
o = onion.New(l1, l3)
}
conf.GetConfig().NatsUrl = o.GetStringDefault("natsurl", "http://localhost:4080")
conf.GetConfig().NatsLogin = o.GetStringDefault("natslogin", "admin")
conf.GetConfig().NatsPassword = o.GetStringDefault("natspassword", "admin")
conf.GetConfig().OidcUrl = o.GetStringDefault("oidcurl", "admin")
// Normal beego init
//if beego.BConfig.RunMode == "dev" {
beego.BConfig.WebConfig.DirectoryIndex = true
beego.BConfig.WebConfig.StaticDir["/swagger"] = "swagger"
//}
beego.Run()
}
func generateSelfPeer() error {
// TODO check if files at private & public path are set
// check if files at private & public path are set
if _, err := os.Stat(conf.GetConfig().PrivateKeyPath); errors.Is(err, os.ErrNotExist) {
return errors.New("private key path does not exist")
}
if _, err := os.Stat(conf.GetConfig().PublicKeyPath); errors.Is(err, os.ErrNotExist) {
return errors.New("public key path does not exist")
}
// check if peer already exists
p := oclib.Search(nil, strconv.Itoa(peer.SELF.EnumIndex()), oclib.LibDataEnum(oclib.PEER))
if len(p.Data) > 0 {
// check public key with the one in the database
f, err := os.ReadFile(conf.GetConfig().PublicKeyPath)
if err != nil {
return err
}
// compare the public key from file with the one in the database
if !strings.Contains(string(f), p.Data[0].(*peer.Peer).PublicKey) {
return errors.New("public key is different from the one in the database")
}
return nil
}
// create a new peer
o := oclib.GetConfLoader()
peer := &peer.Peer{
Url: o.GetStringDefault("HOSTNAME", "http://localhost"),
AbstractObject: utils.AbstractObject{
Name: o.GetStringDefault("NAME", "local"),
},
PublicKey: conf.GetConfig().PublicKeyPath,
State: peer.SELF,
}
data := oclib.StoreOne(oclib.LibDataEnum(oclib.PEER), peer.Serialize())
if data.Err != "" {
return errors.New(data.Err)
}
return nil
}
func discovery() {
fmt.Println("Discovered")
api := tools.API{}
conn := infrastructure.GetPermissionConnector()
conn.CreateRole(conf.GetConfig().AdminRole)
conn.BindRole(conf.GetConfig().AdminRole, "admin")
addPermissions := func(m map[string]interface{}) {
for k, v := range m {
for _, p := range v.([]interface{}) {
conn.CreatePermission(k, p.(string), true)
}
}
}
api.ListenRouter(addPermissions)
tools.NewNATSCaller().SetNATSPub("api", tools.DISCOVERY, map[string]interface{}{})
}

10
models/application.go Normal file
View File

@ -0,0 +1,10 @@
package models
// OpenId application
type Application struct {
ClientId string `json:"client_id,omitempty"`
ClientName string `json:"client_name,omitempty"`
ClientSecret string `json:"client_secret,omitempty"`
AccessToken string `json:"access_token,omitempty"`
CallbackUrl string `json:"callback_url,omitempty"`
}

12
models/auth.go Normal file
View File

@ -0,0 +1,12 @@
package models
import (
"fmt"
"oc-auth/conf"
)
func init() {
c := conf.GetConfig()
// configure storage
fmt.Println(c.NatsUrl)
}

BIN
oc-auth

Binary file not shown.

View File

@ -1,51 +0,0 @@
-----BEGIN RSA PRIVATE KEY-----
MIIJKQIBAAKCAgEAw2pdG6wMtuLcP0+k1LFvIb0DQo/oHW2uNJaEJK74plXqp4zt
z2dRb+RQHFLeLuqk4i/zc3b4K3fKPXSlwnVPJCwzPrnyT8jYGOZVlWlETiV9xeJh
u6s/Bh6g1PWz75XjjwV50iv/CEiLNBT23f/3J44wrQzygqNQCiQSALdxWLAEl4l5
kHSa9oMyV70/Uql94/ayMARZsHgp9ZvqQKbkZPw6yzVMfCBxQozlNlo315OHevud
hnhpDRjN5I7zWmqYt6rbXJJC7Y3Izdvzn7QI88RqjSRST5I/7Kz3ndCqrOnI+OQU
E5NTREyQebphvQfTDTKlRPXkdyktdK2DH28Zj6ZF3yjQvN35Q4zhOzlq77dO5Ihh
opI7ct8dZH1T1nYkvdyCA/EVMtQsASmBOitH0Y0ACoXQK5Kb6nm/TcM/9ZSJUNiE
Muy5gBZ3YKE9oa4cpTpPXwcA+S/cU7HPNnQAsvD3iJi8GTW9uJs84pn4/WhpQqmX
d4rvhKWECCN3fHy01fUs/U0PaSj2jDY/kQVeXoikNMzPUjdZd9m816TIBh3v3aVX
CH/0iTHHAxctvDgMRb2fpvRJ/wwnYjFG9RpamVFDMvC9NffuYzWAA9IRIY4cqger
fHrVZ2HHiPTDDvDAIsvImXZc/h7mXN6m3RCQ4Qywy993wd9gUdgg/qnynHcCAwEA
AQKCAgBSRc29gMo5lXm1DgsPoURwp+tfcsb+3NajPVuVNjVpknKg6CyXTaBzw2QX
CKyShCe3MwkEa+pAIsb66MmA/XK8f/9zQUZLYPvaP994cEFZxV8WmSEcqhR2tx5v
iqKfFDQiWuPXIL7W9fPlkY3+GW4tMSg9M15GsgtYuab6tkD6XeERC8gqkW1MrB/d
4MdwPfvKpmqO3MYGDhFcXrBZV+qAudDnDSGOgPouUrOOFp28HVjE5nqDyt4vrWnB
+I1sW8TATybb6phS+4a3ZQtFCb9bIi7aDZi595ECTDBUOS4ibqs2XpA1TamY78ND
/Lx5oXmx7Mi4J+5wXN3Oad7ytQvFOdOttILNpAMFbLU5yKsxf+EDjCBcR5faNAtu
wAMH9TkzFpmhp5NBwQdAkCFnhyla363ljmlGAWPuG/D9bVZ0qtBf3NAF4hEJ/L4n
vYQFErd64tPasAgWPow2LLvqi3jT232aDgahj1lX1enHoR6TbQE4r3zy8DeA7i0C
hA8GFAvMsqIcee9Xi4yD8QFEH0PrJh6zP1PWKXR4AQVExnFGanz0s6O1GRqLPrIK
31NiRTwIVp0xbet9/GsJxWxqrTKPqd5yJvUGG3A4EL8e3RdWRM5vTHbNCVGi9LhS
3OIXV9/YOQJtWxzWUjFN3HpaNuWHVSR149GAYpTxeh+/ZGoAQQKCAQEA9RzG0LrB
/onSnzfAXD5IwGW/jSb4e8VLCZ/7W0CiD1ht23Q1pAR4bofSYXdx/rhVhRty+38q
GzugBPcejGeGYyKIViO1e8Psrd6dydYoaA9fX3YzcZ0onk9t+tYNxVhstolfIGgc
KW1qwDNrV1PP0N/oQU4QPxLmwcf/BSSl3sf53mVMzcnHkjCF5SgEN1rtIAOUZaM8
B4urSSMZMLpwmhXF9rAUPXWgLS+0fkrQzoaBS2ZfqEcFNs1ln8sTBeoXAz6kyZem
0To1oYhTeN+Tg11quWhJKiTMYmSGT3B7nVt25n0BypDktfaUU+LMY9/BewWwE6xx
iX97bldgv6y4uwKCAQEAzBh5IYa09uJTwrxY0IKVfkXRp2S+8fqhJ5qhEPykCF+4
JJBKPp7IA7rhcf5tw3NVpa/YE1h2H1P5Z4EQkzgETExVotBlOYYNmkBkd9etURGs
omAPHprnvT7q+dR/rc8/lQt3Xzvej4P4zSRbnzg/q2K0I1qs3vOwnZyO3GXk6eni
Q59k0y8zosKdde7m1YJ+KAj5MZc3PeHTfbLaLcfXnTSUX6xwnX+Js8kr2PVP+wSj
sExakP6ieNu/ZzFcYv6aiPgyXIWO/5pjwLt/GTqUPQcO9W76m0w24lWnYCx1iySw
alrl2irL2rnlXJin7q4FttHTWbeH90RVt3050m8ddQKCAQEAkgylgnXlZc+lim1j
1xLdspZt/qM76DP0tDV5RjRK3C3qt5qU47guMl4Hwz+y0v3vJzLl3mk1I6jxfkPp
FewRrTxEVF9OogJqImfFSSCsTuTqBS2fFZF5RGs7svyck/xOOq272sluDlk+BGwf
B5fO+jyQXWkwUQToLosGr3/YvdgWUKe3jd8vZTI4dgTUDk/Ffw/i+nS7LhvQ4fFh
7yEIOyfCH21ngf92g7YrLB1UMdr/a3gCg3hd6PuWFBKisSF8uNg4xE3yfjTbA/cB
FcLSWLHvB67V+aCXkAEp7metoGOBg3D1Akg3nxzf4OQAuXn4BV+sPOzBchZd669w
3IUERQKCAQBxPE7QjBWROKcyTx+TqC/bHE+i6SGLzftlpsQgUZuMzdaz6p5Wue/N
Kf11Kq2pmC73u2VN7nGzFfs1MwWIOLchweRtbeQLk1WutHVJjI8rgHvgpx0cZOOY
OvVR4VVpkKf9QJxdaTElPRpobviqkSG6LAw35VIubNQbzkXxAFOOeGZCEIh3JyQl
9IY6bW8DHOBzw+7GVdifa9DUV8v3RH5bSVXc8yaUK7Ox3TaHrCtQ4RUUdnh1I+Hu
3jUGwvs4LXx96/69GJjrNbSMtTpiO/8NEQJ6p7VBPnrg/pbbpC8fIR8EEySd88qg
sy0PP99EbKbc9POnPk2gofhQ0pinKWEVAoIBAQC0h8J3lGSG9Ki9QJvAOdMqnsSg
uoqjI0y6RmeR7LpYX1ASKNNImjG1hwLyZ8Qg5hCNjySEqBAGGd3MBNfIC6wzBDrV
zSJIrxjvu+2sfz1nUGdYWjQfhx3cT+yGqT6NEQupmstNukxiu2HDu76pi96AX2mk
TXYXlubIpfL50dWZ0wij0LivH6TPavvjbRZnXNVth1qlZOUtuBGyEwcXb4COtqRq
+nP8AEgzKxbMJFVy3PY5E5JyjB5d1ZPQ2OeYUVbfDEEYqzkorjByCcLdv7O1CHNq
VjUyJsd8F1tuCGPxbcbgyCeIqgDM1JxO4zTMSP+C82Ar7VXkr6Q8hAsCgHQ/
-----END RSA PRIVATE KEY-----

View File

@ -1,13 +0,0 @@
-----BEGIN RSA PUBLIC KEY-----
MIICCgKCAgEAw2pdG6wMtuLcP0+k1LFvIb0DQo/oHW2uNJaEJK74plXqp4ztz2dR
b+RQHFLeLuqk4i/zc3b4K3fKPXSlwnVPJCwzPrnyT8jYGOZVlWlETiV9xeJhu6s/
Bh6g1PWz75XjjwV50iv/CEiLNBT23f/3J44wrQzygqNQCiQSALdxWLAEl4l5kHSa
9oMyV70/Uql94/ayMARZsHgp9ZvqQKbkZPw6yzVMfCBxQozlNlo315OHevudhnhp
DRjN5I7zWmqYt6rbXJJC7Y3Izdvzn7QI88RqjSRST5I/7Kz3ndCqrOnI+OQUE5NT
REyQebphvQfTDTKlRPXkdyktdK2DH28Zj6ZF3yjQvN35Q4zhOzlq77dO5IhhopI7
ct8dZH1T1nYkvdyCA/EVMtQsASmBOitH0Y0ACoXQK5Kb6nm/TcM/9ZSJUNiEMuy5
gBZ3YKE9oa4cpTpPXwcA+S/cU7HPNnQAsvD3iJi8GTW9uJs84pn4/WhpQqmXd4rv
hKWECCN3fHy01fUs/U0PaSj2jDY/kQVeXoikNMzPUjdZd9m816TIBh3v3aVXCH/0
iTHHAxctvDgMRb2fpvRJ/wwnYjFG9RpamVFDMvC9NffuYzWAA9IRIY4cqgerfHrV
Z2HHiPTDDvDAIsvImXZc/h7mXN6m3RCQ4Qywy993wd9gUdgg/qnynHcCAwEAAQ==
-----END RSA PUBLIC KEY-----

View File

@ -7,186 +7,51 @@ import (
func init() {
beego.GlobalControllerRouter["oc-auth/controllers:OAuthController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:OAuthController"],
beego.ControllerComments{
Method: "InternalAuthForward",
Router: `/forward`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:OAuthController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:OAuthController"],
beego.ControllerComments{
Method: "Introspect",
Router: `/introspect`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:OAuthController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:OAuthController"],
beego.ControllerComments{
Method: "LoginLDAP",
Router: `/ldap/login`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:OAuthController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:OAuthController"],
beego.ControllerComments{
Method: "LogOutLDAP",
Router: `/ldap/logout`,
AllowHTTPMethods: []string{"delete"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:OAuthController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:OAuthController"],
beego.ControllerComments{
Method: "Refresh",
Router: `/refresh`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"],
beego.ControllerComments{
Method: "GetAll",
Router: `/`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"],
beego.ControllerComments{
Method: "Get",
Router: `/:id/:relation`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"],
beego.ControllerComments{
Method: "Bind",
Router: `/:permission_id/:role_id/:relation`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"],
beego.ControllerComments{
Method: "UnBind",
Router: `/:permission_id/:role_id/:relation`,
AllowHTTPMethods: []string{"delete"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"],
beego.ControllerComments{
Method: "Clear",
Router: `/clear`,
AllowHTTPMethods: []string{"delete"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"],
beego.ControllerComments{
Method: "GetByRole",
Router: `/role/:id`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:PermissionController"],
beego.ControllerComments{
Method: "GetByUser",
Router: `/user/:id`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:RoleController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:RoleController"],
beego.ControllerComments{
Method: "GetAll",
Router: `/`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:RoleController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:RoleController"],
beego.GlobalControllerRouter["oc-auth/controllers:AuthController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:AuthController"],
beego.ControllerComments{
Method: "Post",
Router: `/:id`,
Router: `/`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:RoleController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:RoleController"],
beego.GlobalControllerRouter["oc-auth/controllers:AuthController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:AuthController"],
beego.ControllerComments{
Method: "Get",
Router: `/:id`,
Router: `/:authId`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:RoleController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:RoleController"],
beego.GlobalControllerRouter["oc-auth/controllers:AuthController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:AuthController"],
beego.ControllerComments{
Method: "Delete",
Router: `/:id`,
Router: `/:authId`,
AllowHTTPMethods: []string{"delete"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:RoleController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:RoleController"],
beego.GlobalControllerRouter["oc-auth/controllers:AuthController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:AuthController"],
beego.ControllerComments{
Method: "Bind",
Router: `/:user_id/:role_id`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:RoleController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:RoleController"],
beego.ControllerComments{
Method: "UnBind",
Router: `/:user_id/:role_id`,
AllowHTTPMethods: []string{"delete"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:RoleController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:RoleController"],
beego.ControllerComments{
Method: "Clear",
Router: `/clear`,
AllowHTTPMethods: []string{"delete"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:RoleController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:RoleController"],
beego.ControllerComments{
Method: "GetByUser",
Router: `/user/:id`,
Method: "Find",
Router: `/find/:query`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:RegistrationController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:RegistrationController"],
beego.ControllerComments{
Method: "Post",
Router: `/`,
AllowHTTPMethods: []string{"post"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:VersionController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:VersionController"],
beego.ControllerComments{
Method: "GetAll",
@ -196,13 +61,4 @@ func init() {
Filters: nil,
Params: nil})
beego.GlobalControllerRouter["oc-auth/controllers:VersionController"] = append(beego.GlobalControllerRouter["oc-auth/controllers:VersionController"],
beego.ControllerComments{
Method: "Get",
Router: `/discovery`,
AllowHTTPMethods: []string{"get"},
MethodParams: param.Make(),
Filters: nil,
Params: nil})
}

View File

@ -1,10 +1,10 @@
// @APIVersion 1.0.0
// @Title oc-auth
// @Description OpenCloud authentication services
// @Contact admin@o-cloud.io
// @TermsOfServiceUrl http://cloud.o-forge.io/
// @License AGPL
// @LicenseUrl https://www.gnu.org/licenses/agpl-3.0.html
// @Title beego Test API
// @Description beego has a very cool tools to autogenerate documents for your API
// @Contact astaxie@gmail.com
// @TermsOfServiceUrl http://beego.me/
// @License Apache 2.0
// @LicenseUrl http://www.apache.org/licenses/LICENSE-2.0.html
package routers
import (
@ -14,18 +14,15 @@ import (
)
func init() {
ns := beego.NewNamespace("/oc/",
beego.NSInclude(
&controllers.OAuthController{},
),
beego.NSNamespace("/role",
ns := beego.NewNamespace("/oc",
beego.NSNamespace("/auth",
beego.NSInclude(
&controllers.RoleController{},
&controllers.AuthController{},
),
),
beego.NSNamespace("/permission",
beego.NSNamespace("/registration",
beego.NSInclude(
&controllers.PermissionController{},
&controllers.RegistrationController{},
),
),
beego.NSNamespace("/version",
@ -34,5 +31,6 @@ func init() {
),
),
)
beego.AddNamespace(ns)
}

View File

@ -1,479 +1,20 @@
{
"swagger": "2.0",
"info": {
"title": "oc-auth",
"description": "OpenCloud authentication services\n",
"title": "beego Test API",
"description": "beego has a very cool tools to autogenerate documents for your API\n",
"version": "1.0.0",
"termsOfService": "http://cloud.o-forge.io/",
"termsOfService": "http://beego.me/",
"contact": {
"email": "admin@o-cloud.io"
"email": "astaxie@gmail.com"
},
"license": {
"name": "AGPL",
"url": "https://www.gnu.org/licenses/agpl-3.0.html"
"name": "Apache 2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}
},
"basePath": "/oc/",
"basePath": "/oc",
"paths": {
"/forward": {
"get": {
"tags": [
"oc-auth/controllersOAuthController"
],
"description": "auth forward\n\u003cbr\u003e",
"operationId": "OAuthController.AuthForward",
"parameters": [
{
"in": "header",
"name": "Authorization",
"description": "auth token",
"type": "string"
}
],
"responses": {
"200": {
"description": "{string}"
}
}
}
},
"/introspect": {
"get": {
"tags": [
"oc-auth/controllersOAuthController"
],
"description": "introspect token\n\u003cbr\u003e",
"operationId": "OAuthController.Introspection",
"parameters": [
{
"in": "header",
"name": "Authorization",
"description": "auth token",
"type": "string"
}
],
"responses": {
"200": {
"description": "{string}"
}
}
}
},
"/ldap/login": {
"post": {
"tags": [
"oc-auth/controllersOAuthController"
],
"description": "authenticate user\n\u003cbr\u003e",
"operationId": "OAuthController.Login",
"parameters": [
{
"in": "body",
"name": "body",
"description": "The workflow content",
"required": true,
"schema": {
"$ref": "#/definitions/models.workflow"
}
}
],
"responses": {
"200": {
"description": "{string}"
}
}
}
},
"/ldap/logout": {
"delete": {
"tags": [
"oc-auth/controllersOAuthController"
],
"description": "unauthenticate user\n\u003cbr\u003e",
"operationId": "OAuthController.Logout",
"parameters": [
{
"in": "header",
"name": "Authorization",
"description": "auth token",
"type": "string"
}
],
"responses": {
"200": {
"description": "{string}"
}
}
}
},
"/permission/": {
"get": {
"tags": [
"permission"
],
"description": "find permissions\n\u003cbr\u003e",
"operationId": "PermissionController.GetAll",
"responses": {
"200": {
"description": "{permission} string"
}
}
}
},
"/permission/clear": {
"delete": {
"tags": [
"permission"
],
"description": "clear the permission\n\u003cbr\u003e",
"operationId": "PermissionController.Clear",
"responses": {
"200": {
"description": "{string} delete success!"
}
}
}
},
"/permission/role/{id}": {
"get": {
"tags": [
"permission"
],
"description": "find permission by role id\n\u003cbr\u003e",
"operationId": "PermissionController.GetByRole",
"parameters": [
{
"in": "path",
"name": "id",
"description": "the id you want to get",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{auth} string"
}
}
}
},
"/permission/user/{id}": {
"get": {
"tags": [
"permission"
],
"description": "find permission by user id\n\u003cbr\u003e",
"operationId": "PermissionController.GetByUser",
"parameters": [
{
"in": "path",
"name": "id",
"description": "the id you want to get",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{auth} string"
}
}
}
},
"/permission/{id}/{relation}": {
"get": {
"tags": [
"permission"
],
"description": "find auth by permission\n\u003cbr\u003e",
"operationId": "PermissionController.Get",
"parameters": [
{
"in": "path",
"name": "id",
"description": "the permission you want to get",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{auth} models.auth"
}
}
}
},
"/permission/{permission_id}/{role_id}/{relation}": {
"post": {
"tags": [
"permission"
],
"description": "bind the permission to role\n\u003cbr\u003e",
"operationId": "PermissionController.Bind",
"parameters": [
{
"in": "path",
"name": "role_id",
"description": "The role_id you want to bind",
"required": true,
"type": "string"
},
{
"in": "path",
"name": "method",
"description": "The method you want to relate role \u0026 permission",
"required": true,
"type": "string"
},
{
"in": "path",
"name": "permission_id",
"description": "The permission_id you want to bind",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{string} bind success!"
}
}
},
"delete": {
"tags": [
"permission"
],
"description": "unbind the permission to role\n\u003cbr\u003e",
"operationId": "PermissionController.UnBind",
"parameters": [
{
"in": "path",
"name": "role_id",
"description": "The role_id you want to unbind",
"required": true,
"type": "string"
},
{
"in": "path",
"name": "relation",
"description": "The method you want to unrelate role \u0026 permission",
"required": true,
"type": "string"
},
{
"in": "path",
"name": "permission_id",
"description": "The permission_id you want to unbind",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{string} bind success!"
}
}
}
},
"/refresh": {
"post": {
"tags": [
"oc-auth/controllersOAuthController"
],
"description": "introspect token\n\u003cbr\u003e",
"operationId": "OAuthController.Introspection",
"parameters": [
{
"in": "body",
"name": "body",
"description": "The token info",
"required": true,
"schema": {
"$ref": "#/definitions/models.Token"
}
}
],
"responses": {
"200": {
"description": "{string}"
}
}
}
},
"/role/": {
"get": {
"tags": [
"role"
],
"description": "find roles\n\u003cbr\u003e",
"operationId": "RoleController.GetAll",
"responses": {
"200": {
"description": "{role} string"
}
}
}
},
"/role/clear": {
"delete": {
"tags": [
"role"
],
"description": "clear the role\n\u003cbr\u003e",
"operationId": "RoleController.Clear",
"responses": {
"200": {
"description": "{string} delete success!"
}
}
}
},
"/role/user/{id}": {
"get": {
"tags": [
"role"
],
"description": "find role by user id\n\u003cbr\u003e",
"operationId": "RoleController.GetByUser",
"parameters": [
{
"in": "path",
"name": "id",
"description": "the id you want to get",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{auth} string"
}
}
}
},
"/role/{id}": {
"get": {
"tags": [
"role"
],
"description": "find role by id\n\u003cbr\u003e",
"operationId": "RoleController.Get",
"parameters": [
{
"in": "path",
"name": "id",
"description": "the id you want to get",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{role} string"
}
}
},
"post": {
"tags": [
"role"
],
"description": "create role\n\u003cbr\u003e",
"operationId": "RoleController.Create",
"parameters": [
{
"in": "path",
"name": "id",
"description": "the id you want to get",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{auth} create success!"
}
}
},
"delete": {
"tags": [
"role"
],
"description": "delete the role\n\u003cbr\u003e",
"operationId": "RoleController.Delete",
"parameters": [
{
"in": "path",
"name": "id",
"description": "The id you want to delete",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{string} delete success!"
}
}
}
},
"/role/{user_id}/{role_id}": {
"post": {
"tags": [
"role"
],
"description": "bind the role to user\n\u003cbr\u003e",
"operationId": "RoleController.Bind",
"parameters": [
{
"in": "path",
"name": "user_id",
"description": "The user_id you want to bind",
"required": true,
"type": "string"
},
{
"in": "path",
"name": "role_id",
"description": "The role_id you want to bind",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{string} bind success!"
}
}
},
"delete": {
"tags": [
"role"
],
"description": "unbind the role to user\n\u003cbr\u003e",
"operationId": "RoleController.UnBind",
"parameters": [
{
"in": "path",
"name": "role_id",
"description": "The role_id you want to unbind",
"required": true,
"type": "string"
},
{
"in": "path",
"name": "user_id",
"description": "The user_id you want to unbind",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{string} bind success!"
}
}
}
},
"/version/": {
"get": {
"tags": [
@ -488,42 +29,123 @@
}
}
},
"/version/discovery": {
"get": {
"/auth/": {
"post": {
"tags": [
"version"
"auth"
],
"description": "create auths\n\u003cbr\u003e",
"operationId": "AuthController.Create",
"parameters": [
{
"in": "body",
"name": "body",
"description": "The auth content",
"required": true,
"schema": {
"type": "array",
"items": {
"$ref": "#/definitions/models.auth"
}
}
}
],
"description": "get version\n\u003cbr\u003e",
"operationId": "VersionController.Get",
"responses": {
"200": {
"description": "{string} models.auth.Id"
},
"403": {
"description": "body is empty"
}
}
}
},
"/auth/find/{query}": {
"get": {
"tags": [
"auth"
],
"description": "find auths with query\n\u003cbr\u003e",
"operationId": "AuthController.Find",
"parameters": [
{
"in": "path",
"name": "query",
"description": "the keywords you need",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{auths} []models.auth"
},
"403": {
"description": ""
}
}
}
},
"/auth/{authId}": {
"get": {
"tags": [
"auth"
],
"description": "find auth by authid\n\u003cbr\u003e",
"operationId": "AuthController.Get",
"parameters": [
{
"in": "path",
"name": "authId",
"description": "the authid you want to get",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{auth} models.auth"
},
"403": {
"description": ":authId is empty"
}
}
},
"delete": {
"tags": [
"auth"
],
"description": "delete the auth\n\u003cbr\u003e",
"operationId": "AuthController.Delete",
"parameters": [
{
"in": "path",
"name": "authId",
"description": "The authId you want to delete",
"required": true,
"type": "string"
}
],
"responses": {
"200": {
"description": "{string} delete success!"
},
"403": {
"description": "authId is empty"
}
}
}
}
},
"definitions": {
"models.Token": {
"title": "Token",
"type": "object"
},
"models.workflow": {
"title": "workflow",
"models.auth": {
"title": "auth",
"type": "object"
}
},
"tags": [
{
"name": "oc-auth/controllersOAuthController",
"description": "Operations about auth\n"
},
{
"name": "role",
"description": "Operations about auth\n"
},
{
"name": "permission",
"name": "auth",
"description": "Operations about auth\n"
},
{

View File

@ -1,358 +1,17 @@
swagger: "2.0"
info:
title: oc-auth
title: beego Test API
description: |
OpenCloud authentication services
beego has a very cool tools to autogenerate documents for your API
version: 1.0.0
termsOfService: http://cloud.o-forge.io/
termsOfService: http://beego.me/
contact:
email: admin@o-cloud.io
email: astaxie@gmail.com
license:
name: AGPL
url: https://www.gnu.org/licenses/agpl-3.0.html
basePath: /oc/
name: Apache 2.0
url: http://www.apache.org/licenses/LICENSE-2.0.html
basePath: /oc
paths:
/forward:
get:
tags:
- oc-auth/controllersOAuthController
description: |-
auth forward
<br>
operationId: OAuthController.AuthForward
parameters:
- in: header
name: Authorization
description: auth token
type: string
responses:
"200":
description: '{string}'
/introspect:
get:
tags:
- oc-auth/controllersOAuthController
description: |-
introspect token
<br>
operationId: OAuthController.Introspection
parameters:
- in: header
name: Authorization
description: auth token
type: string
responses:
"200":
description: '{string}'
/ldap/login:
post:
tags:
- oc-auth/controllersOAuthController
description: |-
authenticate user
<br>
operationId: OAuthController.Login
parameters:
- in: body
name: body
description: The workflow content
required: true
schema:
$ref: '#/definitions/models.workflow'
responses:
"200":
description: '{string}'
/ldap/logout:
delete:
tags:
- oc-auth/controllersOAuthController
description: |-
unauthenticate user
<br>
operationId: OAuthController.Logout
parameters:
- in: header
name: Authorization
description: auth token
type: string
responses:
"200":
description: '{string}'
/permission/:
get:
tags:
- permission
description: |-
find permissions
<br>
operationId: PermissionController.GetAll
responses:
"200":
description: '{permission} string'
/permission/{id}/{relation}:
get:
tags:
- permission
description: |-
find auth by permission
<br>
operationId: PermissionController.Get
parameters:
- in: path
name: id
description: the permission you want to get
required: true
type: string
responses:
"200":
description: '{auth} models.auth'
/permission/{permission_id}/{role_id}/{relation}:
post:
tags:
- permission
description: |-
bind the permission to role
<br>
operationId: PermissionController.Bind
parameters:
- in: path
name: role_id
description: The role_id you want to bind
required: true
type: string
- in: path
name: method
description: The method you want to relate role & permission
required: true
type: string
- in: path
name: permission_id
description: The permission_id you want to bind
required: true
type: string
responses:
"200":
description: '{string} bind success!'
delete:
tags:
- permission
description: |-
unbind the permission to role
<br>
operationId: PermissionController.UnBind
parameters:
- in: path
name: role_id
description: The role_id you want to unbind
required: true
type: string
- in: path
name: relation
description: The method you want to unrelate role & permission
required: true
type: string
- in: path
name: permission_id
description: The permission_id you want to unbind
required: true
type: string
responses:
"200":
description: '{string} bind success!'
/permission/clear:
delete:
tags:
- permission
description: |-
clear the permission
<br>
operationId: PermissionController.Clear
responses:
"200":
description: '{string} delete success!'
/permission/role/{id}:
get:
tags:
- permission
description: |-
find permission by role id
<br>
operationId: PermissionController.GetByRole
parameters:
- in: path
name: id
description: the id you want to get
required: true
type: string
responses:
"200":
description: '{auth} string'
/permission/user/{id}:
get:
tags:
- permission
description: |-
find permission by user id
<br>
operationId: PermissionController.GetByUser
parameters:
- in: path
name: id
description: the id you want to get
required: true
type: string
responses:
"200":
description: '{auth} string'
/refresh:
post:
tags:
- oc-auth/controllersOAuthController
description: |-
introspect token
<br>
operationId: OAuthController.Introspection
parameters:
- in: body
name: body
description: The token info
required: true
schema:
$ref: '#/definitions/models.Token'
responses:
"200":
description: '{string}'
/role/:
get:
tags:
- role
description: |-
find roles
<br>
operationId: RoleController.GetAll
responses:
"200":
description: '{role} string'
/role/{id}:
get:
tags:
- role
description: |-
find role by id
<br>
operationId: RoleController.Get
parameters:
- in: path
name: id
description: the id you want to get
required: true
type: string
responses:
"200":
description: '{role} string'
post:
tags:
- role
description: |-
create role
<br>
operationId: RoleController.Create
parameters:
- in: path
name: id
description: the id you want to get
required: true
type: string
responses:
"200":
description: '{auth} create success!'
delete:
tags:
- role
description: |-
delete the role
<br>
operationId: RoleController.Delete
parameters:
- in: path
name: id
description: The id you want to delete
required: true
type: string
responses:
"200":
description: '{string} delete success!'
/role/{user_id}/{role_id}:
post:
tags:
- role
description: |-
bind the role to user
<br>
operationId: RoleController.Bind
parameters:
- in: path
name: user_id
description: The user_id you want to bind
required: true
type: string
- in: path
name: role_id
description: The role_id you want to bind
required: true
type: string
responses:
"200":
description: '{string} bind success!'
delete:
tags:
- role
description: |-
unbind the role to user
<br>
operationId: RoleController.UnBind
parameters:
- in: path
name: role_id
description: The role_id you want to unbind
required: true
type: string
- in: path
name: user_id
description: The user_id you want to unbind
required: true
type: string
responses:
"200":
description: '{string} bind success!'
/role/clear:
delete:
tags:
- role
description: |-
clear the role
<br>
operationId: RoleController.Clear
responses:
"200":
description: '{string} delete success!'
/role/user/{id}:
get:
tags:
- role
description: |-
find role by user id
<br>
operationId: RoleController.GetByUser
parameters:
- in: path
name: id
description: the id you want to get
required: true
type: string
responses:
"200":
description: '{auth} string'
/version/:
get:
tags:
@ -364,32 +23,90 @@ paths:
responses:
"200":
description: ""
/version/discovery:
get:
/auth/:
post:
tags:
- version
- auth
description: |-
get version
create auths
<br>
operationId: VersionController.Get
operationId: AuthController.Create
parameters:
- in: body
name: body
description: The auth content
required: true
schema:
type: array
items:
$ref: '#/definitions/models.auth'
responses:
"200":
description: '{string} models.auth.Id'
"403":
description: body is empty
/auth/{authId}:
get:
tags:
- auth
description: |-
find auth by authid
<br>
operationId: AuthController.Get
parameters:
- in: path
name: authId
description: the authid you want to get
required: true
type: string
responses:
"200":
description: '{auth} models.auth'
"403":
description: :authId is empty
delete:
tags:
- auth
description: |-
delete the auth
<br>
operationId: AuthController.Delete
parameters:
- in: path
name: authId
description: The authId you want to delete
required: true
type: string
responses:
"200":
description: '{string} delete success!'
"403":
description: authId is empty
/auth/find/{query}:
get:
tags:
- auth
description: |-
find auths with query
<br>
operationId: AuthController.Find
parameters:
- in: path
name: query
description: the keywords you need
required: true
type: string
responses:
"200":
description: '{auths} []models.auth'
"403":
description: ""
definitions:
models.Token:
title: Token
type: object
models.workflow:
title: workflow
models.auth:
title: auth
type: object
tags:
- name: oc-auth/controllersOAuthController
description: |
Operations about auth
- name: role
description: |
Operations about auth
- name: permission
- name: auth
description: |
Operations about auth
- name: version