Compare commits

..

76 Commits
v1.0.0 ... main

Author SHA1 Message Date
genofire 07a20220be fix: migrate to codeberg 2023-10-23 21:40:10 +02:00
genofire 9fe244fa48 fix: update dependencies 2023-02-25 22:48:29 +01:00
genofire d7a9f17792 feat(web/auth): add IsLoginWithUserID for request without exit 2022-09-20 20:57:06 +02:00
genofire 1fd4f64a9f feat(database): url creation by struct (for env) 2022-09-20 19:14:08 +02:00
genofire 4fc3ec1b9f make config struct koanf ready 2022-08-14 16:50:52 +02:00
genofire 2aee702fc6 database: migration in transaction 2022-06-06 01:56:24 +02:00
genofire 843a985be7 web: gofmt 2022-06-06 01:55:57 +02:00
genofire 2937b93dff web: NotFound route to root + support own http.FileSystem 2021-10-25 13:19:57 +02:00
genofire 023df961c2 fix(test(mailer)): after move to zap
continuous-integration/drone the build was successful Details
2021-09-29 14:47:31 +02:00
genofire 980510a995 web/webtest: make Logger configurable
continuous-integration/drone the build failed Details
2021-09-29 14:33:35 +02:00
genofire 694ca30e0d fix zap.Logger in webtest
continuous-integration/drone the build failed Details
2021-09-29 14:30:17 +02:00
genofire 36c185100b migrate to zap logging - fast
continuous-integration/drone the build failed Details
2021-09-29 14:08:47 +02:00
genofire 3fd1eac4d8 web/webtest: fix close testserver without mailer
continuous-integration/drone the build was successful Details
2021-09-28 04:53:47 +02:00
genofire b3f53011f2 web/webtest: setup database only on request
continuous-integration/drone the build failed Details
2021-09-28 04:33:52 +02:00
genofire 1e1571a2c3 web/webtest: setup mailserver only on request
continuous-integration/drone the build failed Details
2021-09-28 04:23:35 +02:00
genofire 009126c253 database: fix migration of testdata - or not
continuous-integration/drone the build was successful Details
2021-09-17 21:14:33 +02:00
Geno 87131021f8 ci: debian has python3 as default
continuous-integration/drone the build was successful Details
2021-09-16 02:13:25 +02:00
Geno dd176e24b2 update depends
continuous-integration/drone the build failed Details
2021-09-16 02:00:18 +02:00
Geno 9b2fe62df5 web/auth: middleware respone with 404
continuous-integration/drone the build was successful Details
2021-09-12 22:43:16 +02:00
Geno ea2ffbc424 docs: packages
continuous-integration/drone the build was successful Details
2021-09-11 11:25:54 +02:00
Geno e18eddfdda docs(web/auth): PasswordHashCost 2021-09-11 11:15:38 +02:00
Geno 2fcb2d7cb4 docs(web/webtest) 2021-09-11 11:15:24 +02:00
Geno 4758997040 fix(ci): golang v1.17
continuous-integration/drone the build was successful Details
2021-09-11 01:29:15 +02:00
Geno d86db21705 fix(web): test for json request 2021-09-10 23:52:30 +02:00
Geno 492a959d84 web/webtest: Make TestServer public
continuous-integration/drone the build failed Details
2021-09-07 13:29:25 +02:00
Geno 9e1187a161 database: toml ignore DB
continuous-integration/drone the build failed Details
2021-09-03 14:27:28 +02:00
Martin 3e90199d98
test(web/file/fs): check Size on fileinfo
continuous-integration/drone the build was successful Details
2021-07-30 18:07:59 +02:00
Martin 81bfb1154d
test(web/file): for CreateFS 2021-07-30 18:01:45 +02:00
Lennart 6db99dd2bb
replace web/file by web/file2 2021-07-30 16:34:32 +02:00
Lennart b8acc5f8af
web/file2: add createfs.go 2021-07-30 16:34:32 +02:00
Lennart 967b32fa31
web/file2: test StoreFromHTTP 2021-07-30 16:34:32 +02:00
Lennart b5a323aeb4
add web/file2 2021-07-30 16:34:32 +02:00
Geno 32f0d84427 web: error as errors
continuous-integration/drone the build is pending Details
2021-07-22 18:16:05 +02:00
Geno 9542ac4272 web/file/s3: handling
continuous-integration/drone the build is pending Details
2021-07-22 15:21:05 +02:00
Geno 671e0ac28a web/auth: make hash cost for password configurable - faster testing
continuous-integration/drone the build is pending Details
2021-07-22 14:50:23 +02:00
Geno 689bb03277 first try to setup file upload 2021-07-22 14:45:03 +02:00
Lennart 281d10aba3 document web.ContentType* and web.APIError*
continuous-integration/drone the build is pending Details
2021-07-20 12:30:02 +02:00
Geno fb766ca32b web: small fixes - mainly in docs
continuous-integration/drone the build is pending Details
2021-07-19 18:35:44 +02:00
Lennart b10fc5b588 provide^Wupdate docs of package web
continuous-integration/drone the build is pending Details
2021-07-19 18:19:06 +02:00
Geno 6af94245b6 web: move global module register to service
continuous-integration/drone the build is pending Details
2021-07-19 17:59:08 +02:00
Geno ffd77c3aab web: response by content-type
continuous-integration/drone the build is pending Details
2021-07-18 02:14:59 +02:00
Geno 7923008c9f use fork of gormigrate - Rollback with check of migration table
continuous-integration/drone the build failed Details
2021-07-15 11:21:05 +02:00
Geno 07218da3f6 web/webtest: options to make it more configurable
continuous-integration/drone the build failed Details
2021-07-14 13:57:23 +02:00
Geno 6fb3b904df remigration and rollback all
continuous-integration/drone the build failed Details
2021-07-14 13:33:22 +02:00
Geno d888e27790 web/auth: delete my user
continuous-integration/drone the build failed Details
2021-06-30 15:59:31 +02:00
Geno cc0baa3740 docs(swagger): add tags for groups
continuous-integration/drone the build was successful Details
2021-06-30 15:47:24 +02:00
Geno d38a2a28c3 webtest: without assert
continuous-integration/drone the build failed Details
2021-06-28 13:59:27 +02:00
Geno 48b828b029 webtest: improve error
continuous-integration/drone the build failed Details
2021-06-28 12:14:20 +02:00
Geno 979f5fef7d add support of Mailtesting in web/webtest
continuous-integration/drone the build failed Details
2021-06-25 15:24:47 +02:00
Geno 8c87415917 test(mailer): templates
continuous-integration/drone the build was successful Details
2021-06-23 23:18:50 +02:00
Geno 2502a3bf67 test(mailer): improve - send and fetch mail
continuous-integration/drone the build was successful Details
2021-06-23 22:55:53 +02:00
Geno 0e411ba5e2 test(web): on ci
continuous-integration/drone the build was successful Details
2021-06-23 21:45:32 +02:00
Geno 72fa8a8113 test(mailer): improve
continuous-integration/drone the build failed Details
2021-06-23 20:48:08 +02:00
Geno 87ebc96f80 test(web): improve
continuous-integration/drone the build failed Details
2021-06-23 15:00:03 +02:00
Geno 84fc14679b test(web/auth): improve password 2021-06-23 14:32:19 +02:00
Geno 36e71f7cba test(web/metrics): improve
continuous-integration/drone the build was successful Details
2021-06-23 13:42:42 +02:00
Geno 83ad1cf65f test(web/api/status): 100% LOC
continuous-integration/drone the build failed Details
2021-06-23 13:39:57 +02:00
Geno 679191c55b ci: parallel
continuous-integration/drone the build was successful Details
2021-06-23 13:32:27 +02:00
Geno b29a85551f web/auth: password set by code
continuous-integration/drone the build was successful Details
2021-06-23 13:15:23 +02:00
Geno 1848fccbef web/webtest: remove DatabaseMigration to export DB
continuous-integration/drone the build was successful Details
2021-06-22 20:56:44 +02:00
Geno 56ef5276ce web/auth: split password function 2021-06-22 20:32:53 +02:00
Geno ea83f78593 add mailer 2021-06-22 20:32:34 +02:00
Geno c66f03d829 webtest: forget database
continuous-integration/drone the build was successful Details
2021-06-15 17:58:02 +02:00
Geno 5ce9b1698b ci: fix test on database
continuous-integration/drone the build was successful Details
2021-06-02 18:20:42 +02:00
Geno a0fe660f97 test(database): improve
continuous-integration/drone the build failed Details
2021-06-02 18:00:53 +02:00
Geno 95b99107f5 test(file): improve 2021-06-02 17:06:27 +02:00
Geno 0902defa8a docs: web/auth module
continuous-integration/drone the build was successful Details
2021-06-01 18:44:09 +02:00
Geno a2bea2277b docs: improve of websocket
continuous-integration/drone the build was successful Details
2021-06-01 18:09:40 +02:00
Geno de11bae835 docs: improve of websocket
continuous-integration/drone the build was successful Details
2021-06-01 18:08:29 +02:00
Geno 1edf36b7aa docs: fix typo in web
continuous-integration/drone the build failed Details
2021-06-01 17:49:54 +02:00
Geno 106ad42e78 docs: improve webtest 2021-06-01 17:49:13 +02:00
Geno dbedcfa8f6 docs: improve webtest
continuous-integration/drone the build failed Details
2021-06-01 17:47:37 +02:00
Geno d89da311b1 docs: for multiple golang files
continuous-integration/drone the build failed Details
2021-06-01 17:41:05 +02:00
Geno d007cc0ce2 docs: README and LICENSE
continuous-integration/drone the build was successful Details
2021-06-01 17:16:09 +02:00
Geno 917e7db85b migrate ci to woodpicker
continuous-integration/drone the build was successful Details
- fix lint - install python3
- fix database
- fix coverage (use own)
2021-06-01 17:03:51 +02:00
Geno 88ca3d142e file: improve save and packing 2021-06-01 13:17:51 +02:00
90 changed files with 4023 additions and 959 deletions

View File

@ -6,3 +6,4 @@ if [ -n "$result" ]; then
echo "$result"
exit 1
fi

View File

@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
# checks if every desired package has test files
import os
@ -11,11 +11,11 @@ missing = False
for root, dirs, files in os.walk("."):
# ignore some paths
if root == "." or root == "./database/graphite" or root.startswith("./vendor") or root.startswith("./."):
if root == "." or root.startswith("./vendor") or root.startswith("./.") or root.startswith("./docs"):
continue
# source files but not test files?
if len(filter(source_re.match, files)) > 0 and len(filter(test_re.match, files)) == 0:
if len([f for f in files if source_re.match(f)]) > 0 and len([f for f in files if test_re.match(f)]) == 0:
print("no test files for {}".format(root))
missing = True
@ -23,3 +23,4 @@ if missing:
sys.exit(1)
else:
print("every package has test files")

View File

@ -1,26 +0,0 @@
pipeline:
# Library does not need to build
#build:
# image: golang:latest
# commands:
# - go get -d -t ./...
# - go install
test-coverage:
image: golang:latest
commands:
- go get -u github.com/mattn/goveralls
- go get -u golang.org/x/tools/cmd/cover
- go get -d -t ./...
- ./contrib/ci/check-coverage drone.io
codestyle:
image: golang:latest
commands:
- ./contrib/ci/check-testfiles
- ./contrib/ci/check-gofmt
- go get github.com/client9/misspell/cmd/misspell
- misspell -error .
test-race:
image: golang:latest
commands:
- go get -d -t ./...
- go test -race ./...

View File

@ -2,12 +2,12 @@ language: go
go:
- tip
install:
- go get -t dev.sum7.eu/genofire/golang-lib/...
- go get -t codeberg.org/genofire/golang-lib/...
- go get github.com/mattn/goveralls
- go get golang.org/x/tools/cmd/cover
- go get github.com/client9/misspell/cmd/misspell
script:
- cd $GOPATH/src/dev.sum7.eu/genofire/golang-lib
- cd $GOPATH/src/codeberg.org/genofire/golang-lib
# - go install # Library does not need to build
- ./contrib/ci/check-coverage travis-ci
- ./contrib/ci/check-testfiles

30
.woodpecker.yml Normal file
View File

@ -0,0 +1,30 @@
services:
database:
image: cockroachdb/cockroach:latest
commands:
- cockroach start-single-node --insecure
pipeline:
lint:
image: golang:latest
group: test
commands:
- ./.ci/check-testfiles
- ./.ci/check-gofmt
- go install github.com/client9/misspell/cmd/misspell@latest
- misspell -error .
test-coverage:
image: golang:latest
group: test
commands:
- go get -d -t ./...
- go test -ldflags "-X codeberg.org/genofire/golang-lib/web.TestRunTLS=false -X codeberg.org/genofire/golang-lib/web/webtest.DBConnection=postgres://root:root@database:26257/defaultdb?sslmode=disable -X codeberg.org/genofire/golang-lib/database.DBConnection=postgres://root:root@database:26257/defaultdb?sslmode=disable" $(go list ./... | grep -v /vendor/) -v -failfast -p 1 -coverprofile .testCoverage.txt
- go tool cover -func=".testCoverage.txt"
test-race:
image: golang:latest
group: test-race
commands:
- go get -d -t ./...
- go test -ldflags "-X codeberg.org/genofire/golang-lib/web.TestRunTLS=false -X codeberg.org/genofire/golang-lib/web/webtest.DBConnection=postgres://root:root@database:26257/defaultdb?sslmode=disable -X codeberg.org/genofire/golang-lib/database.DBConnection=postgres://root:root@database:26257/defaultdb?sslmode=disable" $(go list ./... | grep -v /vendor/) -race

View File

@ -1,21 +1,651 @@
MIT License
GNU Affero General Public License
=================================
Copyright (c) 2017 genofire
_Version 3, 19 November 2007_
_Copyright © 2007 Free Software Foundation, Inc. &lt;<http://fsf.org/>&gt;_
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:
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
## Preamble
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.
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 <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a “Source” link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a “copyright disclaimer” for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
&lt;<http://www.gnu.org/licenses/>&gt;.

View File

@ -1,9 +1,12 @@
# golang-lib
[![DroneCI](https://ci.sum7.eu/api/badges/genofire/golang-lib/status.svg?branch=master)](https://ci.sum7.eu/genofire/golang-lib)
[![Travis](https://travis-ci.org/genofire/golang-lib.svg?branch=master)](https://travis-ci.org/genofire/golang-lib) [![CircleCI](https://circleci.com/gh/genofire/golang-lib/tree/master.svg?style=shield)](https://circleci.com/gh/genofire/golang-lib/tree/master)
[![Coverage](https://coveralls.io/repos/github/genofire/golang-lib/badge.svg?branch=master)](https://coveralls.io/github/genofire/golang-lib?branch=master)
[![codecov](https://codecov.io/gh/genofire/golang-lib/branch/master/graph/badge.svg)](https://codecov.io/gh/genofire/golang-lib)
[![Go Report Card](https://goreportcard.com/badge/dev.sum7.eu/genofire/golang-lib)](https://goreportcard.com/report/dev.sum7.eu/genofire/golang-lib)
[![GoDoc](https://godoc.org/dev.sum7.eu/genofire/golang-lib?status.svg)](https://godoc.org/dev.sum7.eu/genofire/golang-lib)
[![DroneCI](https://ci.codeberg.org/api/badges/genofire/golang-lib/status.svg?branch=main)](https://ci.codeberg.org/genofire/golang-lib)
[![Go Report Card](https://goreportcard.com/badge/codeberg.org/genofire/golang-lib)](https://goreportcard.com/report/codeberg.org/genofire/golang-lib)
[![Go Reference](https://pkg.go.dev/badge/codeberg.org/genofire/golang-lib.svg)](https://pkg.go.dev/codeberg.org/genofire/golang-lib)
some packages collected for easy and often used functions
- `database`: Start by Config, Migrate
- `file`: Read and Save - JSON, TOML
- `mailer`: Send E-Mail and receive for testing
- `web`: helpers for golang-gin framework e.g. websocket, metrics, status, auth
- `worker`: cronjob

View File

@ -1,50 +0,0 @@
version: 2
jobs:
build:
docker:
- image: circleci/golang:latest
working_directory: /go/src/github.com/genofire/golang-lib
steps:
- checkout
- run: go get -d -t ./...
- run: go install
test-coverage:
docker:
- image: circleci/golang:latest
working_directory: /go/src/github.com/genofire/golang-lib
steps:
- checkout
- run: go get -d -t ./...
- run: go get github.com/mattn/goveralls
- run: go get golang.org/x/tools/cmd/cover
- run: ./contrib/ci/check-coverage circle-ci
- store_test_results:
path: ./
destination: profile.cov
codestyle:
docker:
- image: circleci/golang:latest
working_directory: /go/src/github.com/genofire/golang-lib
steps:
- checkout
- run: go get -d -t ./...
- run: ./contrib/ci/check-testfiles
- run: ./contrib/ci/check-gofmt
- run: go get github.com/client9/misspell/cmd/misspell
- run: misspell -error .
test_race:
docker:
- image: circleci/golang:latest
working_directory: /go/src/github.com/genofire/golang-lib
steps:
- checkout
- run: go get -d -t ./...
- run: go test -race ./...
workflows:
version: 2
build_and_tests:
jobs:
#- build # Library does not need to build
- test-coverage
- codestyle
- test_race

View File

@ -1,43 +0,0 @@
#!/bin/bash
# Issue: https://github.com/mattn/goveralls/issues/20
# Source: https://github.com/uber/go-torch/blob/63da5d33a225c195fea84610e2456d5f722f3963/.test-cover.sh
CI=$1
echo "run for $CI"
# circle-ci
# travis-ci
# travis-pro
if [ "$CI" == "circle-ci" ]; then
cd ${GOPATH}/src/github.com/${CIRCLE_PROJECT_USERNAME}/${CIRCLE_PROJECT_REPONAME}
fi
echo "mode: count" > profile.cov
FAIL=0
# Standard go tooling behavior is to ignore dirs with leading underscors
for dir in $(find . -maxdepth 10 -not -path './vendor/*' -not -path './.git*' -not -path '*/_*' -type d);
do
if ls $dir/*.go &> /dev/null; then
go test -v -covermode=count -coverprofile=profile.tmp $dir || FAIL=$?
if [ -f profile.tmp ]
then
tail -n +2 < profile.tmp >> profile.cov
rm profile.tmp
fi
fi
done
# Failures have incomplete results, so don't send
[ "$FAIL" -ne 0 ] && exit 1
# ci not publishing
[ "$CI" == "" ] && exit 0
if [ "$CODECOV_TOKEN" != "" ]; then
bash <(curl -s https://codecov.io/bash) -t $CODECOV_TOKEN -f profile.cov
fi
if [ "$COVERALLS_REPO_TOKEN" != "" ] ; then
goveralls -v -coverprofile=profile.cov -service=$CI -repotoken=$COVERALLS_REPO_TOKEN
fi

4
database/docs.go Normal file
View File

@ -0,0 +1,4 @@
/*
Package database implements common functionality for database with gorm.
*/
package database

12
database/error.go Normal file
View File

@ -0,0 +1,12 @@
package database
import (
"errors"
)
var (
// ErrNotConnected - database is not connected
ErrNotConnected = errors.New("database is not connected")
// ErrNothingToMigrate if nothing has to be migrated
ErrNothingToMigrate = errors.New("there is nothing to migrate")
)

59
database/external_test.go Normal file
View File

@ -0,0 +1,59 @@
package database_test
import (
"testing"
"github.com/stretchr/testify/assert"
"codeberg.org/genofire/golang-lib/database"
"github.com/knadh/koanf"
"github.com/knadh/koanf/parsers/toml"
"github.com/knadh/koanf/providers/rawbytes"
)
var (
// DBConnection - url to database on setting up default WebService for webtest
// DBConnection = "user=root password=root dbname=defaultdb host=localhost port=26257 sslmode=disable"
DBConnection = "user=root password=root dbname=defaultdb host=localhost sslmode=disable"
)
func ParseConfig(conn string) *database.Database {
k := koanf.New("/")
out := database.Database{}
k.Load(rawbytes.Provider([]byte(conn)), toml.Parser())
k.UnmarshalWithConf("", &out, koanf.UnmarshalConf{Tag: "config"})
return &out
}
func TestConn(t *testing.T) {
assert := assert.New(t)
d := ParseConfig(`
[connection]
hostname = "localhost"
username = "root"
password = "a"
dbname = "database"
extra_options = "sslmode=disable"
`)
assert.Equal("postgresql://root:a@localhost/database?sslmode=disable", d.Connection.String(), "splitted")
d = ParseConfig(`
[connection]
string = "postgresql://root:a@localhost/database?sslmode=disable"
`)
assert.Equal("postgresql://root:a@localhost/database?sslmode=disable", d.Connection.String(), "connection_string")
d = ParseConfig(`
[connection]
string = "postgresql://root:a@localhost/database?sslmode=disable"
username = "user"
password = "b"
`)
assert.Equal("postgresql://user:b@localhost/database?sslmode=disable", d.Connection.String(), "both")
}

View File

@ -1,24 +1,79 @@
package database
import (
gormigrate "github.com/go-gormigrate/gormigrate/v2"
"net/url"
gormigrate "github.com/genofire/gormigrate/v2"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
type ConnectionURI struct {
URI string `config:"string"`
Hostname string `config:"hostname"`
Username string `config:"username"`
Password string `config:"password"`
DatabaseName string `config:"dbname"`
ExtraOptions string `config:"extra_options"`
}
func (uri *ConnectionURI) String() string {
u,_ := url.Parse(uri.URI)
if u.Scheme == "" {
u.Scheme = "postgresql"
}
if uri.Hostname != "" {
u.Host = uri.Hostname
}
if uri.Username != "" && uri.Password != "" {
u.User = url.UserPassword(uri.Username, uri.Password)
}
if uri.DatabaseName != "" {
u.Path = uri.DatabaseName
}
if uri.ExtraOptions != "" {
u.RawQuery = uri.ExtraOptions
}
return u.String()
}
// Database struct to read from config
type Database struct {
DB *gorm.DB
Connection string `toml:"connection"`
Debug bool `toml:"debug"`
Testdata bool `toml:"testdata"`
LogLevel logger.LogLevel `toml:"log_level"`
DB *gorm.DB `config:"-" toml:"-"`
Connection ConnectionURI `config:"connection" toml:"connection"`
Debug bool `config:"debug" toml:"debug"`
Testdata bool `config:"testdata" toml:"testdata"`
LogLevel logger.LogLevel `config:"log_level" toml:"log_level"`
migrations map[string]*gormigrate.Migration
migrationTestdata map[string]*gormigrate.Migration
}
// Run database config - connect and migrate
func (config *Database) Run() error {
db, err := gorm.Open(postgres.Open(config.Connection), &gorm.Config{
if err := config.run(); err != nil {
return err
}
return config.migrate(config.Testdata)
}
// ReRun database config - connect and re migration
func (config *Database) ReRun() error {
if err := config.run(); err != nil {
return err
}
m, err := config.setupMigrator(true)
if err != nil {
return err
}
if err := m.RollbackAll(); err != nil {
return err
}
return config.migrate(config.Testdata)
}
func (config *Database) run() error {
db, err := gorm.Open(postgres.Open(config.Connection.String()), &gorm.Config{
Logger: logger.Default.LogMode(config.LogLevel),
})
if err != nil {
@ -30,13 +85,14 @@ func (config *Database) Run() error {
}
config.DB = db
if err = config.migrate(config.Testdata); err != nil {
return err
}
return nil
}
// Status get status - is database pingable
func (config *Database) Status() error {
if config.DB == nil {
return ErrNotConnected
}
sqlDB, err := config.DB.DB()
if err != nil {
return err

View File

@ -1 +1,37 @@
package database
import (
"testing"
"github.com/stretchr/testify/assert"
)
var (
// DBConnection - url to database on setting up default WebService for webtest
// DBConnection = "postgresql://root:root@localhost:26257/defaultdb?sslmode=disable"
DBConnection = "postgresql://root:root@localhost/defaultdb?sslmode=disable"
)
func TestStatus(t *testing.T) {
assert := assert.New(t)
d := Database{
Debug: true,
}
d.Connection.URI = "postgresql://localhost"
err := d.Status()
assert.Error(err)
assert.Equal(ErrNotConnected, err)
err = d.Run()
assert.Error(err)
assert.Contains(err.Error(), "failed to connect")
d.Connection.URI = DBConnection
err = d.Run()
assert.Error(err)
assert.Equal(ErrNothingToMigrate, err)
err = d.Status()
assert.NoError(err)
}

View File

@ -1,15 +1,9 @@
package database
import (
"errors"
"sort"
"github.com/bdlm/log"
gormigrate "github.com/go-gormigrate/gormigrate/v2"
)
var (
ErrNothingToMigrate = errors.New("there is nothing to migrate")
gormigrate "github.com/genofire/gormigrate/v2"
)
func (config *Database) sortedMigration(testdata bool) []*gormigrate.Migration {
@ -28,26 +22,46 @@ func (config *Database) sortedMigration(testdata bool) []*gormigrate.Migration {
return migrations
}
func (config *Database) Migrate() error {
return config.migrate(false)
}
func (config *Database) MigrateTestdata() error {
return config.migrate(true)
}
func (config *Database) migrate(testdata bool) error {
func (config *Database) setupMigrator(testdata bool) (*gormigrate.Gormigrate, error) {
migrations := config.sortedMigration(testdata)
if len(migrations) == 0 {
return ErrNothingToMigrate
return nil, ErrNothingToMigrate
}
m := gormigrate.New(config.DB, gormigrate.DefaultOptions, migrations)
return gormigrate.New(config.DB, &gormigrate.Options{
TableName: "migrations",
IDColumnName: "id",
IDColumnSize: 255,
UseTransaction: true,
ValidateUnknownMigrations: false,
}, migrations), nil
}
func (config *Database) migrate(testdata bool) error {
m, err := config.setupMigrator(testdata)
if err != nil {
return err
}
return m.Migrate()
}
// Migrate run migration
func (config *Database) Migrate() error {
return config.migrate(false)
}
// MigrateTestdata run migration and testdata migration
func (config *Database) MigrateTestdata() error {
return config.migrate(true)
}
// AddMigration add to database config migration step
func (config *Database) AddMigration(m ...*gormigrate.Migration) {
config.addMigrate(false, m...)
}
// AddMigrationTestdata add to database config migration step of testdata
func (config *Database) AddMigrationTestdata(m ...*gormigrate.Migration) {
config.addMigrate(true, m...)
}
@ -61,15 +75,21 @@ func (config *Database) addMigrate(testdata bool, m ...*gormigrate.Migration) {
for _, i := range m {
if testdata {
config.migrations[i.ID] = i
} else {
config.migrationTestdata[i.ID] = i
} else {
config.migrations[i.ID] = i
}
}
}
func (config *Database) ReRun(id string) {
// ReMigrate Rollback und run every migration step again till id
func (config *Database) ReMigrate(id string) error {
migrations := config.sortedMigration(true)
m, err := config.setupMigrator(true)
if err != nil {
return err
}
x := 0
for _, m := range migrations {
if m.ID == id {
@ -77,20 +97,13 @@ func (config *Database) ReRun(id string) {
}
x = x + 1
}
// TODO not found
for i := len(migrations) - 1; i >= x; i = i - 1 {
m := migrations[i]
log.Warnf("rollback %s", m.ID)
err := m.Rollback(config.DB)
if err != nil {
log.Errorf("rollback %s", err)
}
}
for _, m := range migrations {
log.Warnf("run %s", m.ID)
err := m.Migrate(config.DB)
if err != nil {
log.Errorf("run %s", err)
mStep := migrations[i]
if err := m.RollbackTo(mStep.ID); err != nil {
return err
}
}
return m.Migrate()
}

View File

@ -3,22 +3,9 @@ package file
import (
"encoding/json"
"io/ioutil"
"os"
"github.com/BurntSushi/toml"
)
// ReadTOML reads a config model from path of a yml file
func ReadTOML(path string, data interface{}) error {
file, err := ioutil.ReadFile(path)
if err != nil {
return err
}
return toml.Unmarshal(file, data)
}
// ReadJSON reads a config model from path of a yml file
func ReadJSON(path string, data interface{}) error {
file, err := os.Open(path)

View File

@ -8,29 +8,11 @@ import (
"github.com/stretchr/testify/assert"
)
func TestReadTOML(t *testing.T) {
assert := assert.New(t)
a := struct {
Text string `toml:"text"`
}{}
err := ReadTOML("testfiles/donoexists", &a)
assert.Error(err, "could find file ^^")
err = ReadTOML("testfiles/trash.txt", &a)
assert.Error(err, "could marshel file ^^")
err = ReadTOML("testfiles/ok.toml", &a)
assert.NoError(err)
assert.Equal("hallo", a.Text)
}
func TestReadJSON(t *testing.T) {
assert := assert.New(t)
a := struct {
Text string `toml:"text"`
Text string `config:"text" toml:"text"`
}{}
err := ReadJSON("testfiles/donoexists", &a)

53
file/toml.go Normal file
View File

@ -0,0 +1,53 @@
package file
import (
"os"
"time"
"github.com/naoina/toml"
)
// TOMLDuration a time.Duration inside toml files
type TOMLDuration time.Duration
// UnmarshalText implements encoding.TextUnmarshaler
func (d *TOMLDuration) UnmarshalText(data []byte) error {
duration, err := time.ParseDuration(string(data))
if err == nil {
*d = TOMLDuration(duration)
}
return err
}
// MarshalText implements encoding.TextMarshaler
func (d TOMLDuration) MarshalText() ([]byte, error) {
return []byte(time.Duration(d).String()), nil
}
// ReadTOML reads a config model from path of a toml file
func ReadTOML(file string, data interface{}) error {
f, err := os.Open(file)
if err != nil {
return err
}
defer f.Close()
return toml.NewDecoder(f).Decode(data)
}
// SaveTOML to path
func SaveTOML(outputFile string, data interface{}) error {
tmpFile := outputFile + ".tmp"
file, err := os.OpenFile(tmpFile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
return err
}
err = toml.NewEncoder(file).Encode(data)
if err != nil {
return err
}
file.Close()
return os.Rename(tmpFile, outputFile)
}

68
file/toml_test.go Normal file
View File

@ -0,0 +1,68 @@
package file
import (
"io/ioutil"
"os"
"testing"
"github.com/stretchr/testify/assert"
)
func TestTOMLDuration(t *testing.T) {
assert := assert.New(t)
var d TOMLDuration
err := d.UnmarshalText([]byte("5m"))
assert.NoError(err)
err = d.UnmarshalText([]byte("5z"))
assert.Error(err)
txt, err := d.MarshalText()
assert.NoError(err)
assert.Equal("5m0s", string(txt))
}
func TestReadTOML(t *testing.T) {
assert := assert.New(t)
a := struct {
Text string `config:"text" toml:"text"`
}{}
err := ReadTOML("testfiles/donoexists", &a)
assert.Error(err, "could find file ^^")
err = ReadTOML("testfiles/trash.txt", &a)
assert.Error(err, "could marshel file ^^")
err = ReadTOML("testfiles/ok.toml", &a)
assert.NoError(err)
assert.Equal("hallo", a.Text)
}
func TestSaveTOML(t *testing.T) {
assert := assert.New(t)
type to struct {
Value int `config:"v" toml:"v"`
}
toSave := to{Value: 3}
tmpfile, _ := ioutil.TempFile("/tmp", "lib-json-testfile.json")
err := SaveTOML(tmpfile.Name(), &toSave)
assert.NoError(err, "could not save temp")
err = SaveTOML(tmpfile.Name(), 3)
assert.Error(err, "could not save func")
toSave.Value = 4
err = SaveTOML("/proc/readonly", &toSave)
assert.Error(err, "could not save to /dev/null")
testvalue := to{}
err = ReadTOML(tmpfile.Name(), &testvalue)
assert.NoError(err)
assert.Equal(3, testvalue.Value)
os.Remove(tmpfile.Name())
}

View File

@ -3,7 +3,7 @@ package file
import (
"time"
"dev.sum7.eu/genofire/golang-lib/worker"
"codeberg.org/genofire/golang-lib/worker"
)
// NewSaveJSONWorker Starts a worker, which save periodly data to json file

60
go.mod
View File

@ -1,24 +1,50 @@
module dev.sum7.eu/genofire/golang-lib
module codeberg.org/genofire/golang-lib
go 1.16
require (
github.com/BurntSushi/toml v0.3.1
github.com/bdlm/log v0.1.20
github.com/bdlm/std v1.0.1 // indirect
github.com/chenjiandongx/ginprom v0.0.0-20201217063207-fe11b7f55a35
github.com/gin-contrib/sessions v0.0.3
github.com/bytedance/sonic v1.8.2 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/chenjiandongx/ginprom v0.0.0-20210617023641-6c809602c38a
github.com/genofire/gormigrate/v2 v2.0.1-0.20210715085530-7373801d0902
github.com/gin-contrib/sessions v0.0.5
github.com/gin-contrib/static v0.0.1
github.com/gin-gonic/autotls v0.0.3
github.com/gin-gonic/gin v1.7.2
github.com/go-gormigrate/gormigrate/v2 v2.0.0
github.com/google/uuid v1.2.0
github.com/prometheus/client_golang v1.10.0
github.com/stretchr/testify v1.7.0
golang.org/x/crypto v0.0.0-20210513164829-c07d793c2f9a
golang.org/x/time v0.0.0-20210220033141-f8bda1e9f3ba
gorm.io/driver/postgres v1.1.0
gorm.io/gorm v1.21.10
gorm.io/plugin/prometheus v0.0.0-20210507023802-dc84a49b85d1
github.com/gin-gonic/autotls v0.0.5
github.com/gin-gonic/gin v1.9.0
github.com/go-mail/mail v2.3.1+incompatible
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/uuid v1.3.0
github.com/gorilla/sessions v1.2.1 // indirect
github.com/jackc/pgx/v4 v4.18.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/cpuid v1.3.1 // indirect
github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/knadh/koanf v1.4.3 // indirect
github.com/kylelemons/godebug v1.1.0 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/minio/minio-go/v7 v7.0.49
github.com/minio/sha256-simd v1.0.0 // indirect
github.com/naoina/go-stringutil v0.1.0 // indirect
github.com/naoina/toml v0.1.1
github.com/prometheus/client_golang v1.14.0
github.com/prometheus/common v0.40.0 // indirect
github.com/prometheus/procfs v0.9.0 // indirect
github.com/smartystreets/goconvey v1.6.4 // indirect
github.com/stretchr/testify v1.8.1
github.com/ugorji/go v1.2.6 // indirect
github.com/ugorji/go/codec v1.2.10 // indirect
go.uber.org/atomic v1.10.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
go.uber.org/zap v1.24.0
golang.org/x/arch v0.2.0 // indirect
golang.org/x/crypto v0.6.0
golang.org/x/time v0.3.0
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/go-playground/assert.v1 v1.2.1 // indirect
gopkg.in/go-playground/validator.v9 v9.29.1 // indirect
gopkg.in/mail.v2 v2.3.1 // indirect
gorm.io/driver/postgres v1.4.8
gorm.io/gorm v1.24.5
gorm.io/plugin/prometheus v0.0.0-20230109022219-ee24990c7392
nhooyr.io/websocket v1.8.7
)

990
go.sum

File diff suppressed because it is too large Load Diff

4
mailer/docs.go Normal file
View File

@ -0,0 +1,4 @@
/*
Package mailer implements common functionality for sending emails and for testing
*/
package mailer

33
mailer/main.go Normal file
View File

@ -0,0 +1,33 @@
package mailer
import (
"github.com/go-mail/mail"
)
// Service to send mail
type Service struct {
SMTPHost string `config:"smtp_host" toml:"smtp_host"`
SMTPPort int `config:"smtp_port" toml:"smtp_port"`
SMTPUsername string `config:"smtp_username" toml:"smtp_username"`
SMTPPassword string `config:"smtp_password" toml:"smtp_password"`
SMTPSSL bool `config:"smtp_ssl" toml:"smtp_ssl"`
Dailer *mail.Dialer `config:"-" toml:"-"`
From string `config:"from" toml:"from"`
}
// Ping mailer
func (m *Service) Ping() error {
conn, err := m.Dailer.Dial()
if err != nil {
return err
}
// do not run in timeout or reconnect errors
return conn.Close()
}
// Setup dailer (and ping)
func (m *Service) Setup() error {
m.Dailer = mail.NewDialer(m.SMTPHost, m.SMTPPort, m.SMTPUsername, m.SMTPPassword)
m.Dailer.SSL = m.SMTPSSL
return m.Ping()
}

57
mailer/main_test.go Normal file
View File

@ -0,0 +1,57 @@
package mailer
import (
"testing"
"github.com/stretchr/testify/assert"
"go.uber.org/zap"
"github.com/go-mail/mail"
)
func TestSetupAndPing(t *testing.T) {
assert := assert.New(t)
log := zap.L()
mock, s := NewFakeServer(log)
assert.NotNil(mock)
// correct setup
err := s.Setup()
assert.NoError(err)
mock.Close()
s.SMTPPassword = "wrong"
mock, s = newFakeServer(s, log)
// wrong password
err = s.Setup()
assert.Error(err)
mock.Close()
}
func TestSend(t *testing.T) {
assert := assert.New(t)
mock, s := NewFakeServer(zap.L())
assert.NotNil(mock)
// correct setup
err := s.Setup()
assert.NoError(err)
m := mail.NewMessage()
m.SetHeader("From", s.From)
m.SetHeader("To", "bob@example.com", "cora@example.com")
m.SetAddressHeader("Cc", "dan@example.com", "Dan")
m.SetHeader("Subject", "Hello!")
m.SetBody("text/plain", "Hello Bob and Cora!")
m.AddAlternative("text/html", "Hello <b>Bob</b> and <i>Cora</i>!")
err = s.Dailer.DialAndSend(m)
assert.NoError(err)
msg := <-mock.Mails
mock.Close()
assert.Equal(s.From, msg.Header["From"][0])
assert.Contains(msg.Body, "Bob and Cora!")
}

50
mailer/template.go Normal file
View File

@ -0,0 +1,50 @@
package mailer
import (
"bytes"
hTemplate "html/template"
"text/template"
)
// Renderer for easy template of TXT or HTML
type Renderer struct {
tmpl *template.Template
hTmpl *hTemplate.Template
}
// TemplateTXT - create template render
func TemplateTXT(temp string) *Renderer {
tmpl, err := template.New("").Parse(temp)
if err != nil {
return nil
}
return &Renderer{
tmpl: tmpl,
}
}
// TemplateHTML - create template render for html
func TemplateHTML(temp string) *Renderer {
tmpl, err := hTemplate.New("").Parse(temp)
if err != nil {
return nil
}
return &Renderer{
hTmpl: tmpl,
}
}
// Render template
func (r *Renderer) Render(data interface{}) string {
var buf bytes.Buffer
if r.hTmpl != nil {
if err := r.hTmpl.Execute(&buf, data); err != nil {
return ""
}
} else {
if err := r.tmpl.Execute(&buf, data); err != nil {
return ""
}
}
return string(buf.Bytes())
}

39
mailer/template_test.go Normal file
View File

@ -0,0 +1,39 @@
package mailer
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestTemplate(t *testing.T) {
assert := assert.New(t)
value := struct {
T string
}{
T: "<script>alert('you have been pwned')</script>",
}
templ := TemplateTXT("A {{ .T }")
// invalid template
assert.Nil(templ)
templ = TemplateTXT("A {{ .T }}")
// text template
assert.Equal("", templ.Render(3))
// text template
assert.Equal("A <script>alert('you have been pwned')</script>", templ.Render(&value))
templ = TemplateHTML("A {{ .T }")
// invalid template
assert.Nil(templ)
templ = TemplateHTML("A {{ .T }}")
// html template
assert.Equal("", templ.Render(3))
// html template
assert.Equal("A &lt;script&gt;alert(&#39;you have been pwned&#39;)&lt;/script&gt;", templ.Render(&value))
}

127
mailer/test.go Normal file
View File

@ -0,0 +1,127 @@
package mailer
import (
"errors"
"fmt"
"net"
"net/textproto"
"go.uber.org/zap"
)
var defaultStartupPort = 12025
type fakeServer struct {
log *zap.Logger
s *Service
l net.Listener
Mails chan *TestingMail
}
// TestingMail a mail in format from test server
type TestingMail struct {
Header textproto.MIMEHeader
Body string
}
// NewFakeServer - to get mocked Service for mail-service
func NewFakeServer(log *zap.Logger) (*fakeServer, *Service) {
s := &Service{
SMTPHost: "127.0.0.1",
SMTPPort: defaultStartupPort,
SMTPUsername: "user",
SMTPPassword: "password",
SMTPSSL: false,
From: "golang-lib@example.org",
}
defaultStartupPort++
return newFakeServer(s, log)
}
func newFakeServer(s *Service, log *zap.Logger) (*fakeServer, *Service) {
fs := &fakeServer{
log: log,
s: s,
Mails: make(chan *TestingMail),
}
l, err := net.Listen("tcp", fmt.Sprintf("%s:%d", fs.s.SMTPHost, fs.s.SMTPPort))
if err != nil {
log.Panic("error listing", zap.Error(err))
return nil, nil
}
fs.l = l
go fs.run()
return fs, s
}
func (fs *fakeServer) Close() {
fs.l.Close()
}
func (fs *fakeServer) run() {
for {
conn, err := fs.l.Accept()
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
fs.log.Panic("Error accepting", zap.Error(err))
}
go fs.handle(conn)
}
}
func (fs *fakeServer) handle(conn net.Conn) {
defer conn.Close()
c := textproto.NewConn(conn)
defer c.Close()
c.Cmd("220 localhost.fake ESMTP Postfix")
s, _ := c.ReadLine()
if len(s) < 6 || s[:4] != "EHLO" {
c.Cmd("221 Bye")
return
}
c.Cmd("250-Hello %s", s[5:])
c.Cmd("250-PIPELINIG")
c.Cmd("250 AUTH PLAIN")
s, _ = c.ReadLine()
if s == "AUTH PLAIN AHVzZXIAcGFzc3dvcmQ=" {
c.Cmd("235 Authentication successful")
} else {
c.Cmd("535 Authentication failed")
c.Cmd("221 Bye")
return
}
for {
s, _ = c.ReadLine()
switch s {
case "QUIT":
c.Cmd("221 Bye")
return
case "DATA":
c.Cmd("354 End data with <CR><LF>.<CR><LF>")
head, _ := c.ReadMIMEHeader()
data := ""
handleMsgData:
for {
s, _ := c.ReadLine()
switch s {
case ".":
break handleMsgData
default:
data = fmt.Sprintf("%s%s\n", data, s)
c.Cmd("250 Ok")
}
}
fs.Mails <- &TestingMail{
Header: head,
Body: data,
}
default:
// fmt.Println(s)
// TODO : MAIL FROM: and RCPT TO:
c.Cmd("250 Ok")
}
}
}

26
mailer/test_test.go Normal file
View File

@ -0,0 +1,26 @@
package mailer
import (
"testing"
"github.com/stretchr/testify/assert"
"go.uber.org/zap"
)
func TestFakeServer(t *testing.T) {
assert := assert.New(t)
s := &Service{
SMTPHost: "127.0.0.1",
SMTPPort: -2,
SMTPUsername: "user",
SMTPPassword: "password",
SMTPSSL: false,
}
// Port
assert.Panics(func() {
mock, _ := newFakeServer(s, zap.L())
mock.Close()
})
}

4
web/api/status/docs.go Normal file
View File

@ -0,0 +1,4 @@
/*
Package status implements for web the module to publish the status with version and other extras
*/
package status

View File

@ -5,43 +5,47 @@ import (
"github.com/gin-gonic/gin"
"dev.sum7.eu/genofire/golang-lib/web"
"codeberg.org/genofire/golang-lib/web"
)
var (
VERSION string = ""
UP func() bool = func() bool {
// VERSION string on status API
VERSION string = ""
// UP function to detect, if API is healthy
UP func() bool = func() bool {
return true
}
// EXTRAS show more informations in status
EXTRAS interface{} = nil
)
// Status API response
type Status struct {
Version string `json:"version"`
Up bool `json:"up"`
Extras interface{} `json:"extras,omitempty"`
}
// Register status module
// @Summary Show Status of current API
// @Description Show version and status
// @Tags status
// @Produce json
// @Success 200 {object} Status
// @Failure 400 {object} web.HTTPError
// @Failure 404 {object} web.HTTPError
// @Router /api/status [get]
func init() {
web.ModuleRegister(func(r *gin.Engine, ws *web.Service) {
r.GET("/api/status", func(c *gin.Context) {
status := &Status{
Version: VERSION,
Up: UP(),
Extras: EXTRAS,
}
if !status.Up {
c.JSON(http.StatusInternalServerError, status)
return
}
c.JSON(http.StatusOK, status)
})
func Register(r *gin.Engine, ws *web.Service) {
r.GET("/api/status", func(c *gin.Context) {
status := &Status{
Version: VERSION,
Up: UP(),
Extras: EXTRAS,
}
if !status.Up {
c.JSON(http.StatusInternalServerError, status)
return
}
c.JSON(http.StatusOK, status)
})
}

View File

@ -6,18 +6,31 @@ import (
"github.com/stretchr/testify/assert"
"dev.sum7.eu/genofire/golang-lib/web/webtest"
"codeberg.org/genofire/golang-lib/web/webtest"
)
func TestAPIStatus(t *testing.T) {
assert := assert.New(t)
s := webtest.New(assert)
s, err := webtest.New(Register)
assert.NoError(err)
defer s.Close()
assert.NotNil(s)
obj := Status{}
// GET - common name
s.Request(http.MethodGet, "/api/status", nil, http.StatusOK, &obj)
// GET
err = s.Request(http.MethodGet, "/api/status", nil, http.StatusOK, &obj)
assert.NoError(err)
assert.Equal(VERSION, obj.Version)
assert.Equal(EXTRAS, obj.Extras)
assert.True(obj.Up)
UP = func() bool { return false }
obj = Status{}
// GET - failed status
err = s.Request(http.MethodGet, "/api/status", nil, http.StatusInternalServerError, &obj)
assert.NoError(err)
assert.Equal(VERSION, obj.Version)
assert.Equal(EXTRAS, obj.Extras)
assert.False(obj.Up)
}

View File

@ -8,7 +8,7 @@ import (
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"dev.sum7.eu/genofire/golang-lib/web"
"codeberg.org/genofire/golang-lib/web"
)
type login struct {
@ -18,6 +18,7 @@ type login struct {
// @Summary Login
// @Description Login by username and password, you will get a cookie of current session
// @Tags auth
// @Accept json
// @Produce json
// @Success 200 {object} User
@ -26,51 +27,49 @@ type login struct {
// @Failure 500 {object} web.HTTPError
// @Router /api/v1/auth/login [post]
// @Param body body login false "login"
func init() {
web.ModuleRegister(func(r *gin.Engine, ws *web.Service) {
r.POST("/api/v1/auth/login", func(c *gin.Context) {
var data login
if err := c.BindJSON(&data); err != nil {
c.JSON(http.StatusBadRequest, web.HTTPError{
Message: web.APIErrorInvalidRequestFormat,
Error: err.Error(),
})
return
}
func apiLogin(r *gin.Engine, ws *web.Service) {
r.POST("/api/v1/auth/login", func(c *gin.Context) {
var data login
if err := c.BindJSON(&data); err != nil {
c.JSON(http.StatusBadRequest, web.HTTPError{
Message: web.ErrAPIInvalidRequestFormat.Error(),
Error: err.Error(),
})
return
}
d := &User{}
if err := ws.DB.Where(map[string]interface{}{"username": data.Username}).First(d).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(http.StatusUnauthorized, web.HTTPError{
Message: APIErrorUserNotFound,
Error: err.Error(),
})
return
}
c.JSON(http.StatusInternalServerError, web.HTTPError{
Message: web.APIErrorInternalDatabase,
Error: err.Error(),
})
return
}
if !d.ValidatePassword(data.Password) {
d := &User{}
if err := ws.DB.Where(map[string]interface{}{"username": data.Username}).First(d).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(http.StatusUnauthorized, web.HTTPError{
Message: APIErrorIncorrectPassword,
})
return
}
session := sessions.Default(c)
session.Set("user_id", d.ID.String())
if err := session.Save(); err != nil {
c.JSON(http.StatusBadRequest, web.HTTPError{
Message: APIErrorCreateSession,
Message: ErrAPIUserNotFound.Error(),
Error: err.Error(),
})
return
}
c.JSON(http.StatusInternalServerError, web.HTTPError{
Message: web.ErrAPIInternalDatabase.Error(),
Error: err.Error(),
})
return
}
if !d.ValidatePassword(data.Password) {
c.JSON(http.StatusUnauthorized, web.HTTPError{
Message: ErrAPIIncorrectPassword.Error(),
})
return
}
c.JSON(http.StatusOK, d)
})
session := sessions.Default(c)
session.Set("user_id", d.ID.String())
if err := session.Save(); err != nil {
c.JSON(http.StatusBadRequest, web.HTTPError{
Message: ErrAPICreateSession.Error(),
Error: err.Error(),
})
return
}
c.JSON(http.StatusOK, d)
})
}

View File

@ -6,39 +6,41 @@ import (
"github.com/stretchr/testify/assert"
"dev.sum7.eu/genofire/golang-lib/database"
"dev.sum7.eu/genofire/golang-lib/web"
"dev.sum7.eu/genofire/golang-lib/web/webtest"
"codeberg.org/genofire/golang-lib/web"
"codeberg.org/genofire/golang-lib/web/webtest"
)
func TestAPILogin(t *testing.T) {
assert := assert.New(t)
s := webtest.New(assert)
s, err := webtest.NewWithDBSetup(apiLogin, SetupMigration)
assert.NoError(err)
defer s.Close()
assert.NotNil(s)
s.DatabaseMigration(func(db *database.Database) {
SetupMigration(db)
})
hErr := web.HTTPError{}
// invalid
s.Request(http.MethodPost, "/api/v1/auth/login", 1, http.StatusBadRequest, &hErr)
assert.Equal(web.APIErrorInvalidRequestFormat, hErr.Message)
err = s.Request(http.MethodPost, "/api/v1/auth/login", 1, http.StatusBadRequest, &hErr)
assert.NoError(err)
assert.Equal(web.ErrAPIInvalidRequestFormat.Error(), hErr.Message)
req := login{}
hErr = web.HTTPError{}
// invalid - user
s.Request(http.MethodPost, "/api/v1/auth/login", &req, http.StatusUnauthorized, &hErr)
assert.Equal(APIErrorUserNotFound, hErr.Message)
err = s.Request(http.MethodPost, "/api/v1/auth/login", &req, http.StatusUnauthorized, &hErr)
assert.NoError(err)
assert.Equal(ErrAPIUserNotFound.Error(), hErr.Message)
req.Username = "admin"
hErr = web.HTTPError{}
// invalid - password
s.Request(http.MethodPost, "/api/v1/auth/login", &req, http.StatusUnauthorized, &hErr)
assert.Equal(APIErrorIncorrectPassword, hErr.Message)
err = s.Request(http.MethodPost, "/api/v1/auth/login", &req, http.StatusUnauthorized, &hErr)
assert.NoError(err)
assert.Equal(ErrAPIIncorrectPassword.Error(), hErr.Message)
req.Password = "CHANGEME"
obj := User{}
// valid login
s.Request(http.MethodPost, "/api/v1/auth/login", &req, http.StatusOK, &obj)
err = s.Request(http.MethodPost, "/api/v1/auth/login", &req, http.StatusOK, &obj)
assert.NoError(err)
assert.Equal("admin", obj.Username)
}

35
web/auth/api_my_delete.go Normal file
View File

@ -0,0 +1,35 @@
package auth
import (
"net/http"
"codeberg.org/genofire/golang-lib/web"
"github.com/gin-gonic/gin"
)
// @Summary Delete own User
// @Description delete current loggedin user
// @Tags auth
// @Accept json
// @Produce json
// @Success 200 {object} bool "true if deleted"
// @Failure 401 {object} web.HTTPError
// @Failure 500 {object} web.HTTPError
// @Router /api/v1/my/profil [delete]
// @Security ApiKeyAuth
func apiMyDelete(r *gin.Engine, ws *web.Service) {
r.DELETE("/api/v1/my/profil", func(c *gin.Context) {
id, ok := GetCurrentUserID(c)
if !ok {
return
}
if err := ws.DB.Delete(&User{ID: id}).Error; err != nil {
c.JSON(http.StatusInternalServerError, web.HTTPError{
Message: web.ErrAPIInternalDatabase.Error(),
Error: err.Error(),
})
return
}
c.JSON(http.StatusOK, true)
})
}

View File

@ -0,0 +1,39 @@
package auth
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"codeberg.org/genofire/golang-lib/web"
"codeberg.org/genofire/golang-lib/web/webtest"
)
func TestAPIDeleteMyProfil(t *testing.T) {
assert := assert.New(t)
s, err := webtest.NewWithDBSetup(Register, SetupMigration)
assert.NoError(err)
defer s.Close()
assert.NotNil(s)
hErr := web.HTTPError{}
// invalid
err = s.Request(http.MethodDelete, "/api/v1/my/profil", nil, http.StatusUnauthorized, &hErr)
assert.NoError(err)
assert.Equal(ErrAPINoSession.Error(), hErr.Message)
err = s.Login(webtest.Login{
Username: "admin",
Password: "CHANGEME",
})
assert.NoError(err)
res := false
// company
err = s.Request(http.MethodDelete, "/api/v1/my/profil", nil, http.StatusOK, &res)
assert.NoError(err)
assert.True(true)
s.DB.ReMigrate("10-data-0008-01-user")
}

View File

@ -0,0 +1,55 @@
package auth
import (
"net/http"
"github.com/gin-gonic/gin"
"codeberg.org/genofire/golang-lib/web"
)
// @Summary Change Password
// @Description Change Password of current login user
// @Tags auth
// @Accept json
// @Produce json
// @Success 200 {object} boolean "if password was saved (e.g. `true`)"
// @Failure 400 {object} web.HTTPError
// @Failure 401 {object} web.HTTPError
// @Failure 500 {object} web.HTTPError
// @Router /api/v1/my/auth/password [post]
// @Security ApiKeyAuth
// @Param body body string false "new password"
func apiMyPassword(r *gin.Engine, ws *web.Service) {
r.POST("/api/v1/my/auth/password", MiddlewareLogin(ws), func(c *gin.Context) {
d, ok := GetCurrentUser(c, ws)
if !ok {
return
}
var password string
if err := c.BindJSON(&password); err != nil {
c.JSON(http.StatusBadRequest, web.HTTPError{
Message: web.ErrAPIInvalidRequestFormat.Error(),
Error: err.Error(),
})
return
}
if err := d.SetPassword(password); err != nil {
c.JSON(http.StatusInternalServerError, web.HTTPError{
Message: ErrAPICreatePassword.Error(),
Error: err.Error(),
})
return
}
if err := ws.DB.Save(&d).Error; err != nil {
c.JSON(http.StatusInternalServerError, web.HTTPError{
Message: web.ErrAPIInternalDatabase.Error(),
Error: err.Error(),
})
return
}
c.JSON(http.StatusOK, true)
})
}

View File

@ -0,0 +1,49 @@
package auth
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"codeberg.org/genofire/golang-lib/web"
"codeberg.org/genofire/golang-lib/web/webtest"
)
func TestAPIPassword(t *testing.T) {
assert := assert.New(t)
s, err := webtest.NewWithDBSetup(Register, SetupMigration)
assert.NoError(err)
defer s.Close()
assert.NotNil(s)
passwordCurrent := "CHANGEME"
passwordNew := "test"
hErr := web.HTTPError{}
// no auth
err = s.Request(http.MethodPost, "/api/v1/my/auth/password", &passwordNew, http.StatusUnauthorized, &hErr)
assert.NoError(err)
assert.Equal(ErrAPINoSession.Error(), hErr.Message)
err = s.TestLogin()
assert.NoError(err)
hErr = web.HTTPError{}
// invalid
err = s.Request(http.MethodPost, "/api/v1/my/auth/password", nil, http.StatusBadRequest, &hErr)
assert.NoError(err)
assert.Equal(web.ErrAPIInvalidRequestFormat.Error(), hErr.Message)
res := false
// set new password
err = s.Request(http.MethodPost, "/api/v1/my/auth/password", &passwordNew, http.StatusOK, &res)
assert.NoError(err)
assert.True(res)
res = false
// set old password
err = s.Request(http.MethodPost, "/api/v1/my/auth/password", &passwordCurrent, http.StatusOK, &res)
assert.NoError(err)
assert.True(res)
}

28
web/auth/api_my_status.go Normal file
View File

@ -0,0 +1,28 @@
package auth
import (
"net/http"
"github.com/gin-gonic/gin"
"codeberg.org/genofire/golang-lib/web"
)
// @Summary Login status
// @Description show user_id and username if logged in
// @Tags auth
// @Accept json
// @Produce json
// @Success 200 {object} User
// @Failure 401 {object} web.HTTPError
// @Failure 500 {object} web.HTTPError
// @Router /api/v1/my/auth/status [get]
// @Security ApiKeyAuth
func apiMyStatus(r *gin.Engine, ws *web.Service) {
r.GET("/api/v1/my/auth/status", MiddlewareLogin(ws), func(c *gin.Context) {
d, ok := GetCurrentUser(c, ws)
if ok {
c.JSON(http.StatusOK, d)
}
})
}

View File

@ -0,0 +1,35 @@
package auth
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"codeberg.org/genofire/golang-lib/web"
"codeberg.org/genofire/golang-lib/web/webtest"
)
func TestAPIMyStatus(t *testing.T) {
assert := assert.New(t)
s, err := webtest.NewWithDBSetup(Register, SetupMigration)
assert.NoError(err)
defer s.Close()
assert.NotNil(s)
hErr := web.HTTPError{}
// invalid
err = s.Request(http.MethodGet, "/api/v1/my/auth/status", nil, http.StatusUnauthorized, &hErr)
assert.NoError(err)
assert.Equal(ErrAPINoSession.Error(), hErr.Message)
err = s.TestLogin()
assert.NoError(err)
obj := User{}
// invalid - user
err = s.Request(http.MethodGet, "/api/v1/my/auth/status", nil, http.StatusOK, &obj)
assert.NoError(err)
assert.Equal("admin", obj.Username)
}

View File

@ -1,61 +0,0 @@
package auth
import (
"net/http"
"github.com/bdlm/log"
"github.com/gin-gonic/gin"
"dev.sum7.eu/genofire/golang-lib/web"
)
// @Summary Change Password
// @Description Change Password of current login user
// @Accept json
// @Produce json
// @Success 200 {object} boolean "if password was saved (e.g. `true`)"
// @Failure 400 {object} web.HTTPError
// @Failure 401 {object} web.HTTPError
// @Failure 500 {object} web.HTTPError
// @Router /api/v1/my/auth/password [post]
// @Security ApiKeyAuth
// @Param body body string false "new password"
func init() {
web.ModuleRegister(func(r *gin.Engine, ws *web.Service) {
r.POST("/api/v1/my/auth/password", MiddlewareLogin(ws), func(c *gin.Context) {
d, ok := GetCurrentUser(c, ws)
if !ok {
return
}
var password string
if err := c.BindJSON(&password); err != nil {
c.JSON(http.StatusBadRequest, web.HTTPError{
Message: web.APIErrorInvalidRequestFormat,
Error: err.Error(),
})
return
}
if err := d.SetPassword(password); err != nil {
c.JSON(http.StatusInternalServerError, web.HTTPError{
Message: APIErrroCreatePassword,
Error: err.Error(),
})
return
}
result := ws.DB.Save(&d)
if err := result.Error; err != nil {
c.JSON(http.StatusInternalServerError, web.HTTPError{
Message: web.APIErrorInternalDatabase,
Error: err.Error(),
})
return
}
if result.RowsAffected > 1 {
log.Panicf("there should not be more then 1 user with the same email, it was %d session", result.RowsAffected)
}
c.JSON(http.StatusOK, result.RowsAffected == 1)
})
})
}

View File

@ -0,0 +1,74 @@
package auth
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"gorm.io/gorm"
"codeberg.org/genofire/golang-lib/web"
)
// PasswordWithForgetCode - JSON Request to set password without login
type PasswordWithForgetCode struct {
ForgetCode uuid.UUID `json:"forget_code"`
Password string `json:"password"`
}
// @Summary Change Password with ForgetCode
// @Description Change Password of any user by generated forget code
// @Tags auth
// @Accept json
// @Produce json
// @Success 200 {object} string "username of changed password (e.g. `"admin"`)"
// @Failure 400 {object} web.HTTPError
// @Failure 401 {object} web.HTTPError
// @Failure 500 {object} web.HTTPError
// @Router /api/v1/auth/password/code [post]
// @Param body body PasswordWithForgetCode false "new password and forget code"
func apiPasswordCode(r *gin.Engine, ws *web.Service) {
r.POST("/api/v1/auth/password/code", func(c *gin.Context) {
var req PasswordWithForgetCode
if err := c.BindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, web.HTTPError{
Message: web.ErrAPIInvalidRequestFormat.Error(),
Error: err.Error(),
})
return
}
d := User{}
if err := ws.DB.Where("forget_code", req.ForgetCode).First(&d).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(http.StatusBadRequest, web.HTTPError{
Message: ErrAPIUserNotFound.Error(),
Error: err.Error(),
})
return
}
c.JSON(http.StatusInternalServerError, web.HTTPError{
Message: ErrAPICreatePassword.Error(),
Error: err.Error(),
})
return
}
if err := d.SetPassword(req.Password); err != nil {
c.JSON(http.StatusInternalServerError, web.HTTPError{
Message: ErrAPICreatePassword.Error(),
Error: err.Error(),
})
return
}
d.ForgetCode = nil
if err := ws.DB.Save(&d).Error; err != nil {
c.JSON(http.StatusInternalServerError, web.HTTPError{
Message: web.ErrAPIInternalDatabase.Error(),
Error: err.Error(),
})
return
}
c.JSON(http.StatusOK, d.Username)
})
}

View File

@ -0,0 +1,62 @@
package auth
import (
"net/http"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"codeberg.org/genofire/golang-lib/web"
"codeberg.org/genofire/golang-lib/web/webtest"
)
func TestAPIPasswordCode(t *testing.T) {
assert := assert.New(t)
s, err := webtest.NewWithDBSetup(apiPasswordCode, SetupMigration)
assert.NoError(err)
defer s.Close()
assert.NotNil(s)
forgetCode := uuid.New()
passwordCurrent := "CHANGEME"
passwordNew := "test"
s.DB.DB.Model(&User{ID: TestUser1ID}).Update("forget_code", forgetCode)
hErr := web.HTTPError{}
// invalid
err = s.Request(http.MethodPost, "/api/v1/auth/password/code", &passwordNew, http.StatusBadRequest, &hErr)
assert.NoError(err)
assert.Equal(web.ErrAPIInvalidRequestFormat.Error(), hErr.Message)
res := ""
// set new password
err = s.Request(http.MethodPost, "/api/v1/auth/password/code", &PasswordWithForgetCode{
ForgetCode: forgetCode,
Password: passwordNew,
}, http.StatusOK, &res)
assert.NoError(err)
assert.Equal("admin", res)
hErr = web.HTTPError{}
// set password without code
err = s.Request(http.MethodPost, "/api/v1/auth/password/code", &PasswordWithForgetCode{
ForgetCode: forgetCode,
Password: passwordCurrent,
}, http.StatusBadRequest, &hErr)
assert.NoError(err)
assert.Equal(ErrAPIUserNotFound.Error(), hErr.Message)
forgetCode = uuid.New()
s.DB.DB.Model(&User{ID: TestUser1ID}).Update("forget_code", forgetCode)
res = ""
// set old password
err = s.Request(http.MethodPost, "/api/v1/auth/password/code", &PasswordWithForgetCode{
ForgetCode: forgetCode,
Password: passwordCurrent,
}, http.StatusOK, &res)
assert.NoError(err)
assert.Equal("admin", res)
}

View File

@ -1,41 +0,0 @@
package auth
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"dev.sum7.eu/genofire/golang-lib/database"
"dev.sum7.eu/genofire/golang-lib/web"
"dev.sum7.eu/genofire/golang-lib/web/webtest"
)
func TestAPIPassword(t *testing.T) {
assert := assert.New(t)
s := webtest.New(assert)
assert.NotNil(s)
s.DatabaseMigration(func(db *database.Database) {
SetupMigration(db)
})
passwordCurrent := "CHANGEME"
passwordNew := "test"
hErr := web.HTTPError{}
// invalid
s.Request(http.MethodPost, "/api/v1/my/auth/password", &passwordNew, http.StatusUnauthorized, &hErr)
assert.Equal(APIErrorNoSession, hErr.Message)
s.TestLogin()
res := false
// set new password
s.Request(http.MethodPost, "/api/v1/my/auth/password", &passwordNew, http.StatusOK, &res)
assert.True(res)
res = false
// set old password
s.Request(http.MethodPost, "/api/v1/my/auth/password", &passwordCurrent, http.StatusOK, &res)
assert.True(res)
}

View File

@ -1,28 +0,0 @@
package auth
import (
"net/http"
"github.com/gin-gonic/gin"
"dev.sum7.eu/genofire/golang-lib/web"
)
// @Summary Login status
// @Description show user_id and username if logged in
// @Accept json
// @Produce json
// @Success 200 {object} User
// @Failure 401 {object} web.HTTPError
// @Failure 500 {object} web.HTTPError
// @Router /api/v1/auth/status [get]
func init() {
web.ModuleRegister(func(r *gin.Engine, ws *web.Service) {
r.GET("/api/v1/auth/status", MiddlewareLogin(ws), func(c *gin.Context) {
d, ok := GetCurrentUser(c, ws)
if ok {
c.JSON(http.StatusOK, d)
}
})
})
}

View File

@ -1,34 +0,0 @@
package auth
import (
"net/http"
"testing"
"github.com/stretchr/testify/assert"
"dev.sum7.eu/genofire/golang-lib/database"
"dev.sum7.eu/genofire/golang-lib/web"
"dev.sum7.eu/genofire/golang-lib/web/webtest"
)
func TestAPIStatus(t *testing.T) {
assert := assert.New(t)
s := webtest.New(assert)
assert.NotNil(s)
s.DatabaseMigration(func(db *database.Database) {
SetupMigration(db)
})
hErr := web.HTTPError{}
// invalid
s.Request(http.MethodGet, "/api/v1/auth/status", nil, http.StatusUnauthorized, &hErr)
assert.Equal(APIErrorNoSession, hErr.Message)
s.TestLogin()
obj := User{}
// invalid - user
s.Request(http.MethodGet, "/api/v1/auth/status", nil, http.StatusOK, &obj)
assert.Equal("admin", obj.Username)
}

4
web/auth/docs.go Normal file
View File

@ -0,0 +1,4 @@
/*
Package auth implements for web the module for authentification
*/
package auth

View File

@ -1,10 +1,20 @@
package auth
const (
APIErrorUserNotFound string = "user not found"
APIErrorIncorrectPassword string = "incorrect password"
APIErrorNoSession string = "no session"
APIErrorCreateSession string = "create session"
import "errors"
APIErrroCreatePassword string = "error during create password"
var (
// ErrAPIUserNotFound api error string if user not found
ErrAPIUserNotFound = errors.New("user not found")
// ErrAPIIncorrectPassword api error string if password is incorrect
ErrAPIIncorrectPassword = errors.New("incorrect password")
// ErrAPINoSession api error string if no session exists
ErrAPINoSession = errors.New("no session")
// ErrAPICreateSession api error string if session could not created
ErrAPICreateSession = errors.New("create session")
// ErrAPICreatePassword api error string if password could not created
ErrAPICreatePassword = errors.New("error during create password")
// ErrAPINoPermission api error string if an error happen on accesing this object
ErrAPINoPermission = errors.New("error on access an object")
)

23
web/auth/lib_password.go Normal file
View File

@ -0,0 +1,23 @@
package auth
import (
"golang.org/x/crypto/bcrypt"
)
// PasswordHashCost - to set global, for more speed or security
var PasswordHashCost = bcrypt.DefaultCost
// HashPassword - create new hash of password
func HashPassword(password string) (string, error) {
p, err := bcrypt.GenerateFromPassword([]byte(password), PasswordHashCost)
if err != nil {
return "", err
}
return string(p), nil
}
// ValidatePassword - check if given password is equal to saved hash
func ValidatePassword(hash, password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
return err == nil
}

View File

@ -9,17 +9,15 @@ import (
"github.com/google/uuid"
"gorm.io/gorm"
"dev.sum7.eu/genofire/golang-lib/web"
"codeberg.org/genofire/golang-lib/web"
)
func GetCurrentUserID(c *gin.Context) (uuid.UUID, bool) {
// IsLoginWithUserID get UserID of session in golang-gin
func IsLoginWithUserID(c *gin.Context) (uuid.UUID, bool) {
session := sessions.Default(c)
v := session.Get("user_id")
if v == nil {
c.JSON(http.StatusUnauthorized, web.HTTPError{
Message: APIErrorNoSession,
})
return uuid.Nil, false
}
@ -27,6 +25,18 @@ func GetCurrentUserID(c *gin.Context) (uuid.UUID, bool) {
return id, true
}
// GetCurrentUserID get UserID of session in golang-gin
func GetCurrentUserID(c *gin.Context) (uuid.UUID, bool) {
id, ok := IsLoginWithUserID(c)
if !ok {
c.JSON(http.StatusUnauthorized, web.HTTPError{
Message: ErrAPINoSession.Error(),
})
}
return id, ok
}
// GetCurrentUser get User of session from database in golang-gin
func GetCurrentUser(c *gin.Context, ws *web.Service) (*User, bool) {
id, ok := GetCurrentUserID(c)
if !ok {
@ -36,13 +46,13 @@ func GetCurrentUser(c *gin.Context, ws *web.Service) (*User, bool) {
if err := ws.DB.First(d).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
c.JSON(http.StatusUnauthorized, web.HTTPError{
Message: APIErrorUserNotFound,
Message: ErrAPIUserNotFound.Error(),
Error: err.Error(),
})
return nil, false
}
c.JSON(http.StatusInternalServerError, web.HTTPError{
Message: web.APIErrorInternalDatabase,
Message: web.ErrAPIInternalDatabase.Error(),
Error: err.Error(),
})
return nil, false

15
web/auth/main.go Normal file
View File

@ -0,0 +1,15 @@
package auth
import (
"codeberg.org/genofire/golang-lib/web"
"github.com/gin-gonic/gin"
)
// Register to WebService
func Register(r *gin.Engine, ws *web.Service) {
apiLogin(r, ws)
apiMyDelete(r, ws)
apiMyPassword(r, ws)
apiMyStatus(r, ws)
apiPasswordCode(r, ws)
}

View File

@ -6,9 +6,10 @@ import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"dev.sum7.eu/genofire/golang-lib/web"
"codeberg.org/genofire/golang-lib/web"
)
// MiddlewareLogin if user id in session for golang-gin
func MiddlewareLogin(ws *web.Service) gin.HandlerFunc {
return func(c *gin.Context) {
_, ok := GetCurrentUserID(c)
@ -18,9 +19,12 @@ func MiddlewareLogin(ws *web.Service) gin.HandlerFunc {
}
}
// MiddlewarePermissionParamUUID if user has access to obj, check access by uuid in golang-gin url param uuid
func MiddlewarePermissionParamUUID(ws *web.Service, obj HasPermission) gin.HandlerFunc {
return MiddlewarePermissionParam(ws, obj, "uuid")
}
// MiddlewarePermissionParam if user has access to obj, check access in golang-gin url by param
func MiddlewarePermissionParam(ws *web.Service, obj HasPermission, param string) gin.HandlerFunc {
return func(c *gin.Context) {
userID, ok := GetCurrentUserID(c)
@ -30,18 +34,24 @@ func MiddlewarePermissionParam(ws *web.Service, obj HasPermission, param string)
objID, err := uuid.Parse(c.Params.ByName(param))
if err != nil {
c.JSON(http.StatusUnauthorized, web.HTTPError{
Message: web.APIErrorInvalidRequestFormat,
Message: web.ErrAPIInvalidRequestFormat.Error(),
Error: err.Error(),
})
c.Abort()
}
_, err = obj.HasPermission(ws.DB, userID, objID)
d, err := obj.HasPermission(ws.DB, userID, objID)
if err != nil {
c.JSON(http.StatusUnauthorized, web.HTTPError{
Message: http.StatusText(http.StatusUnauthorized),
Message: ErrAPINoPermission.Error(),
Error: err.Error(),
})
c.Abort()
}
if d == nil {
c.JSON(http.StatusNotFound, web.HTTPError{
Message: web.ErrAPINotFound.Error(),
})
c.Abort()
}
}
}

View File

@ -2,16 +2,18 @@ package auth
import (
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
// User struct - default User model which could be extended
type User struct {
ID uuid.UUID `json:"id" gorm:"type:uuid;default:gen_random_uuid()" example:"88078ec0-2135-445f-bf05-632701c77695"`
Username string `json:"username" gorm:"unique" example:"kukoon"`
Password string `json:"-" example:"super secret password"`
ID uuid.UUID `json:"id" gorm:"type:uuid;default:gen_random_uuid()" example:"88078ec0-2135-445f-bf05-632701c77695"`
Username string `json:"username" gorm:"unique" example:"kukoon"`
Password string `json:"-" example:"super secret password"`
ForgetCode *uuid.UUID `json:"-" gorm:"forget_code;type:uuid"`
}
// NewUser by username and password
func NewUser(username, password string) (*User, error) {
user := &User{
Username: username,
@ -22,20 +24,22 @@ func NewUser(username, password string) (*User, error) {
return user, nil
}
func (this *User) SetPassword(password string) error {
p, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
// SetPassword - create new hash of password
func (u *User) SetPassword(password string) error {
p, err := HashPassword(password)
if err != nil {
return err
}
this.Password = string(p)
u.Password = p
return nil
}
func (this *User) ValidatePassword(password string) bool {
err := bcrypt.CompareHashAndPassword([]byte(this.Password), []byte(password))
return err == nil
// ValidatePassword - check if given password is equal to saved hash
func (u *User) ValidatePassword(password string) bool {
return ValidatePassword(u.Password, password)
}
// HasPermission interface for middleware check in other models
type HasPermission interface {
HasPermission(tx *gorm.DB, userID, objID uuid.UUID) (interface{}, error)
}

View File

@ -3,11 +3,12 @@ package auth
import (
"testing"
gormigrate "github.com/go-gormigrate/gormigrate/v2"
gormigrate "github.com/genofire/gormigrate/v2"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
"dev.sum7.eu/genofire/golang-lib/database"
"codeberg.org/genofire/golang-lib/database"
"github.com/stretchr/testify/assert"
)
@ -30,6 +31,7 @@ func SetupMigration(db *database.Database) {
{
ID: "10-data-0008-01-user",
Migrate: func(tx *gorm.DB) error {
PasswordHashCost = bcrypt.MinCost
user, err := NewUser("admin", "CHANGEME")
if err != nil {
return err

View File

@ -1,13 +1,17 @@
package web
import "errors"
// HTTPError is returned in HTTP error responses.
type HTTPError struct {
Message string `json:"message" example:"invalid format"`
Error string `json:"error,omitempty" example:"<internal error message>"`
Data interface{} `json:"data,omitempty" swaggerignore:"true"`
}
const (
APIErrorInvalidRequestFormat = "Invalid Request Format"
APIErrorInternalDatabase = "Internal Database Error"
APIErrorNotFound = "Not found"
// Error strings used for HTTPError.Message.
var (
ErrAPIInvalidRequestFormat = errors.New("Invalid Request Format")
ErrAPIInternalDatabase = errors.New("Internal Database Error")
ErrAPINotFound = errors.New("Not found")
)

57
web/file/createfs.go Normal file
View File

@ -0,0 +1,57 @@
package file
import (
"codeberg.org/genofire/golang-lib/web/file/fs"
"codeberg.org/genofire/golang-lib/web/file/s3"
)
// fsType represents a type of file store.
type fsType int
const (
typeFS fsType = iota
typeS3
)
var stringToType = map[string]fsType{
"fs": typeFS,
"s3": typeS3,
}
func (t *fsType) UnmarshalText(input []byte) error {
val, ok := stringToType[string(input)]
if !ok {
return ErrInvalidFSType
}
*t = val
return nil
}
// FSInfo is a TOML structure storing access information about a file store.
type FSInfo struct {
FSType fsType `config:"type" toml:"type"`
// file system
Root string `config:",omitempty" toml:",omitempty"`
// s3
Endpoint string `config:",omitempty" toml:",omitempty"`
Secure bool `config:",omitempty" toml:",omitempty"`
ID string `config:",omitempty" toml:",omitempty"`
Secret string `config:",omitempty" toml:",omitempty"`
Bucket string `config:",omitempty" toml:",omitempty"`
Location string `config:",omitempty" toml:",omitempty"`
}
// Create creates a file store from the information provided.
func (i *FSInfo) Create() (FS, error) {
switch i.FSType {
case typeFS:
if len(i.Root) == 0 {
return nil, ErrNoFSRoot
}
return &fs.FS{Root: i.Root}, nil
case typeS3:
return s3.New(i.Endpoint, i.Secure, i.ID, i.Secret, i.Bucket, i.Location)
default:
return nil, ErrNotImplementedFSType
}
}

62
web/file/createfs_test.go Normal file
View File

@ -0,0 +1,62 @@
package file_test
import (
"testing"
fsfile "codeberg.org/genofire/golang-lib/file"
"codeberg.org/genofire/golang-lib/web/file"
"github.com/stretchr/testify/assert"
)
func TestCreateFSOK(t *testing.T) {
assert := assert.New(t)
config := file.FSInfo{}
err := fsfile.ReadTOML("testdata/createfs_fs.toml", &config)
assert.NoError(err)
fs, err := config.Create()
assert.NoError(err)
assert.NoError(fs.Check())
}
func TestCreateS3(t *testing.T) {
assert := assert.New(t)
config := file.FSInfo{}
err := fsfile.ReadTOML("testdata/createfs_s3.toml", &config)
assert.NoError(err)
fs, err := config.Create()
assert.NoError(err)
assert.NoError(fs.Check())
}
func TestCreateFSNotOK(t *testing.T) {
assert := assert.New(t)
config := file.FSInfo{}
err := fsfile.ReadTOML("testdata/createfs_fsnone.toml", &config)
assert.NoError(err)
_, err = config.Create()
assert.ErrorIs(err, file.ErrNoFSRoot)
}
func TestCreateFSNone(t *testing.T) {
assert := assert.New(t)
config := file.FSInfo{}
err := fsfile.ReadTOML("testdata/createfs_none.toml", &config)
// https://github.com/naoina/toml/pull/51
assert.Contains(err.Error(), file.ErrInvalidFSType.Error())
}
func TestCreateFSInvalid(t *testing.T) {
assert := assert.New(t)
config := file.FSInfo{}
_, err := config.Create()
assert.ErrorIs(err, file.ErrNoFSRoot)
}

10
web/file/error.go Normal file
View File

@ -0,0 +1,10 @@
package file
import "errors"
// errors
var (
ErrInvalidFSType = errors.New("invalid file store type")
ErrNoFSRoot = errors.New("no file store root")
ErrNotImplementedFSType = errors.New("FSInfo.Create not implemented for provided file store type")
)

13
web/file/fileinfo.go Normal file
View File

@ -0,0 +1,13 @@
package file
import (
"io/fs"
"github.com/google/uuid"
)
type FileInfo interface {
fs.FileInfo
ID() uuid.UUID
ContentType() string
}

69
web/file/fs.go Normal file
View File

@ -0,0 +1,69 @@
/*
Package file abstracts non-hierarchical file stores. Each file consists of a
name, a MIME type, a UUID, and data. File names may be duplicate.
TODO: think about name vs. UUID againshould the ``name'' really be the filename
and not the UUID?
*/
package file
import (
"fmt"
"io"
"io/fs"
"net/http"
"strings"
"github.com/google/uuid"
)
// An FS is a file store.
type FS interface {
// Store stores a new file with the given UUID, name, and MIME type.
// Its data is taken from the provided Reader. If it encounters an
// error, it does nothing. Any existing file with the same UUID is
// overwritten.
Store(id uuid.UUID, name, contentType string, data io.Reader) error
// RemoveUUID deletes a file.
RemoveUUID(id uuid.UUID) error
// Open opens a file by its name. If multiple files have the same name,
// it is unspecified which one is opened. This may very well be very
// slow. This is bad. Go away.
Open(name string) (fs.File, error)
// OpenUUID opens a file by its UUID.
OpenUUID(id uuid.UUID) (fs.File, error)
// Check checks the health of the file store. If the file store is not
// healthy, it returns a descriptive error. Otherwise, the file store
// should be usable.
Check() error
}
// StoreFromHTTP stores the first file with given form key from an HTTP
// multipart/form-data request. Its Content-Type header is ignored; the type is
// detected. The file name is the last part of the provided file name not
// containing any slashes or backslashes.
//
// TODO: store all files with the given key instead of just the first one
func StoreFromHTTP(fs FS, r *http.Request, key string) error {
file, fileHeader, err := r.FormFile(key)
if err != nil {
return fmt.Errorf("get file from request: %w", err)
}
defer file.Close()
buf := make([]byte, 512)
n, err := file.Read(buf)
if err != nil && err != io.EOF {
return fmt.Errorf("read from file: %w", err)
}
contentType := http.DetectContentType(buf[:n])
_, err = file.Seek(0, io.SeekStart)
if err != nil {
return fmt.Errorf("seek in file: %w", err)
}
i := strings.LastIndexAny(fileHeader.Filename, "/\\")
// if i == -1 { i = -1 }
return fs.Store(uuid.New(), fileHeader.Filename[i+1:], contentType, file)
}

37
web/file/fs/file.go Normal file
View File

@ -0,0 +1,37 @@
package fs
import (
"fmt"
"io/fs"
"os"
"path"
"github.com/google/uuid"
)
// File is a file handle with its associated ID.
type File struct {
*os.File
fs *FS
id uuid.UUID
}
func (f File) Stat() (fs.FileInfo, error) {
fi := FileInfo{id: f.id}
var err error
fi.FileInfo, err = f.File.Stat()
if err != nil {
return nil, fmt.Errorf("os stat: %w", err)
}
name, err := os.ReadFile(path.Join(f.fs.Root, f.id.String(), "name"))
if err != nil {
return nil, fmt.Errorf("reading name: %w", err)
}
fi.name = string(name)
contentType, err := os.ReadFile(path.Join(f.fs.Root, f.id.String(), "type"))
if err != nil {
return nil, fmt.Errorf("reading type: %w", err)
}
fi.contentType = string(contentType)
return fi, nil
}

19
web/file/fs/fileinfo.go Normal file
View File

@ -0,0 +1,19 @@
package fs
import (
"os"
"github.com/google/uuid"
)
type FileInfo struct {
id uuid.UUID
name string
contentType string
os.FileInfo
}
func (fi FileInfo) ID() uuid.UUID { return fi.id }
func (fi FileInfo) ContentType() string { return fi.contentType }
func (fi FileInfo) Name() string { return fi.name }
func (fi FileInfo) Sys() interface{} { return fi.FileInfo }

123
web/file/fs/fs.go Normal file
View File

@ -0,0 +1,123 @@
/*
Package fs implements a non-hierarchical file store using the underlying (disk)
file system.
A file store contains directories named after UUIDs, each containing the
following files:
name the file name (``basename'')
type the file's MIME type
data the file data
This is not meant for anything for which the word ``scale'' plays any role at
all, ever, anywhere.
TODO: should io/fs ever support writable file systems, use one of those instead
of the ``disk'' (os.Open & Co.) (see https://github.com/golang/go/issues/45757)
*/
package fs
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"github.com/google/uuid"
)
// FS is an on-disk file store.
type FS struct {
// Root is the path of the file store, relative to the process's working
// directory or absolute.
Root string
}
func (fs *FS) Store(id uuid.UUID, name, contentType string, data io.Reader) error {
p := path.Join(fs.Root, id.String())
_, err := os.Stat(p)
if err == nil {
err = os.RemoveAll(p)
if err != nil {
return fmt.Errorf("remove old %v: %w", id, err)
}
}
err = os.Mkdir(p, 0o750)
if err != nil {
return fmt.Errorf("mkdir %s: %w", id.String(), err)
}
defer func() {
if err != nil {
os.RemoveAll(p)
}
}()
err = os.WriteFile(path.Join(p, "name"), []byte(name), 0o640)
if err != nil {
return fmt.Errorf("write name: %w", err)
}
err = os.WriteFile(path.Join(p, "type"), []byte(contentType), 0o640)
if err != nil {
return fmt.Errorf("write type: %w", err)
}
f, err := os.Create(path.Join(p, "data"))
if err != nil {
return fmt.Errorf("create data file: %w", err)
}
_, err = io.Copy(f, data)
if err != nil {
return fmt.Errorf("write data: %w", err)
}
return nil
}
func (fs *FS) RemoveUUID(id uuid.UUID) error {
return os.RemoveAll(path.Join(fs.Root, id.String()))
}
// OpenUUID opens the file with the given UUID.
func (fs *FS) OpenUUID(id uuid.UUID) (fs.File, error) {
f, err := os.Open(path.Join(fs.Root, id.String(), "data"))
if err != nil {
return nil, fmt.Errorf("open data: %w", err)
}
return File{File: f, fs: fs, id: id}, nil
}
// Open searches for and opens the file with the given name.
func (fs *FS) Open(name string) (fs.File, error) {
files, err := os.ReadDir(fs.Root)
if err != nil {
return nil, err
}
for _, v := range files {
id := v.Name()
entryName, err := os.ReadFile(path.Join(fs.Root, id, "name"))
if err != nil || string(entryName) != name {
continue
}
f, err := os.Open(path.Join(fs.Root, id, "data"))
if err != nil {
return nil, fmt.Errorf("open data: %w", err)
}
return File{File: f, fs: fs, id: uuid.MustParse(id)}, nil
}
return nil, errors.New("no such file")
}
// Check checks whether the file store is operable, ie. whether fs.Root exists
// and is a directory.
func (fs *FS) Check() error {
fi, err := os.Stat(fs.Root)
if err != nil {
return err
}
if !fi.IsDir() {
return errors.New("file store is not a directory")
}
return nil
}

52
web/file/fs/fs_test.go Normal file
View File

@ -0,0 +1,52 @@
package fs_test
import (
"io"
"os"
"strings"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"codeberg.org/genofire/golang-lib/web/file"
"codeberg.org/genofire/golang-lib/web/file/fs"
)
func TestOpenStat(t *testing.T) {
assert := assert.New(t)
var fs file.FS = &fs.FS{Root: "./testdata"}
assert.NoError(fs.Check())
f, err := fs.Open("glenda")
assert.NoError(err)
assert.NotNil(f)
fi, err := f.Stat()
assert.NoError(err)
assert.NotNil(fi)
assert.Equal(uuid.MustParse("d2750ced-4bdc-41d0-8c2f-5b9de44b84ef"), fi.(file.FileInfo).ID())
assert.Equal("text/plain", fi.(file.FileInfo).ContentType())
assert.Equal("glenda", fi.Name())
assert.Equal(int64(99), fi.Size())
}
func TestCreateOpenUUIDRead(t *testing.T) {
assert := assert.New(t)
var fs file.FS = &fs.FS{Root: "./testdata"}
assert.NoError(fs.Check())
err := fs.Store(uuid.MustParse("f9375ccb-ee09-4ecf-917e-b88725efcb68"), "$name", "text/plain", strings.NewReader("hello, world\n"))
assert.NoError(err)
f, err := fs.OpenUUID(uuid.MustParse("f9375ccb-ee09-4ecf-917e-b88725efcb68"))
assert.NoError(err)
assert.NotNil(f)
buf, err := io.ReadAll(f)
assert.NoError(err)
assert.Equal("hello, world\n", string(buf))
os.RemoveAll("./testdata/f9375ccb-ee09-4ecf-917e-b88725efcb68")
}

View File

@ -0,0 +1,8 @@
Small hand-drwawn Glenda by ems:
(\(\
¸". ..
( . .)
| ° ¡
¿ ;
c?".UJ"

View File

@ -0,0 +1 @@
glenda

View File

@ -0,0 +1 @@
text/plain

111
web/file/fs_test.go Normal file
View File

@ -0,0 +1,111 @@
package file_test
import (
"errors"
"fmt"
"io"
"io/fs"
"mime"
"mime/multipart"
"net/http"
"net/http/httptest"
"os"
"testing"
"github.com/google/uuid"
"github.com/stretchr/testify/assert"
"codeberg.org/genofire/golang-lib/web/file"
)
type TestFS struct {
assert *assert.Assertions
filename string
data string
contentType string
}
func (f TestFS) Store(id uuid.UUID, name, contentType string, data io.Reader) error {
f.assert.Equal(f.filename, name)
dat, err := io.ReadAll(data)
f.assert.NoError(err)
f.assert.Equal(f.data, string(dat))
contentType, _, err = mime.ParseMediaType(contentType)
f.assert.NoError(err)
f.assert.Equal(f.contentType, contentType)
return nil
}
func (f TestFS) RemoveUUID(id uuid.UUID) error {
return errors.New("TestFS.RemoveUUID called")
}
func (f TestFS) Open(name string) (fs.File, error) {
return nil, errors.New("TestFS.Open called")
}
func (f TestFS) OpenUUID(uuid.UUID) (fs.File, error) {
return nil, errors.New("TestFS.OpenUUID called")
}
func (f TestFS) Check() error { return nil }
func TestStoreFromHTTP(t *testing.T) {
assert := assert.New(t)
testfs := TestFS{
assert: assert,
filename: "cute-cat.png",
data: "content\nof file",
contentType: "text/plain",
}
r, w := io.Pipe()
m := multipart.NewWriter(w)
rq := httptest.NewRequest("PUT", "/", r)
rq.Header.Set("Content-Type", m.FormDataContentType())
go func() {
f, err := m.CreateFormFile("file", testfs.filename)
assert.NoError(err)
_, err = f.Write([]byte(testfs.data))
assert.NoError(err)
m.Close()
}()
assert.NoError(file.StoreFromHTTP(testfs, rq, "file"))
}
var fstore file.FS
func ExampleFS() {
// generate the UUID for the new file
id := uuid.New()
// store a file
{
f, _ := os.Open("glenda.png")
fstore.Store(id, "glenda.png", "image/png", f)
f.Close()
}
// copy back to a local file
{
r, _ := fstore.OpenUUID(id)
w, _ := os.Create("glenda.png")
io.Copy(w, r)
r.Close()
w.Close()
}
}
func ExampleStoreFromHTTP() {
http.HandleFunc("/upload", func(w http.ResponseWriter, r *http.Request) {
if err := file.StoreFromHTTP(fstore, r, "file"); err != nil {
w.Header().Set("content-type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(fmt.Sprintf(`{"message":"%v"}`, err)))
} else {
w.WriteHeader(http.StatusOK)
}
})
}

21
web/file/s3/file.go Normal file
View File

@ -0,0 +1,21 @@
package s3
import (
"io/fs"
"github.com/minio/minio-go/v7"
)
type File struct {
*minio.Object
}
func (f File) Stat() (fs.FileInfo, error) {
var fi FileInfo
var err error
fi.ObjectInfo, err = f.Object.Stat()
if err != nil {
return nil, err
}
return fi, nil
}

24
web/file/s3/fileinfo.go Normal file
View File

@ -0,0 +1,24 @@
package s3
import (
"io/fs"
"time"
"github.com/google/uuid"
"github.com/minio/minio-go/v7"
)
type FileInfo struct {
minio.ObjectInfo
}
func (fi FileInfo) Name() string { return fi.UserMetadata["filename"] }
func (fi FileInfo) Size() int64 { return fi.ObjectInfo.Size }
// TODO: try to map s3 permissions to these, somehow
func (fi FileInfo) Mode() fs.FileMode { return 0o640 }
func (fi FileInfo) ModTime() time.Time { return fi.LastModified }
func (fi FileInfo) IsDir() bool { return false }
func (fi FileInfo) Sys() interface{} { return fi.ObjectInfo }
func (fi FileInfo) ID() uuid.UUID { return uuid.MustParse(fi.Key) }
func (fi FileInfo) ContentType() string { return fi.ObjectInfo.ContentType }

87
web/file/s3/fs.go Normal file
View File

@ -0,0 +1,87 @@
/*
Package s3 implements a non-hierarchical file store using Amazon s3. A file
store uses a single bucket. Each file is an object with its UUID as the name.
The file name is stored in the user-defined object metadata x-amz-meta-filename.
*/
package s3
import (
"context"
"errors"
"io"
"io/fs"
"github.com/google/uuid"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
type FS struct {
client *minio.Client
bucket string
}
// New ``connects'' to an s3 endpoint and creates a file store using the
// specified bucket. The bucket is created if it doesn't exist.
func New(endpoint string, secure bool, id, secret, bucket, location string) (*FS, error) {
var fs FS
var err error
fs.client, err = minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(id, secret, ""),
Secure: secure,
})
if err != nil {
return nil, err
}
ctx := context.TODO()
err = fs.client.MakeBucket(ctx, bucket, minio.MakeBucketOptions{
Region: location,
})
if err != nil {
if exists, err := fs.client.BucketExists(ctx, bucket); err != nil || !exists {
return nil, err
}
}
fs.bucket = bucket
return &fs, nil
}
func (fs *FS) Store(id uuid.UUID, name, contentType string, data io.Reader) error {
ctx := context.TODO()
_, err := fs.client.PutObject(ctx, fs.bucket, id.String(), data, -1, minio.PutObjectOptions{
UserMetadata: map[string]string{
"filename": name,
},
ContentType: contentType,
})
return err
}
func (fs *FS) RemoveUUID(id uuid.UUID) error {
ctx := context.TODO()
return fs.client.RemoveObject(ctx, fs.bucket, id.String(), minio.RemoveObjectOptions{})
}
// TODO: implement
func (fs *FS) Open(name string) (fs.File, error) {
return nil, errors.New("not implemented")
}
func (fs *FS) OpenUUID(id uuid.UUID) (fs.File, error) {
ctx := context.TODO()
object, err := fs.client.GetObject(ctx, fs.bucket, id.String(), minio.GetObjectOptions{})
if err != nil {
return nil, err
}
return File{Object: object}, nil
}
// TODO: do some checking
func (fs *FS) Check() error {
return nil
}

25
web/file/s3/fs_test.go Normal file
View File

@ -0,0 +1,25 @@
package s3_test
import (
"testing"
"github.com/stretchr/testify/assert"
"codeberg.org/genofire/golang-lib/web/file"
"codeberg.org/genofire/golang-lib/web/file/s3"
)
// TODO: actually test, either using little dummies or using sth like play.min.io
func TestTypes(t *testing.T) {
assert := assert.New(t)
var fstore file.FS
fstore, err := s3.New("127.0.0.1", false, "", "", "", "")
_ = fstore
assert.Error(err)
}
func ExampleNew() {
s3.New("play.min.io", true, "Q3AM3UQ867SPQQA43P2F", "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG", "file-store", "")
}

2
web/file/testdata/createfs_fs.toml vendored Normal file
View File

@ -0,0 +1,2 @@
type = "fs"
root = "fs/testdata"

View File

@ -0,0 +1,2 @@
type = "fs"
root = ""

1
web/file/testdata/createfs_none.toml vendored Normal file
View File

@ -0,0 +1 @@
type = "notsupported"

7
web/file/testdata/createfs_s3.toml vendored Normal file
View File

@ -0,0 +1,7 @@
type = "s3"
endpoint = "play.min.io"
secure = true
id = "Q3AM3UQ867SPQQA43P2F"
secret = "zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG"
bucket = "file-store"
location = ""

View File

@ -1,61 +1,91 @@
/*
Package web implements common functionality for web APIs using Gin and Gorm.
Modules
Modules provide functionality for a web server. A module is a function executed
before starting a server, accessing the Service and the Gin Engine. Each Service
maintains a list of modules. When it runs, it executes all of its modules.
*/
package web
import (
"github.com/bdlm/log"
"net/http"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
"go.uber.org/zap"
// acme
"github.com/gin-gonic/autotls"
"golang.org/x/crypto/acme/autocert"
// internal
"codeberg.org/genofire/golang-lib/mailer"
"gorm.io/gorm"
)
// Service to store Configuration and Webserver wide objects
// (like DB Connection)
// A Service stores configuration of a server.
type Service struct {
// config
Listen string `toml:"listen"`
AccessLog bool `toml:"access_log"`
Webroot string `toml:"webroot"`
ACME struct {
Enable bool `toml:"enable"`
Domains []string `toml:"domains"`
Cache string `toml:"cache"`
} `toml:"acme"`
Listen string `config:"listen" toml:"listen"`
AccessLog bool `config:"access_log" toml:"access_log"`
WebrootIndexDisable bool `config:"webroot_index_disable" toml:"webroot_index_disable"`
Webroot string `config:"webroot" toml:"webroot"`
WebrootFS http.FileSystem `config:"-" toml:"-"`
ACME struct {
Enable bool `config:"enable" toml:"enable"`
Domains []string `config:"domains" toml:"domains"`
Cache string `config: "cache" toml:"cache"`
} `config:"acme" toml:"acme"`
Session struct {
Name string `toml:"name"`
Secret string `toml:"secret"`
} `toml:"session"`
Name string `config:"name" toml:"name"`
Secret string `config: "secret" toml:"secret"`
} `config:"session" toml:"session"`
// internal
DB *gorm.DB `toml:"-"`
DB *gorm.DB `config:"-" toml:"-"`
Mailer *mailer.Service `config:"-" toml:"-"`
log *zap.Logger
modules []ModuleRegisterFunc
}
// Run to startup all related web parts
// (e.g. configure the server, metrics, and finally bind routing)
func (config *Service) Run() error {
// SetLog - set new logger
func (s *Service) SetLog(l *zap.Logger) {
s.log = l
}
// Log - get current logger
func (s *Service) Log() *zap.Logger {
return s.log
}
// Run creates, configures, and runs a new gin.Engine using its registered
// modules.
func (s *Service) Run(log *zap.Logger) error {
s.log = log
gin.EnableJsonDecoderDisallowUnknownFields()
gin.SetMode(gin.ReleaseMode)
r := gin.New()
// catch crashed
r.Use(gin.Recovery())
if config.AccessLog {
if s.AccessLog {
r.Use(gin.Logger())
log.Debug("request logging enabled")
s.log.Debug("request logging enabled")
}
config.LoadSession(r)
config.Bind(r)
s.LoadSession(r)
s.Bind(r)
if config.ACME.Enable {
if config.Listen != "" {
log.Panic("For ACME / Let's Encrypt it is not possible to set `listen`")
if s.ACME.Enable {
if s.Listen != "" {
s.log.Panic("For ACME / Let's Encrypt it is not possible to set `listen`")
}
m := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist(config.ACME.Domains...),
Cache: autocert.DirCache(config.ACME.Cache),
HostPolicy: autocert.HostWhitelist(s.ACME.Domains...),
Cache: autocert.DirCache(s.ACME.Cache),
}
return autotls.RunWithManager(r, &m)
} else {
return r.Run(config.Listen)
}
return r.Run(s.Listen)
}

View File

@ -1 +1,37 @@
package web
import (
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"go.uber.org/zap"
)
var (
TestRunTLS = ""
)
func TestRun(t *testing.T) {
assert := assert.New(t)
s := &Service{AccessLog: true, Listen: "8.8.8.8:80"}
s.ModuleRegister(func(_ *gin.Engine, _ *Service) {})
// HTTP - failed
err := s.Run(zap.L())
assert.Error(err)
s.ACME.Enable = true
// acme with listen port - panic
assert.Panics(func() {
s.Run(zap.L())
})
if TestRunTLS == "false" {
return
}
s.Listen = ""
// httpS - failed
err = s.Run(zap.L())
assert.Error(err)
}

4
web/metrics/docs.go Normal file
View File

@ -0,0 +1,4 @@
/*
Package metrics implements for web the module to publish prometheus metrics
*/
package metrics

View File

@ -10,55 +10,58 @@ import (
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
// db metrics
gormPrometheus "gorm.io/plugin/prometheus"
"dev.sum7.eu/genofire/golang-lib/web"
"codeberg.org/genofire/golang-lib/web"
)
var (
NAMESPACE string = "service"
VERSION string = ""
UP func() bool = func() bool {
// NAMESPACE of prometheus metrics
NAMESPACE string = "service"
// VERSION in prometheus metrics
VERSION string = ""
// UP function for healthy check in prometheus metrics
UP func() bool = func() bool {
return true
}
)
func init() {
web.ModuleRegister(func(r *gin.Engine, ws *web.Service) {
r.Use(ginprom.PromMiddleware(&ginprom.PromOpts{
EndpointLabelMappingFn: func(c *gin.Context) string {
url := c.Request.URL.Path
for _, p := range c.Params {
url = strings.Replace(url, p.Value, ":"+p.Key, 1)
}
return url
},
// Register to WebService
func Register(r *gin.Engine, ws *web.Service) {
r.Use(ginprom.PromMiddleware(&ginprom.PromOpts{
EndpointLabelMappingFn: func(c *gin.Context) string {
url := c.Request.URL.Path
for _, p := range c.Params {
url = strings.Replace(url, p.Value, ":"+p.Key, 1)
}
return url
},
}))
prometheus.MustRegister(prometheus.NewGaugeFunc(
prometheus.GaugeOpts{
Namespace: NAMESPACE,
Name: "up",
Help: "is current version of service running",
ConstLabels: prometheus.Labels{"version": VERSION},
},
func() float64 {
if UP() {
return 1
}
return 0
},
))
if ws.DB != nil {
ws.DB.Use(gormPrometheus.New(gormPrometheus.Config{
DBName: NAMESPACE,
RefreshInterval: 15,
}))
prometheus.MustRegister(prometheus.NewGaugeFunc(
prometheus.GaugeOpts{
Namespace: NAMESPACE,
Name: "up",
Help: "is current version of service running",
ConstLabels: prometheus.Labels{"version": VERSION},
},
func() float64 {
if UP() {
return 1
}
return 0
},
))
}
if ws.DB != nil {
ws.DB.Use(gormPrometheus.New(gormPrometheus.Config{
DBName: NAMESPACE,
RefreshInterval: 15,
}))
}
r.GET("/metrics", ginprom.PromHandler(promhttp.Handler()))
})
r.GET("/metrics", ginprom.PromHandler(promhttp.Handler()))
}

View File

@ -6,14 +6,23 @@ import (
"github.com/stretchr/testify/assert"
"dev.sum7.eu/genofire/golang-lib/web/webtest"
"codeberg.org/genofire/golang-lib/web/webtest"
)
func TestMetricsLoaded(t *testing.T) {
assert := assert.New(t)
s := webtest.New(assert)
s, err := webtest.New(Register)
assert.NoError(err)
defer s.Close()
assert.NotNil(s)
// GET
s.Request(http.MethodGet, "/metrics", nil, http.StatusOK, nil)
err = s.Request(http.MethodGet, "/metrics", nil, http.StatusOK, nil)
assert.NoError(err)
UP = func() bool { return false }
// GET
err = s.Request(http.MethodGet, "/metrics", nil, http.StatusOK, nil)
assert.NoError(err)
}

View File

@ -1,26 +1,37 @@
package web
import (
"github.com/bdlm/log"
"github.com/gin-contrib/static"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
var (
modules []ModuleRegisterFunc
)
// A ModuleRegisterFunc is a module.
type ModuleRegisterFunc func(*gin.Engine, *Service)
func ModuleRegister(f ModuleRegisterFunc) {
modules = append(modules, f)
// ModuleRegister adds f to ws's list of modules.
func (ws *Service) ModuleRegister(f ModuleRegisterFunc) {
ws.modules = append(ws.modules, f)
}
// Bind executes all of ws's modules with r.
func (ws *Service) Bind(r *gin.Engine) {
for _, f := range modules {
for _, f := range ws.modules {
f(r, ws)
}
log.Infof("loaded %d modules", len(modules))
r.Use(static.Serve("/", static.LocalFile(ws.Webroot, false)))
ws.log.Info("bind modules", zap.Int("count", len(ws.modules)))
if ws.Webroot != "" {
ws.WebrootFS = static.LocalFile(ws.Webroot, false)
}
r.Use(func(c *gin.Context) {
if !ws.WebrootIndexDisable {
_, err := ws.WebrootFS.Open(c.Request.URL.Path)
if err != nil {
c.FileFromFS("/", ws.WebrootFS)
return
}
}
c.FileFromFS(c.Request.URL.Path, ws.WebrootFS)
})
}

View File

@ -1,13 +1,21 @@
package web
import (
"bytes"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
"time"
)
// JSONRequest issues a GET request to the specified URL and reads the returned
// JSON into value. See json.Unmarshal for the rules for converting JSON into a
// value.
func JSONRequest(url string, value interface{}) error {
var netClient = &http.Client{
netClient := &http.Client{
Timeout: time.Second * 20,
}
@ -17,8 +25,46 @@ func JSONRequest(url string, value interface{}) error {
}
err = json.NewDecoder(resp.Body).Decode(&value)
resp.Body.Close()
if err != nil {
return err
}
return nil
}
// NewRequestWithFile Create a Request with file as body
func NewRequestWithFile(url, filename string) (*http.Request, error) {
buf := bytes.NewBuffer(nil)
bodyWriter := multipart.NewWriter(buf)
// We need to truncate the input filename, as the server might be stupid and take the input
// filename verbatim. Then, he will have directory parts which do not exist on the server.
fileWriter, err := bodyWriter.CreateFormFile("file", filepath.Base(filename))
if err != nil {
return nil, err
}
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
if _, err := io.Copy(fileWriter, file); err != nil {
return nil, err
}
// We have all the data written to the bodyWriter.
// Now we can infer the content type
contentType := bodyWriter.FormDataContentType()
// This is mandatory as it flushes the buffer.
bodyWriter.Close()
req, err := http.NewRequest(http.MethodPost, url, buf)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", contentType)
return req, nil
}

26
web/request_test.go Normal file
View File

@ -0,0 +1,26 @@
package web
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestJSONRequest(t *testing.T) {
assert := assert.New(t)
data := struct {
IP string `json:"query"`
}{}
err := JSONRequest("http://ip-api.com/json/?fields=query", &data)
assert.NoError(err)
assert.NotEqual("", data.IP)
wrongData := ""
err = JSONRequest("http://ip-api.com/json/?fields=query", &wrongData)
assert.Error(err)
wrongData = ""
err = JSONRequest("http://no.example.org/", &wrongData)
assert.Error(err)
}

45
web/response.go Normal file
View File

@ -0,0 +1,45 @@
package web
import (
"github.com/gin-gonic/gin"
)
// MIME type strings.
const (
ContentTypeJSON = "application/json"
ContentTypeJS = "application/javascript"
ContentTypeXML = "text/xml"
ContentTypeYAML = "text/yaml"
ContentTypeHTML = "text/html"
)
// Response sends an HTTP response.
//
// statusCode is the respone's status.
//
// If the request's Content-Type is JavaScript, JSON, YAML, or XML, it returns
// data serialized as JSONP, JSON, YAML, or XML, respectively. If the
// Content-Type is HTML, it returns the HTML template templateName rendered with
// data.
func Response(ctx *gin.Context, statusCode int, data interface{}, templateName string) {
switch ctx.ContentType() {
case ContentTypeJS:
ctx.JSONP(statusCode, data)
return
case ContentTypeJSON:
ctx.JSON(statusCode, data)
return
case ContentTypeYAML:
ctx.YAML(statusCode, data)
return
case ContentTypeXML:
ctx.XML(statusCode, data)
return
case ContentTypeHTML:
ctx.HTML(statusCode, templateName, data)
return
default:
ctx.JSON(statusCode, data)
return
}
}

View File

@ -6,7 +6,8 @@ import (
"github.com/gin-gonic/gin"
)
func (config *Service) LoadSession(r *gin.Engine) {
store := cookie.NewStore([]byte(config.Session.Secret))
r.Use(sessions.Sessions(config.Session.Name, store))
// LoadSession starts session handling for s.
func (s *Service) LoadSession(r *gin.Engine) {
store := cookie.NewStore([]byte(s.Session.Secret))
r.Use(sessions.Sessions(s.Session.Name, store))
}

4
web/webtest/docs.go Normal file
View File

@ -0,0 +1,4 @@
/*
Package webtest implements an easy way to write test for web modules
*/
package webtest

View File

@ -10,114 +10,194 @@ import (
"strings"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"go.uber.org/zap"
"dev.sum7.eu/genofire/golang-lib/database"
"dev.sum7.eu/genofire/golang-lib/web"
"codeberg.org/genofire/golang-lib/database"
"codeberg.org/genofire/golang-lib/mailer"
"codeberg.org/genofire/golang-lib/web"
)
type testServer struct {
db *database.Database
var (
// DBConnection - url to database on setting up default WebService for webtest
DBConnection = "postgresql://root:root@localhost:26257/defaultdb?sslmode=disable"
)
// Option to configure TestServer
type Option struct {
ModuleLoader web.ModuleRegisterFunc
Database bool
DBReRun bool
DBSetup func(db *database.Database)
Mailer bool
Logger *zap.Logger
}
func (option Option) log() *zap.Logger {
if option.Logger != nil {
return option.Logger
}
return zap.L()
}
// TestServer - to run it without listen an server
type TestServer struct {
DB *database.Database
Mails chan *mailer.TestingMail
Close func()
gin *gin.Engine
ws *web.Service
assert *assert.Assertions
WS *web.Service
lastCookies []*http.Cookie
}
// Login Request format (maybe just internal usage)
type Login struct {
Username string `json:"username"`
Password string `json:"password"`
}
func New(assert *assert.Assertions) *testServer {
// New starts WebService for testing
func New(modules web.ModuleRegisterFunc) (*TestServer, error) {
return Option{ModuleLoader: modules}.New()
}
// NewWithDBSetup allows to reconfigure before ReRun the database - e.g. for adding Migration-Steps
func NewWithDBSetup(modules web.ModuleRegisterFunc, dbCall func(db *database.Database)) (*TestServer, error) {
return Option{
Database: true,
DBReRun: true,
DBSetup: dbCall,
ModuleLoader: modules,
}.New()
}
// New allows to configure WebService for testing
func (option Option) New() (*TestServer, error) {
log := option.log()
ws := &web.Service{}
ws.SetLog(log)
ws.Session.Name = "mysession"
ws.Session.Secret = "hidden"
ts := &TestServer{
WS: ws,
Close: func() {},
}
// db setup
dbConfig := database.Database{
Connection: "user=root password=root dbname=defaultdb host=localhost port=26257 sslmode=disable",
Testdata: true,
Debug: false,
LogLevel: 0,
if option.Database {
ts.DB = &database.Database{
Testdata: true,
Debug: false,
LogLevel: 0,
}
ts.DB.Connection.URI = DBConnection
if option.DBSetup != nil {
option.DBSetup(ts.DB)
}
var err error
if option.DBReRun {
err = ts.DB.ReRun()
} else {
err = ts.DB.Run()
}
if err != nil && err != database.ErrNothingToMigrate {
return nil, err
}
if ts.DB.DB == nil {
return nil, database.ErrNotConnected
}
ws.DB = ts.DB.DB
}
err := dbConfig.Run()
if err != nil && err != database.ErrNothingToMigrate {
fmt.Println(err.Error())
assert.Nil(err)
if option.Mailer {
mock, mail := mailer.NewFakeServer(log)
if err := mail.Setup(); err != nil {
return nil, err
}
ws.Mailer = mail
ts.Mails = mock.Mails
ts.Close = mock.Close
}
assert.NotNil(dbConfig.DB)
// api setup
gin.EnableJsonDecoderDisallowUnknownFields()
gin.SetMode(gin.TestMode)
ws := &web.Service{
DB: dbConfig.DB,
}
ws.Session.Name = "mysession"
ws.Session.Secret = "hidden"
ws.ModuleRegister(option.ModuleLoader)
r := gin.Default()
ws.LoadSession(r)
ws.Bind(r)
return &testServer{
db: &dbConfig,
gin: r,
ws: ws,
assert: assert,
}
ts.gin = r
return ts, nil
}
func (this *testServer) DatabaseMigration(f func(db *database.Database)) {
f(this.db)
this.db.MigrateTestdata()
// DatabaseForget to run a test without a database
func (s *TestServer) DatabaseForget() {
s.WS.DB = nil
s.DB = nil
}
func (this *testServer) Request(method, url string, body interface{}, expectCode int, jsonObj interface{}) {
// Request sends a request to webtest WebService
func (s *TestServer) Request(method, url string, body interface{}, expectCode int, jsonObj interface{}) error {
var jsonBody io.Reader
if body != nil {
if strBody, ok := body.(string); ok {
jsonBody = strings.NewReader(strBody)
} else {
jsonBodyArray, err := json.Marshal(body)
this.assert.Nil(err, "no request created")
if err != nil {
return err
}
jsonBody = bytes.NewBuffer(jsonBodyArray)
}
}
req, err := http.NewRequest(method, url, jsonBody)
this.assert.Nil(err, "no request created")
if len(this.lastCookies) > 0 {
for _, c := range this.lastCookies {
if err != nil {
return err
}
if len(s.lastCookies) > 0 {
for _, c := range s.lastCookies {
req.AddCookie(c)
}
}
w := httptest.NewRecorder()
this.gin.ServeHTTP(w, req)
s.gin.ServeHTTP(w, req)
// valid statusCode
this.assert.Equal(expectCode, w.Code, "expected http status code")
if expectCode != w.Code {
fmt.Printf("wrong status code, body:%v\n", w.Body)
return
return fmt.Errorf("wrong status code, body: %v", w.Body)
}
if jsonObj != nil {
// fetch JSON
err = json.NewDecoder(w.Body).Decode(jsonObj)
this.assert.Nil(err, "decode json")
if err != nil {
return err
}
}
result := w.Result()
if result != nil {
cookies := result.Cookies()
if len(cookies) > 0 {
this.lastCookies = cookies
s.lastCookies = cookies
}
}
return nil
}
func (this *testServer) Login(login Login) {
// Login to API by send request
func (s *TestServer) Login(login Login) error {
// POST: correct login
this.Request(http.MethodPost, "/api/v1/auth/login", &login, http.StatusOK, nil)
return s.Request(http.MethodPost, "/api/v1/auth/login", &login, http.StatusOK, nil)
}
func (this *testServer) TestLogin() {
this.Login(Login{
// TestLogin to API by default login data
func (s *TestServer) TestLogin() error {
return s.Login(Login{
Username: "admin",
Password: "CHANGEME",
})

View File

@ -1,7 +1,10 @@
package ws
const (
// BodyError Message Body map typ for errors
BodyError = "error"
BodySet = "set"
BodyGet = "get"
// BodySet Message Body map typ for set values
BodySet = "set"
// BodyGet Message Body map typ for get values
BodyGet = "get"
)

View File

@ -6,15 +6,18 @@ import (
"sync"
"time"
"github.com/bdlm/log"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"go.uber.org/zap"
"golang.org/x/time/rate"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
)
// WebsocketEndpoint to handle Request
type WebsocketEndpoint struct {
log *zap.Logger
// publishLimiter controls the rate limit applied to the publish endpoint.
//
// Defaults to one publish every 100ms with a burst of 8.
@ -24,79 +27,105 @@ type WebsocketEndpoint struct {
Subscribers map[*Subscriber]struct{}
// Message Handler
handlers map[string]MessageHandleFunc
handlers map[string]MessageHandleFunc
// DefaultMessageHandler if no other handler for MessageType found
DefaultMessageHandler MessageHandleFunc
OnOpen SubscriberEventFunc
OnClose SubscriberEventFunc
// Run Function on open connection by subscriper
OnOpen SubscriberEventFunc
// Run Function on close connection to subscriper
OnClose SubscriberEventFunc
}
// MessageHandleFunc for handling messages
type MessageHandleFunc func(ctx context.Context, msg *Message)
// Subscriber of websocket endpoint
type Subscriber struct {
out chan *Message
closeSlow func()
}
// SubscriberEventFunc for handling connection state of Subsriber
type SubscriberEventFunc func(s *Subscriber, msg chan<- *Message)
// Message on websocket
type Message struct {
Type string `json:"type"`
ID *uuid.UUID `json:"id,omitempty"`
ReplyID *uuid.UUID `json:"reply_id,omitempty"`
Body map[string]interface{} `json:"body"`
Reply chan<- *Message `json:"-"`
Subscriber *Subscriber `json:"-"`
}
func NewEndpoint() *WebsocketEndpoint {
// Reply to Message
func (m *Message) Reply(msg *Message) {
if m == nil || m.Subscriber == nil {
return
}
if m.ID != nil {
msg.ReplyID = m.ID
if msg.ID == nil {
id := uuid.New()
msg.ID = &id
}
}
m.Subscriber.out <- msg
}
// MessageHandleFunc for handling messages
type MessageHandleFunc func(ctx context.Context, msg *Message)
// NewEndpoint - create an empty websocket
func NewEndpoint(log *zap.Logger) *WebsocketEndpoint {
return &WebsocketEndpoint{
log: log,
publishLimiter: rate.NewLimiter(rate.Every(time.Millisecond*100), 8),
Subscribers: make(map[*Subscriber]struct{}),
handlers: make(map[string]MessageHandleFunc),
}
}
func (this *WebsocketEndpoint) Handler(ctx *gin.Context) {
c, err := websocket.Accept(ctx.Writer, ctx.Request, &websocket.AcceptOptions{
InsecureSkipVerify: true,
})
// Broadcast Message to all subscriber (exclude sender of Message)
func (we *WebsocketEndpoint) Broadcast(msg *Message) {
we.subscribersMu.Lock()
defer we.subscribersMu.Unlock()
we.publishLimiter.Wait(context.Background())
for s := range we.Subscribers {
if s == msg.Subscriber {
continue
}
select {
case s.out <- msg:
default:
go s.closeSlow()
}
}
}
// AddMessageHandler - add websocket message handler
func (we *WebsocketEndpoint) AddMessageHandler(typ string, f MessageHandleFunc) {
we.handlers[typ] = f
}
// Handler - to register in gin webservice
func (we *WebsocketEndpoint) Handler(ctx *gin.Context) {
c, err := websocket.Accept(ctx.Writer, ctx.Request, nil)
if err != nil {
ctx.JSON(http.StatusBadRequest, false)
return
}
defer c.Close(websocket.StatusInternalError, "")
err = this.addSubscriber(ctx, c)
err = we.addSubscriber(ctx, c)
if websocket.CloseStatus(err) == websocket.StatusNormalClosure ||
websocket.CloseStatus(err) == websocket.StatusGoingAway {
return
}
log.Errorf("subscriber stopped: %s", err)
we.log.Error("subscriber stopped", zap.Error(err))
}
func (this *WebsocketEndpoint) AddMessageHandler(typ string, f MessageHandleFunc) {
this.handlers[typ] = f
}
type Subscriber struct {
out chan *Message
closeSlow func()
}
func (this *WebsocketEndpoint) readWorker(ctx context.Context, c *websocket.Conn, s *Subscriber) error {
for {
var msg Message
err := wsjson.Read(ctx, c, &msg)
if err != nil {
return err
}
log.WithField("type", msg.Type).Debug("receive")
msg.Subscriber = s
msg.Reply = s.out
if handler, ok := this.handlers[msg.Type]; ok {
handler(ctx, &msg)
} else if this.DefaultMessageHandler != nil {
this.DefaultMessageHandler(ctx, &msg)
}
}
}
func (this *WebsocketEndpoint) addSubscriber(ctxGin *gin.Context, c *websocket.Conn) error {
// addSubscriber and startup of websocket endpoint
func (we *WebsocketEndpoint) addSubscriber(ctxGin *gin.Context, c *websocket.Conn) error {
s := &Subscriber{
out: make(chan *Message, 10),
closeSlow: func() {
@ -104,34 +133,35 @@ func (this *WebsocketEndpoint) addSubscriber(ctxGin *gin.Context, c *websocket.C
},
}
this.subscribersMu.Lock()
this.Subscribers[s] = struct{}{}
this.subscribersMu.Unlock()
we.subscribersMu.Lock()
we.Subscribers[s] = struct{}{}
we.subscribersMu.Unlock()
defer func() {
this.subscribersMu.Lock()
delete(this.Subscribers, s)
this.subscribersMu.Unlock()
if this.OnClose != nil {
this.OnClose(s, s.out)
we.subscribersMu.Lock()
delete(we.Subscribers, s)
we.subscribersMu.Unlock()
if we.OnClose != nil {
we.OnClose(s, s.out)
}
log.Debug("websocket closed")
we.log.Debug("websocket closed")
}()
if this.OnOpen != nil {
this.OnOpen(s, s.out)
if we.OnOpen != nil {
we.OnOpen(s, s.out)
}
ctx := ctxGin.Request.Context()
go func() {
err := this.readWorker(ctx, c, s)
err := we.readWorker(ctx, c, s)
if websocket.CloseStatus(err) == websocket.StatusNormalClosure ||
websocket.CloseStatus(err) == websocket.StatusGoingAway {
return
}
log.Errorf("websocket reading error: %s", err)
we.log.Error("websocket reading error", zap.Error(err))
}()
log.Debug("websocket started")
we.log.Debug("websocket started")
for {
select {
@ -146,27 +176,28 @@ func (this *WebsocketEndpoint) addSubscriber(ctxGin *gin.Context, c *websocket.C
}
}
// readWorker of subscriber
func (we *WebsocketEndpoint) readWorker(ctx context.Context, c *websocket.Conn, s *Subscriber) error {
for {
var msg Message
err := wsjson.Read(ctx, c, &msg)
if err != nil {
return err
}
we.log.Debug("receive", zap.String("type", msg.Type))
msg.Subscriber = s
if handler, ok := we.handlers[msg.Type]; ok {
handler(ctx, &msg)
} else if we.DefaultMessageHandler != nil {
we.DefaultMessageHandler(ctx, &msg)
}
}
}
// writeTimeout send message to subscriber with timeout
func writeTimeout(ctx context.Context, timeout time.Duration, c *websocket.Conn, msg *Message) error {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
return wsjson.Write(ctx, c, msg)
}
func (this *WebsocketEndpoint) Broadcast(msg *Message) {
this.subscribersMu.Lock()
defer this.subscribersMu.Unlock()
this.publishLimiter.Wait(context.Background())
for s := range this.Subscribers {
if s == msg.Subscriber {
continue
}
select {
case s.out <- msg:
default:
go s.closeSlow()
}
}
}