snapshot of https://github.com/traggo/server.git (master, 2026-09-16; blobs > 131072B omitted)
Some checks failed
build / build (push) Failing after 3s
Some checks failed
build / build (push) Failing after 3s
This commit is contained in:
4
.dockerignore
Normal file
4
.dockerignore
Normal file
@@ -0,0 +1,4 @@
|
||||
/docker/Dockerfile.dev
|
||||
/ui/node_modules/
|
||||
.idea/
|
||||
build/
|
||||
3
.env.development
Normal file
3
.env.development
Normal file
@@ -0,0 +1,3 @@
|
||||
TRAGGO_LOG_LEVEL=debug
|
||||
TRAGGO_DATABASE_DIALECT=sqlite3
|
||||
TRAGGO_DATABASE_CONNECTION=file::memory:?mode=memory&cache=shared
|
||||
19
.env.sample
Normal file
19
.env.sample
Normal file
@@ -0,0 +1,19 @@
|
||||
# the port the http server should use
|
||||
# TRAGGO_PORT=3030
|
||||
|
||||
# default username and password
|
||||
# TRAGGO_DEFAULT_USER_NAME=admin
|
||||
# TRAGGO_DEFAULT_USER_PASS=admin
|
||||
|
||||
# bcrypt password strength (higher = more secure but also slower)
|
||||
# TRAGGO_PASS_STRENGTH=10
|
||||
|
||||
# how verbose traggo/server should log (must be one of: debug, info, warn, error, fatal, panic)
|
||||
# TRAGGO_LOG_LEVEL=info
|
||||
|
||||
# the database dialect (must be one of: sqlite3)
|
||||
# TRAGGO_DATABASE_DIALECT=sqlite3
|
||||
|
||||
# the database connection string, differs depending on the dialect
|
||||
# sqlite3: path/to/database.db
|
||||
# TRAGGO_DATABASE_CONNECTION=data/traggo.db
|
||||
12
.github/FUNDING.yml
vendored
Normal file
12
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,12 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: jmattheis
|
||||
patreon: # Replace with a single Patreon username
|
||||
open_collective: # Replace with a single Open Collective username
|
||||
ko_fi: # Replace with a single Ko-fi username
|
||||
tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
|
||||
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
|
||||
liberapay: # Replace with a single Liberapay username
|
||||
issuehunt: # Replace with a single IssueHunt username
|
||||
otechie: # Replace with a single Otechie username
|
||||
custom: https://jmattheis.de/donate
|
||||
27
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
27
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@@ -0,0 +1,27 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: a:bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**To Reproduce**
|
||||
Steps to reproduce the behavior:
|
||||
1. Go to '...'
|
||||
2. Click on '....'
|
||||
3. Scroll down to '....'
|
||||
4. See error
|
||||
|
||||
**Expected behavior**
|
||||
A clear and concise description of what you expected to happen.
|
||||
|
||||
**Screenshots**
|
||||
If applicable, add screenshots to help explain your problem.
|
||||
|
||||
**Additional context**
|
||||
Add any other context about the problem here. (Include configs for traggo and reverse proxies like nginx)
|
||||
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest an idea for this project
|
||||
title: ''
|
||||
labels: a:feature
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
||||
|
||||
**Describe the solution you'd like**
|
||||
A clear and concise description of what you want to happen.
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
A clear and concise description of any alternative solutions or features you've considered.
|
||||
|
||||
**Additional context**
|
||||
Add any other context or screenshots about the feature request here.
|
||||
29
.github/ISSUE_TEMPLATE/questions.md
vendored
Normal file
29
.github/ISSUE_TEMPLATE/questions.md
vendored
Normal file
@@ -0,0 +1,29 @@
|
||||
---
|
||||
name: Questions
|
||||
about: Having difficulties with traggo?
|
||||
title: ''
|
||||
labels: question
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
<!--
|
||||
Official documentation - https://traggo.net/
|
||||
-->
|
||||
|
||||
**Have you read the documentation?**
|
||||
- [ ] Yes, but it does not include related information regarding my question.
|
||||
- [ ] Yes, but the steps described in the documentation do not work on my machine.
|
||||
- [ ] Yes, but I am having difficulty understanding it and want clarification.
|
||||
|
||||
**You are setting up traggo in**
|
||||
- [ ] Docker
|
||||
- [ ] Linux native platform
|
||||
- [ ] Windows native platform
|
||||
|
||||
**Describe your problem**
|
||||
A clear and concise description of what the question is.
|
||||
|
||||
**Any errors, logs, or other information that might help us identify your problem**
|
||||
|
||||
Ex: `docker-compose.yml`, `nginx.conf`, browser requests, etc.
|
||||
BIN
.github/traggo_calendar.png
vendored
Normal file
BIN
.github/traggo_calendar.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 132 KiB |
BIN
.github/traggo_dashboard.png
vendored
Normal file
BIN
.github/traggo_dashboard.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 136 KiB |
BIN
.github/traggo_list.png
vendored
Normal file
BIN
.github/traggo_list.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 103 KiB |
30
.github/workflows/build.yml
vendored
Normal file
30
.github/workflows/build.yml
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
name: build
|
||||
on: [push, pull_request]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: 1.25.x
|
||||
- uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '20'
|
||||
- uses: actions/checkout@v5
|
||||
- run: make download-tools
|
||||
- run: make install
|
||||
- run: make generate
|
||||
- run: make build-js
|
||||
env:
|
||||
NODE_OPTIONS: --openssl-legacy-provider
|
||||
- run: make lint
|
||||
- run: make test
|
||||
- if: startsWith(github.ref, 'refs/tags/v')
|
||||
run: echo "$DOCKER_PASS" | docker login --username "traggoci" --password-stdin
|
||||
env:
|
||||
DOCKER_PASS: ${{ secrets.DOCKER_PASS }}
|
||||
- if: startsWith(github.ref, 'refs/tags/v')
|
||||
run: make release
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
14
.gitignore
vendored
Normal file
14
.gitignore
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
.idea
|
||||
dist/
|
||||
build
|
||||
vendor
|
||||
coverage.txt
|
||||
generated
|
||||
.env.development.local
|
||||
.env
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
node_modules
|
||||
__generated__
|
||||
*-packr.go
|
||||
96
.goreleaser.yml
Normal file
96
.goreleaser.yml
Normal file
@@ -0,0 +1,96 @@
|
||||
version: 2
|
||||
project_name: traggo
|
||||
builds:
|
||||
- id: linux-amd64
|
||||
main: ./
|
||||
goos: [linux]
|
||||
goarch: ['amd64']
|
||||
flags: ['-tags="netgo osusergo sqlite_omit_load_extension"']
|
||||
ldflags: ["-s","-w","-linkmode","external","-extldflags","-static","-X main.BuildDate={{.Date}}","-X main.BuildMode=prod","-X main.BuildCommit={{.Commit}}","-X main.BuildVersion={{.Version}}"]
|
||||
- id: linux-armhf
|
||||
main: ./
|
||||
goos: [linux]
|
||||
goarch: [arm]
|
||||
goarm: [7]
|
||||
env: [CC=arm-linux-gnueabihf-gcc, CXX=arm-linux-gnueabihf-g++]
|
||||
flags: ['-tags="netgo osusergo sqlite_omit_load_extension"']
|
||||
ldflags: ["-s","-w","-linkmode","external","-extldflags","-static","-X main.BuildDate={{.Date}}","-X main.BuildMode=prod","-X main.BuildCommit={{.Commit}}","-X main.BuildVersion={{.Version}}"]
|
||||
- id: linux-arm64
|
||||
main: ./
|
||||
goos: [linux]
|
||||
goarch: [arm64]
|
||||
env: [CC=aarch64-linux-gnu-gcc, CXX=aarch64-linux-gnu-g++]
|
||||
flags: ['-tags="netgo osusergo sqlite_omit_load_extension"']
|
||||
ldflags: ["-s","-w","-linkmode","external","-extldflags","-static","-X main.BuildDate={{.Date}}","-X main.BuildMode=prod","-X main.BuildCommit={{.Commit}}","-X main.BuildVersion={{.Version}}"]
|
||||
- id: windows-amd64
|
||||
main: ./
|
||||
goos: [windows]
|
||||
goarch: [amd64]
|
||||
env: [CC=x86_64-w64-mingw32-gcc, CXX=x86_64-w64-mingw32-gcc]
|
||||
flags: ['-tags="netgo osusergo sqlite_omit_load_extension"']
|
||||
ldflags: ["-s","-w","-linkmode","external","-extldflags","-static","-X main.BuildDate={{.Date}}","-X main.BuildMode=prod","-X main.BuildCommit={{.Commit}}","-X main.BuildVersion={{.Version}}"]
|
||||
archives:
|
||||
- files:
|
||||
- LICENSE
|
||||
- README.md
|
||||
- .env.sample
|
||||
name_template: '{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{- if eq .Arch "386" }}i386{{- else }}{{ .Arch }}{{ end }}{{ if .Arm }}v{{ .Arm }}{{ end }}'
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
formats: [zip]
|
||||
checksum:
|
||||
disable: true
|
||||
changelog:
|
||||
disable: true
|
||||
dockers:
|
||||
- use: buildx
|
||||
goos: linux
|
||||
goarch: amd64
|
||||
image_templates:
|
||||
- "traggo/server:amd64-latest"
|
||||
- "traggo/server:amd64-{{ .RawVersion }}"
|
||||
dockerfile: docker/Dockerfile
|
||||
build_flag_templates:
|
||||
- "--platform=linux/amd64"
|
||||
- "--label=org.opencontainers.image.created={{.Date}}"
|
||||
- "--label=org.opencontainers.image.title={{.ProjectName}}"
|
||||
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
|
||||
- "--label=org.opencontainers.image.version={{.Version}}"
|
||||
- use: buildx
|
||||
goos: linux
|
||||
goarch: arm64
|
||||
image_templates:
|
||||
- "traggo/server:arm64-latest"
|
||||
- "traggo/server:arm64-{{ .RawVersion }}"
|
||||
dockerfile: docker/Dockerfile
|
||||
build_flag_templates:
|
||||
- "--platform=linux/arm64"
|
||||
- "--label=org.opencontainers.image.created={{.Date}}"
|
||||
- "--label=org.opencontainers.image.title={{.ProjectName}}"
|
||||
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
|
||||
- "--label=org.opencontainers.image.version={{.Version}}"
|
||||
- use: buildx
|
||||
goos: linux
|
||||
goarch: arm
|
||||
goarm: 7
|
||||
image_templates:
|
||||
- "traggo/server:armv7-latest"
|
||||
- "traggo/server:armv7-{{ .RawVersion }}"
|
||||
dockerfile: docker/Dockerfile
|
||||
build_flag_templates:
|
||||
- "--platform=linux/arm/v7"
|
||||
- "--label=org.opencontainers.image.created={{.Date}}"
|
||||
- "--label=org.opencontainers.image.title={{.ProjectName}}"
|
||||
- "--label=org.opencontainers.image.revision={{.FullCommit}}"
|
||||
- "--label=org.opencontainers.image.version={{.Version}}"
|
||||
docker_manifests:
|
||||
- name_template: "traggo/server:latest"
|
||||
image_templates:
|
||||
- "traggo/server:amd64-latest"
|
||||
- "traggo/server:arm64-latest"
|
||||
- "traggo/server:armv7-latest"
|
||||
- name_template: "traggo/server:{{ .RawVersion }}"
|
||||
image_templates:
|
||||
- "traggo/server:amd64-{{ .RawVersion }}"
|
||||
- "traggo/server:arm64-{{ .RawVersion }}"
|
||||
- "traggo/server:armv7-{{ .RawVersion }}"
|
||||
76
CODE_OF_CONDUCT.md
Normal file
76
CODE_OF_CONDUCT.md
Normal file
@@ -0,0 +1,76 @@
|
||||
# Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
In the interest of fostering an open and welcoming environment, we as
|
||||
contributors and maintainers pledge to making participation in our project and
|
||||
our community a harassment-free experience for everyone, regardless of age, body
|
||||
size, disability, ethnicity, sex characteristics, gender identity and expression,
|
||||
level of experience, education, socio-economic status, nationality, personal
|
||||
appearance, race, religion, or sexual identity and orientation.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
||||
Project maintainers are responsible for clarifying the standards of acceptable
|
||||
behavior and are expected to take appropriate and fair corrective action in
|
||||
response to any instances of unacceptable behavior.
|
||||
|
||||
Project maintainers have the right and responsibility to remove, edit, or
|
||||
reject comments, commits, code, wiki edits, issues, and other contributions
|
||||
that are not aligned to this Code of Conduct, or to ban temporarily or
|
||||
permanently any contributor for other behaviors that they deem inappropriate,
|
||||
threatening, offensive, or harmful.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies both within project spaces and in public spaces
|
||||
when an individual is representing the project or its community. Examples of
|
||||
representing a project or community include using an official project e-mail
|
||||
address, posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event. Representation of a project may be
|
||||
further defined and clarified by project maintainers.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported by contacting the project team at traggo@protonmail.com. All
|
||||
complaints will be reviewed and investigated and will result in a response that
|
||||
is deemed necessary and appropriate to the circumstances. The project team is
|
||||
obligated to maintain confidentiality with regard to the reporter of an incident.
|
||||
Further details of specific enforcement policies may be posted separately.
|
||||
|
||||
Project maintainers who do not follow or enforce the Code of Conduct in good
|
||||
faith may face temporary or permanent repercussions as determined by other
|
||||
members of the project's leadership.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
|
||||
available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
||||
|
||||
For answers to common questions about this code of conduct, see
|
||||
https://www.contributor-covenant.org/faq
|
||||
674
LICENSE
Normal file
674
LICENSE
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
94
Makefile
Normal file
94
Makefile
Normal file
@@ -0,0 +1,94 @@
|
||||
TAGS=netgo osusergo sqlite_omit_load_extension
|
||||
VERSION=$(shell git describe --tags --abbrev=0 | cut -c 2-)
|
||||
COMMIT=$(shell git rev-parse --verify HEAD)
|
||||
DATE=$(shell date -u +"%Y-%m-%dT%H:%M:%SZ")
|
||||
LD_FLAGS=-s -w -linkmode external -extldflags "-static" -X main.BuildDate=$(DATE) -X main.BuildMode=prod -X main.BuildCommit=$(COMMIT) -X main.BuildVersion=$(VERSION)
|
||||
BUILD_DIR=./build
|
||||
PWD=$(shell pwd)
|
||||
|
||||
license-dir:
|
||||
mkdir -p build/license || true
|
||||
|
||||
download-tools:
|
||||
go install golang.org/x/tools/cmd/goimports@v0.1.10
|
||||
go install github.com/99designs/gqlgen@v0.17.85
|
||||
|
||||
generate-go:
|
||||
gqlgen
|
||||
|
||||
generate-js:
|
||||
(cd ui && yarn generate)
|
||||
|
||||
generate: generate-go generate-js
|
||||
|
||||
lint-go:
|
||||
go vet ./...
|
||||
goimports -l $(shell find . -type f -name '*.go' -not -path "./vendor/*")
|
||||
|
||||
lint-js:
|
||||
(cd ui && yarn format:check)
|
||||
(cd ui && yarn lint:check)
|
||||
|
||||
lint: lint-go lint-js
|
||||
|
||||
format-go:
|
||||
goimports -w $(shell find . -type f -name '*.go' -not -path "./vendor/*")
|
||||
|
||||
format-js:
|
||||
(cd ui && yarn format)
|
||||
|
||||
format: format-go format-js
|
||||
|
||||
test-go:
|
||||
go test --race -coverprofile=coverage.txt -covermode=atomic ./...
|
||||
|
||||
test-js:
|
||||
(cd ui && CI=true yarn test)
|
||||
|
||||
test: test-go test-js
|
||||
|
||||
install-go:
|
||||
go mod download
|
||||
|
||||
install-js:
|
||||
(cd ui && yarn)
|
||||
|
||||
build-js:
|
||||
(cd ui && yarn build)
|
||||
|
||||
pre-build: build-js
|
||||
|
||||
build-bin-local: pre-build
|
||||
CGO_ENABLED=1 go build -a -ldflags '${LD_FLAGS}' -tags '${TAGS}' -o ${BUILD_DIR}/traggo-server
|
||||
|
||||
.PHONY: release
|
||||
release:
|
||||
docker build -t traggo:build -f docker/Dockerfile.build docker
|
||||
docker run \
|
||||
--rm \
|
||||
-v "$$HOME/.docker/config.json:/root/.docker/config.json" \
|
||||
-e CGO_ENABLED=1 \
|
||||
-e GITHUB_TOKEN="$$GITHUB_TOKEN" \
|
||||
-v /var/run/docker.sock:/var/run/docker.sock \
|
||||
-v $$PWD:/work \
|
||||
-w /work \
|
||||
traggo:build \
|
||||
release --skip=validate --clean
|
||||
|
||||
.PHONY: release-snapshot
|
||||
release-snapshot:
|
||||
docker build -t traggo:build -f docker/Dockerfile.build docker
|
||||
docker run \
|
||||
--rm \
|
||||
-v "$$HOME/.docker/config.json:/root/.docker/config.json" \
|
||||
-e CGO_ENABLED=1 \
|
||||
-e GITHUB_TOKEN="$$GITHUB_TOKEN" \
|
||||
-v /var/run/docker.sock:/var/run/docker.sock \
|
||||
-v $$PWD:/work \
|
||||
-w /work \
|
||||
traggo:build \
|
||||
release --clean --snapshot
|
||||
|
||||
install: install-go install-js
|
||||
|
||||
.PHONY: build
|
||||
62
README.md
Normal file
62
README.md
Normal file
@@ -0,0 +1,62 @@
|
||||
<p align="center">
|
||||
<a href="https://github.com/traggo/logo">
|
||||
<img height="300px" src="https://raw.githubusercontent.com/traggo/logo/master/logo.png" />
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<h1 align="center">traggo/server</h1>
|
||||
<p align="center"><i>tag-based time tracking</i></p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://travis-ci.com/traggo/server">
|
||||
<img alt="Build Status" src="https://travis-ci.com/traggo/server.svg?branch=master">
|
||||
</a>
|
||||
<a href="https://codecov.io/gh/traggo/server">
|
||||
<img alt="codecov" src="https://codecov.io/gh/traggo/server/branch/master/graph/badge.svg">
|
||||
</a>
|
||||
<a href="https://hub.docker.com/r/traggo/server">
|
||||
<img alt="Docker Pulls" src="https://img.shields.io/docker/pulls/traggo/server.svg">
|
||||
</a>
|
||||
<a href="https://github.com/traggo/server/releases/latest">
|
||||
<img alt="latest release" src="https://img.shields.io/github/release/traggo/server.svg">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
|
||||
Traggo is a tag-based time tracking tool. In Traggo there are no tasks, only [tagged](https://traggo.net/terminology/#tag) [time spans](https://traggo.net/terminology/#timespan).
|
||||
|
||||
With [tags](https://traggo.net/terminology/#tag), Traggo tries to be as customizable as possible, f.ex. if you work on different projects you could add a `project`-tag.
|
||||
If you like to see statistics from the different things you do, you could add a `type`-tag with values like `email`, `programming`, `meeting`.
|
||||
You can do it just as you like.
|
||||
|
||||
If you want to use Traggo, you need to host it yourself. This way, you have the full control over your data and no third-party
|
||||
may be able to read it. Have a look at our [Install Guide](https://traggo.net/install/).
|
||||
|
||||
## Features
|
||||
|
||||
* easy to setup
|
||||
* time tracking (obviously)
|
||||
* customizable dashboards with diagrams
|
||||
* a list and calendar view of the tracked time
|
||||
* sleek web ui with multiple themes
|
||||
* simple user management
|
||||
|
||||
---
|
||||
|
||||
<a href="./.github/traggo_list.png">
|
||||
<img width="265" alt="traggo list" src=".github/traggo_list.png">
|
||||
</a>
|
||||
<a href=".github/traggo_calendar.png">
|
||||
<img width="265" alt="traggo list" src=".github/traggo_calendar.png">
|
||||
</a>
|
||||
<a href=".github/traggo_dashboard.png">
|
||||
<img width="265" alt="traggo list" src=".github/traggo_dashboard.png">
|
||||
</a>
|
||||
|
||||
[Install](https://traggo.net/install/) ᛫
|
||||
[Configuration](https://traggo.net/config/) ᛫
|
||||
[Setup Dev Environment](https://traggo.net/dev/setup/)
|
||||
|
||||
## Versioning
|
||||
We use [SemVer](http://semver.org/) for versioning. For the versions available, see the
|
||||
[tags on this repository](https://github.com/traggo/server/tags).
|
||||
29
auth/cleanup.go
Normal file
29
auth/cleanup.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/jmattheis/go-timemath"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
var timeNow = time.Now
|
||||
|
||||
// CleanUp clean up expired devices
|
||||
func CleanUp(db *gorm.DB, interval time.Duration, close chan bool) {
|
||||
for {
|
||||
select {
|
||||
case <-time.After(interval):
|
||||
affected := db.Where("type = ? AND active_at < ?", model.TypeLongExpiry, timemath.Second.Subtract(timeNow(), model.TypeLongExpiry.Seconds())).
|
||||
Or("type = ? AND active_at < ?", model.TypeShortExpiry, timemath.Second.Subtract(timeNow(), model.TypeShortExpiry.Seconds())).
|
||||
Delete(new(model.Device)).RowsAffected
|
||||
if affected > 0 {
|
||||
log.Debug().Int64("amount", affected).Msg("removed devices")
|
||||
}
|
||||
case <-close:
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
138
auth/cleanup_test.go
Normal file
138
auth/cleanup_test.go
Normal file
@@ -0,0 +1,138 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/test"
|
||||
)
|
||||
|
||||
func TestCleanUp_stops(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
|
||||
methodDone := make(chan struct{})
|
||||
stopCleanUp := make(chan bool)
|
||||
|
||||
go func() {
|
||||
CleanUp(db.DB, time.Microsecond*10, stopCleanUp)
|
||||
methodDone <- struct{}{}
|
||||
}()
|
||||
|
||||
stopCleanUp <- true
|
||||
|
||||
select {
|
||||
case <-methodDone:
|
||||
// expected
|
||||
case <-time.After(time.Second):
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
|
||||
func TestCleanUp_removeExpiredDevices(t *testing.T) {
|
||||
now := test.Time("2018-06-30T18:30:00Z")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.User(2)
|
||||
db.Create(&model.Device{
|
||||
ID: 1,
|
||||
Token: "abc",
|
||||
UserID: 2,
|
||||
Name: "android 1",
|
||||
Type: model.TypeShortExpiry,
|
||||
ActiveAt: test.Time("2018-06-30T17:30:00Z"),
|
||||
CreatedAt: test.Time("2009-06-30T18:30:00Z"),
|
||||
})
|
||||
db.Create(&model.Device{
|
||||
ID: 2,
|
||||
Token: "abc2",
|
||||
UserID: 2,
|
||||
Name: "android 2",
|
||||
Type: model.TypeShortExpiry,
|
||||
ActiveAt: test.Time("2018-06-30T17:29:59Z"),
|
||||
CreatedAt: test.Time("2009-06-30T18:30:00Z"),
|
||||
})
|
||||
db.Create(&model.Device{
|
||||
ID: 3,
|
||||
Token: "abc3",
|
||||
UserID: 2,
|
||||
Name: "android 3",
|
||||
Type: model.TypeLongExpiry,
|
||||
ActiveAt: test.Time("2018-05-31T18:30:00Z"),
|
||||
CreatedAt: test.Time("2009-06-30T18:30:00Z"),
|
||||
})
|
||||
db.Create(&model.Device{
|
||||
ID: 4,
|
||||
Token: "abc4",
|
||||
UserID: 2,
|
||||
Name: "android 4",
|
||||
Type: model.TypeLongExpiry,
|
||||
ActiveAt: test.Time("2018-05-31T18:29:59Z"),
|
||||
CreatedAt: test.Time("2009-06-30T18:30:00Z"),
|
||||
})
|
||||
db.Create(&model.Device{
|
||||
ID: 5,
|
||||
Token: "abc5",
|
||||
UserID: 2,
|
||||
Name: "android 5",
|
||||
Type: model.TypeNoExpiry,
|
||||
ActiveAt: test.Time("2002-06-30T18:30:00Z"),
|
||||
CreatedAt: test.Time("2000-06-30T18:30:00Z"),
|
||||
})
|
||||
|
||||
stopCleanUp := make(chan bool)
|
||||
|
||||
go CleanUp(db.DB, time.Microsecond*10, stopCleanUp)
|
||||
|
||||
<-time.After(time.Millisecond * 20)
|
||||
|
||||
expected := []model.Device{
|
||||
{
|
||||
ID: 1,
|
||||
Token: "abc",
|
||||
UserID: 2,
|
||||
Name: "android 1",
|
||||
Type: model.TypeShortExpiry,
|
||||
ActiveAt: test.Time("2018-06-30T17:30:00Z"),
|
||||
CreatedAt: test.Time("2009-06-30T18:30:00Z"),
|
||||
},
|
||||
{
|
||||
ID: 3,
|
||||
Token: "abc3",
|
||||
UserID: 2,
|
||||
Name: "android 3",
|
||||
Type: model.TypeLongExpiry,
|
||||
ActiveAt: test.Time("2018-05-31T18:30:00Z"),
|
||||
CreatedAt: test.Time("2009-06-30T18:30:00Z"),
|
||||
},
|
||||
{
|
||||
ID: 5,
|
||||
Token: "abc5",
|
||||
UserID: 2,
|
||||
Name: "android 5",
|
||||
Type: model.TypeNoExpiry,
|
||||
ActiveAt: test.Time("2002-06-30T18:30:00Z"),
|
||||
CreatedAt: test.Time("2000-06-30T18:30:00Z"),
|
||||
},
|
||||
}
|
||||
|
||||
var devices []model.Device
|
||||
db.Find(&devices)
|
||||
assert.Equal(t, expected, devices)
|
||||
stopCleanUp <- true
|
||||
}
|
||||
|
||||
func fakeTime(t time.Time) func() {
|
||||
old := timeNow
|
||||
timeNow = func() time.Time {
|
||||
return t
|
||||
}
|
||||
return func() {
|
||||
timeNow = old
|
||||
}
|
||||
}
|
||||
26
auth/hasrole.go
Normal file
26
auth/hasrole.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
)
|
||||
|
||||
// HasRole checks if the current user has sufficient permissions.
|
||||
func HasRole() func(ctx context.Context, obj interface{}, next graphql.Resolver, role gqlmodel.Role) (res interface{}, err error) {
|
||||
return func(ctx context.Context, obj interface{}, next graphql.Resolver, role gqlmodel.Role) (interface{}, error) {
|
||||
user := GetUser(ctx)
|
||||
|
||||
if user == nil {
|
||||
return nil, errors.New("you need to login")
|
||||
}
|
||||
|
||||
if role == gqlmodel.RoleAdmin && !user.Admin {
|
||||
return nil, errors.New("permission denied")
|
||||
}
|
||||
|
||||
return next(ctx)
|
||||
}
|
||||
}
|
||||
55
auth/hasrole_test.go
Normal file
55
auth/hasrole_test.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package auth_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/test/fake"
|
||||
)
|
||||
|
||||
var (
|
||||
successResp = struct{}{}
|
||||
)
|
||||
|
||||
func TestHasRole_requiredUser_givenAdmin_succeeds(t *testing.T) {
|
||||
res, err := auth.HasRole()(fake.UserWithPerm(1, true), nil, noop, gqlmodel.RoleUser)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, successResp, res)
|
||||
}
|
||||
|
||||
func TestHasRole_requiredAdmin_givenAdmin_succeeds(t *testing.T) {
|
||||
res, err := auth.HasRole()(fake.UserWithPerm(1, true), nil, noop, gqlmodel.RoleAdmin)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, successResp, res)
|
||||
}
|
||||
|
||||
func TestHasRole_requiredUser_givenUser_succeeds(t *testing.T) {
|
||||
res, err := auth.HasRole()(fake.UserWithPerm(1, false), nil, noop, gqlmodel.RoleUser)
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, successResp, res)
|
||||
}
|
||||
|
||||
func TestHasRole_requiredAdmin_givenUser_fails(t *testing.T) {
|
||||
res, err := auth.HasRole()(fake.UserWithPerm(1, false), nil, noop, gqlmodel.RoleAdmin)
|
||||
assert.Nil(t, res)
|
||||
assert.EqualError(t, err, "permission denied")
|
||||
}
|
||||
|
||||
func TestHasRole_requiredAdmin_noUserGiven_fails(t *testing.T) {
|
||||
res, err := auth.HasRole()(context.Background(), nil, noop, gqlmodel.RoleAdmin)
|
||||
assert.Nil(t, res)
|
||||
assert.EqualError(t, err, "you need to login")
|
||||
}
|
||||
|
||||
func TestHasRole_requiredUser_noUserGiven_fails(t *testing.T) {
|
||||
res, err := auth.HasRole()(context.Background(), nil, noop, gqlmodel.RoleUser)
|
||||
assert.Nil(t, res)
|
||||
assert.EqualError(t, err, "you need to login")
|
||||
}
|
||||
|
||||
func noop(context.Context) (res interface{}, err error) {
|
||||
return successResp, nil
|
||||
}
|
||||
182
auth/middleware.go
Normal file
182
auth/middleware.go
Normal file
@@ -0,0 +1,182 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
type key string
|
||||
|
||||
var (
|
||||
traggoSession = "traggo"
|
||||
createSessionKey key = "createSession"
|
||||
destroySessionKey key = "destroySession"
|
||||
userKey key = "user"
|
||||
deviceKey key = "device"
|
||||
)
|
||||
|
||||
// Middleware is the auth middleware which sets user and device context parameters.
|
||||
func Middleware(db *gorm.DB) mux.MiddlewareFunc {
|
||||
return func(handler http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
handler.ServeHTTP(writer, sessionCallbacks(reqisterUser(request, writer, db), writer))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func sessionCallbacks(request *http.Request, writer http.ResponseWriter) *http.Request {
|
||||
createSession := func(token string, maxAge int) {
|
||||
http.SetCookie(writer, &http.Cookie{
|
||||
Name: traggoSession,
|
||||
Value: token,
|
||||
MaxAge: maxAge,
|
||||
})
|
||||
}
|
||||
destroySession := func() {
|
||||
http.SetCookie(writer, &http.Cookie{
|
||||
Name: traggoSession,
|
||||
Value: "",
|
||||
MaxAge: -1,
|
||||
})
|
||||
}
|
||||
return request.WithContext(WithDestroySession(WithCreateSession(request.Context(), createSession), destroySession))
|
||||
}
|
||||
|
||||
func reqisterUser(request *http.Request, writer http.ResponseWriter, db *gorm.DB) *http.Request {
|
||||
token, err := getToken(request)
|
||||
if err != nil {
|
||||
return request
|
||||
}
|
||||
|
||||
device := &model.Device{}
|
||||
if db.Where("token = ?", token).Find(device).RecordNotFound() {
|
||||
log.Debug().Str("token", token).Msg("No device with token found")
|
||||
return request
|
||||
}
|
||||
|
||||
user := &model.User{}
|
||||
if db.Find(user, device.UserID).RecordNotFound() {
|
||||
log.Panic().Int("userID", device.UserID).Int("deviceID", device.ID).Msg("User not found")
|
||||
}
|
||||
log.Debug().Int("userid", device.UserID).Str("username", user.Name).Msg("User found")
|
||||
|
||||
impersonate := request.Header.Get("X-Traggo-Impersonate")
|
||||
if impersonate != "" {
|
||||
if !user.Admin {
|
||||
log.Info().Str("impersonate", impersonate).Msg("Trying to impersonate without being admin")
|
||||
return request
|
||||
}
|
||||
userID, err := strconv.Atoi(impersonate)
|
||||
if err != nil {
|
||||
log.Info().Str("impersonate", impersonate).Msg("Unable to parse impersonation header")
|
||||
return request
|
||||
}
|
||||
impersonateUser := &model.User{}
|
||||
if db.Find(impersonateUser, userID).RecordNotFound() {
|
||||
log.Info().Int("userid", userID).Msg("Impersonation user not found")
|
||||
return request
|
||||
}
|
||||
user = impersonateUser
|
||||
log.Info().Str("username", user.Name).Msg("Impersonation user")
|
||||
}
|
||||
|
||||
if device.ActiveAt.Before(time.Now().Add(5 * -time.Minute)) {
|
||||
log.Debug().Int("deviceId", device.ID).Str("deviceName", device.Name).Msg("update device activeAt")
|
||||
device.ActiveAt = timeNow()
|
||||
db.Save(device)
|
||||
|
||||
if cookie, err := request.Cookie(traggoSession); err == nil && cookie != nil {
|
||||
cookie.MaxAge = device.Type.Seconds()
|
||||
http.SetCookie(writer, cookie)
|
||||
}
|
||||
}
|
||||
|
||||
return request.WithContext(WithUser(WithDevice(request.Context(), device), user))
|
||||
}
|
||||
|
||||
func getToken(request *http.Request) (string, error) {
|
||||
if value := request.Header.Get("Authorization"); value != "" && strings.HasPrefix(value, "traggo ") {
|
||||
log.Debug().Msg("Using authorization header for authentication")
|
||||
key := strings.TrimPrefix(value, "traggo ")
|
||||
return key, nil
|
||||
}
|
||||
|
||||
if cookie, err := request.Cookie("traggo"); err == nil && cookie != nil && cookie.Value != "" {
|
||||
log.Debug().Msg("Using cookie for authentication")
|
||||
return cookie.Value, nil
|
||||
}
|
||||
|
||||
if token := request.FormValue("token"); token != "" {
|
||||
log.Debug().Msg("Using query parameter for authentication")
|
||||
return token, nil
|
||||
}
|
||||
|
||||
return "", errors.New("no token found")
|
||||
}
|
||||
|
||||
// WithDevice adds the authenticated device to the context.
|
||||
func WithDevice(ctx context.Context, device *model.Device) context.Context {
|
||||
return context.WithValue(
|
||||
ctx,
|
||||
deviceKey,
|
||||
device)
|
||||
}
|
||||
|
||||
// WithUser adds the authenticated user to the context.
|
||||
func WithUser(ctx context.Context, user *model.User) context.Context {
|
||||
return context.WithValue(
|
||||
ctx,
|
||||
userKey,
|
||||
user)
|
||||
}
|
||||
|
||||
// WithCreateSession adds the create session method
|
||||
func WithCreateSession(ctx context.Context, f func(token string, age int)) context.Context {
|
||||
return context.WithValue(ctx, createSessionKey, f)
|
||||
}
|
||||
|
||||
// WithDestroySession adds the destroy session method
|
||||
func WithDestroySession(ctx context.Context, f func()) context.Context {
|
||||
return context.WithValue(ctx, destroySessionKey, f)
|
||||
}
|
||||
|
||||
// GetUser returns the authenticated user or panics.
|
||||
func GetUser(ctx context.Context) *model.User {
|
||||
if user, ok := ctx.Value(userKey).(*model.User); ok {
|
||||
return user
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetDevice returns the authenticated device or nil.
|
||||
func GetDevice(ctx context.Context) *model.Device {
|
||||
if device, ok := ctx.Value(deviceKey).(*model.Device); ok {
|
||||
return device
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetCreateSession gets the create session callback
|
||||
func GetCreateSession(ctx context.Context) func(token string, age int) {
|
||||
if f, ok := ctx.Value(createSessionKey).(func(string, int)); ok {
|
||||
return f
|
||||
}
|
||||
panic("create session must exist")
|
||||
}
|
||||
|
||||
// GetDestroySession gets the destroy session callback
|
||||
func GetDestroySession(ctx context.Context) func() {
|
||||
if f, ok := ctx.Value(destroySessionKey).(func()); ok {
|
||||
return f
|
||||
}
|
||||
panic("create session must exist")
|
||||
}
|
||||
328
auth/middleware_test.go
Normal file
328
auth/middleware_test.go
Normal file
@@ -0,0 +1,328 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/traggo/server/test"
|
||||
)
|
||||
|
||||
func TestMiddleware_noAuthentication_noAuthentication(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
spy := &requestSpy{}
|
||||
|
||||
Middleware(db.DB)(spy).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/test", nil))
|
||||
|
||||
ctx := spy.req.Context()
|
||||
assert.Nil(t, GetUser(ctx))
|
||||
assert.Nil(t, GetDevice(ctx))
|
||||
}
|
||||
|
||||
func TestMiddleware_query_notExistingToken_noAuthentication(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
spy := &requestSpy{}
|
||||
|
||||
Middleware(db.DB)(spy).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/test?token=abc", nil))
|
||||
|
||||
ctx := spy.req.Context()
|
||||
assert.Nil(t, GetUser(ctx))
|
||||
assert.Nil(t, GetDevice(ctx))
|
||||
}
|
||||
|
||||
func TestMiddleware_query_validToken_authenticates(t *testing.T) {
|
||||
now := test.Time("2018-06-30T18:30:00Z")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
builder := db.User(1)
|
||||
user := builder.User
|
||||
device := builder.NewDevice(2, "abc", "test")
|
||||
spy := &requestSpy{}
|
||||
|
||||
Middleware(db.DB)(spy).ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/test?token=abc", nil))
|
||||
|
||||
ctx := spy.req.Context()
|
||||
assert.Equal(t, &user, GetUser(ctx))
|
||||
|
||||
device.ActiveAt = now
|
||||
assert.Equal(t, &device, GetDevice(ctx))
|
||||
}
|
||||
|
||||
func TestMiddleware_header_notExistingToken_noAuthentication(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
spy := &requestSpy{}
|
||||
|
||||
request := httptest.NewRequest("GET", "/test?token=abc", nil)
|
||||
request.Header["Authorization"] = []string{"traggo abc"}
|
||||
Middleware(db.DB)(spy).ServeHTTP(httptest.NewRecorder(), request)
|
||||
|
||||
ctx := spy.req.Context()
|
||||
assert.Nil(t, GetUser(ctx))
|
||||
assert.Nil(t, GetDevice(ctx))
|
||||
}
|
||||
|
||||
func TestMiddleware_header_validToken_authenticates(t *testing.T) {
|
||||
now := test.Time("2018-06-30T18:30:00Z")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
builder := db.User(1)
|
||||
user := builder.User
|
||||
device := builder.NewDevice(2, "abc", "test")
|
||||
spy := &requestSpy{}
|
||||
|
||||
request := httptest.NewRequest("GET", "/test", nil)
|
||||
request.Header.Set("Authorization", "traggo abc")
|
||||
Middleware(db.DB)(spy).ServeHTTP(httptest.NewRecorder(), request)
|
||||
|
||||
ctx := spy.req.Context()
|
||||
assert.Equal(t, &user, GetUser(ctx))
|
||||
|
||||
device.ActiveAt = now
|
||||
assert.Equal(t, &device, GetDevice(ctx))
|
||||
}
|
||||
|
||||
func TestMiddleware_header_validToken_invalidAuthenticationType_noAuthentication(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.User(1).NewDevice(2, "abc", "test")
|
||||
spy := &requestSpy{}
|
||||
|
||||
request := httptest.NewRequest("GET", "/test", nil)
|
||||
request.Header.Set("Authorization", "basic abc")
|
||||
|
||||
Middleware(db.DB)(spy).ServeHTTP(httptest.NewRecorder(), request)
|
||||
|
||||
ctx := spy.req.Context()
|
||||
assert.Nil(t, GetUser(ctx))
|
||||
assert.Nil(t, GetDevice(ctx))
|
||||
}
|
||||
|
||||
func TestMiddleware_cookie_notExistingToken_noAuthentication(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
spy := &requestSpy{}
|
||||
|
||||
request := httptest.NewRequest("GET", "/test?token=abc", nil)
|
||||
request.AddCookie(&http.Cookie{
|
||||
Name: "traggo",
|
||||
Value: "abc",
|
||||
})
|
||||
Middleware(db.DB)(spy).ServeHTTP(httptest.NewRecorder(), request)
|
||||
|
||||
ctx := spy.req.Context()
|
||||
assert.Nil(t, GetUser(ctx))
|
||||
assert.Nil(t, GetDevice(ctx))
|
||||
}
|
||||
|
||||
func TestMiddleware_cookie_validToken_authenticates(t *testing.T) {
|
||||
now := test.Time("2018-06-30T18:30:00Z")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
builder := db.User(1)
|
||||
user := builder.User
|
||||
device := builder.NewDevice(2, "abc", "test")
|
||||
spy := &requestSpy{}
|
||||
|
||||
request := httptest.NewRequest("GET", "/test?token=abc", nil)
|
||||
request.AddCookie(&http.Cookie{
|
||||
Name: "traggo",
|
||||
Value: "abc",
|
||||
})
|
||||
Middleware(db.DB)(spy).ServeHTTP(httptest.NewRecorder(), request)
|
||||
|
||||
ctx := spy.req.Context()
|
||||
assert.Equal(t, &user, GetUser(ctx))
|
||||
|
||||
device.ActiveAt = now
|
||||
assert.Equal(t, &device, GetDevice(ctx))
|
||||
}
|
||||
|
||||
func TestMiddleware_createSession_setsCookie(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
spy := &requestSpy{}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
request := httptest.NewRequest("GET", "/test", nil)
|
||||
Middleware(db.DB)(spy).ServeHTTP(recorder, request)
|
||||
|
||||
ctx := spy.req.Context()
|
||||
GetCreateSession(ctx)("new token", 60)
|
||||
|
||||
cookieHeader := recorder.Header().Get("Set-Cookie")
|
||||
assert.Equal(t, `traggo="new token"; Max-Age=60`, cookieHeader)
|
||||
}
|
||||
|
||||
func TestMiddleware_noCallbackExecuted_noCookieSet(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
spy := &requestSpy{}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
request := httptest.NewRequest("GET", "/test", nil)
|
||||
Middleware(db.DB)(spy).ServeHTTP(recorder, request)
|
||||
|
||||
cookieHeader := recorder.Header().Get("Set-Cookie")
|
||||
assert.Equal(t, "", cookieHeader)
|
||||
}
|
||||
|
||||
func TestMiddleware_destroySession_destroysCookie(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
spy := &requestSpy{}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
request := httptest.NewRequest("GET", "/test", nil)
|
||||
Middleware(db.DB)(spy).ServeHTTP(recorder, request)
|
||||
|
||||
ctx := spy.req.Context()
|
||||
GetDestroySession(ctx)()
|
||||
|
||||
cookieHeader := recorder.Header().Get("Set-Cookie")
|
||||
assert.Equal(t, "traggo=; Max-Age=0", cookieHeader)
|
||||
}
|
||||
|
||||
func TestMiddleware_impersonate_no_admin(t *testing.T) {
|
||||
now := test.Time("2018-06-30T18:30:00Z")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
builder := db.User(1)
|
||||
builder.NewDevice(2, "abc", "test")
|
||||
spy := &requestSpy{}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
request := httptest.NewRequest("GET", "/test?token=abc", nil)
|
||||
request.Header.Set("X-Traggo-Impersonate", "empty")
|
||||
Middleware(db.DB)(spy).ServeHTTP(recorder, request)
|
||||
|
||||
response := recorder.Result()
|
||||
assert.Equal(t, 200, response.StatusCode)
|
||||
|
||||
ctx := spy.req.Context()
|
||||
assert.Nil(t, GetUser(ctx))
|
||||
assert.Nil(t, GetDevice(ctx))
|
||||
}
|
||||
|
||||
func TestMiddleware_impersonate_invalid_personate_header(t *testing.T) {
|
||||
now := test.Time("2018-06-30T18:30:00Z")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
builder := db.User(1)
|
||||
user := builder.User
|
||||
user.Admin = true
|
||||
db.Save(user)
|
||||
builder.NewDevice(2, "abc", "test")
|
||||
spy := &requestSpy{}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
request := httptest.NewRequest("GET", "/test?token=abc", nil)
|
||||
request.Header.Set("X-Traggo-Impersonate", "invalid")
|
||||
Middleware(db.DB)(spy).ServeHTTP(recorder, request)
|
||||
|
||||
response := recorder.Result()
|
||||
assert.Equal(t, 200, response.StatusCode)
|
||||
|
||||
ctx := spy.req.Context()
|
||||
assert.Nil(t, GetUser(ctx))
|
||||
assert.Nil(t, GetDevice(ctx))
|
||||
}
|
||||
|
||||
func TestMiddleware_impersonate_non_existing_user(t *testing.T) {
|
||||
now := test.Time("2018-06-30T18:30:00Z")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
builder := db.User(1)
|
||||
user := builder.User
|
||||
user.Admin = true
|
||||
db.Save(user)
|
||||
builder.NewDevice(2, "abc", "test")
|
||||
spy := &requestSpy{}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
request := httptest.NewRequest("GET", "/test?token=abc", nil)
|
||||
request.Header.Set("X-Traggo-Impersonate", "42")
|
||||
Middleware(db.DB)(spy).ServeHTTP(recorder, request)
|
||||
|
||||
response := recorder.Result()
|
||||
assert.Equal(t, 200, response.StatusCode)
|
||||
|
||||
ctx := spy.req.Context()
|
||||
assert.Nil(t, GetUser(ctx))
|
||||
assert.Nil(t, GetDevice(ctx))
|
||||
}
|
||||
|
||||
func TestMiddleware_impersonate_happy(t *testing.T) {
|
||||
now := test.Time("2018-06-30T18:30:00Z")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
admin_builder := db.User(1)
|
||||
admin_user := admin_builder.User
|
||||
admin_user.Admin = true
|
||||
db.Save(admin_user)
|
||||
admin_device := admin_builder.NewDevice(2, "abc", "test")
|
||||
|
||||
builder := db.User(2)
|
||||
user := builder.User
|
||||
|
||||
spy := &requestSpy{}
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
request := httptest.NewRequest("GET", "/test?token=abc", nil)
|
||||
request.Header.Set("X-Traggo-Impersonate", "2")
|
||||
Middleware(db.DB)(spy).ServeHTTP(recorder, request)
|
||||
|
||||
response := recorder.Result()
|
||||
assert.Equal(t, 200, response.StatusCode)
|
||||
|
||||
ctx := spy.req.Context()
|
||||
assert.Equal(t, &user, GetUser(ctx))
|
||||
|
||||
admin_device.ActiveAt = now
|
||||
assert.Equal(t, &admin_device, GetDevice(ctx))
|
||||
}
|
||||
|
||||
func TestGetCreateSession_panicsWhenMiddlewareWasNotExecuted(t *testing.T) {
|
||||
assert.Panics(t, func() {
|
||||
GetCreateSession(context.Background())
|
||||
})
|
||||
}
|
||||
|
||||
func TestGetDestroySession_panicsWhenMiddlewareWasNotExecuted(t *testing.T) {
|
||||
assert.Panics(t, func() {
|
||||
GetDestroySession(context.Background())
|
||||
})
|
||||
}
|
||||
|
||||
type requestSpy struct {
|
||||
req *http.Request
|
||||
}
|
||||
|
||||
func (s *requestSpy) ServeHTTP(_ http.ResponseWriter, req *http.Request) {
|
||||
s.req = req
|
||||
}
|
||||
43
auth/rand/random.go
Normal file
43
auth/rand/random.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package rand
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
var (
|
||||
chars = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
|
||||
|
||||
randRead = rand.Read
|
||||
)
|
||||
|
||||
func init() {
|
||||
// exits with 1 when crypto/rand is not available
|
||||
Token(1)
|
||||
}
|
||||
|
||||
func randBytes(count int) ([]byte, error) {
|
||||
bytes := make([]byte, count)
|
||||
_, err := randRead(bytes)
|
||||
return bytes, err
|
||||
}
|
||||
|
||||
// Token returns a random token.
|
||||
func Token(count int) string {
|
||||
bytes, err := randBytes(count)
|
||||
if err != nil {
|
||||
log.Panic().Msg("crypto/rand is not available")
|
||||
}
|
||||
return bytesToString(bytes, count)
|
||||
}
|
||||
|
||||
func bytesToString(bytes []byte, count int) string {
|
||||
token := make([]rune, count)
|
||||
|
||||
for index, item := range bytes {
|
||||
token[index] = chars[int(item)%len(chars)]
|
||||
}
|
||||
|
||||
return string(token)
|
||||
}
|
||||
30
auth/rand/random_test.go
Normal file
30
auth/rand/random_test.go
Normal file
@@ -0,0 +1,30 @@
|
||||
package rand
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestToken(t *testing.T) {
|
||||
for i := 1; i < 10; i++ {
|
||||
assert.Len(t, Token(i), i)
|
||||
}
|
||||
assert.Len(t, Token(120), 120)
|
||||
assert.Len(t, Token(222), 222)
|
||||
assert.Len(t, Token(555665), 555665)
|
||||
}
|
||||
|
||||
func TestToken_panics(t *testing.T) {
|
||||
old := randRead
|
||||
defer func() {
|
||||
randRead = old
|
||||
}()
|
||||
randRead = func(b []byte) (n int, err error) {
|
||||
return 0, errors.New("oops")
|
||||
}
|
||||
assert.Panics(t, func() {
|
||||
Token(1)
|
||||
})
|
||||
}
|
||||
104
config/config.go
Normal file
104
config/config.go
Normal file
@@ -0,0 +1,104 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/joho/godotenv"
|
||||
"github.com/kelseyhightower/envconfig"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/traggo/server/config/mode"
|
||||
)
|
||||
|
||||
var (
|
||||
prefix = "traggo"
|
||||
files = []string{".env.development.local", ".env.development", ".env.local", ".env"}
|
||||
absoluteFiles = []string{"/etc/traggo/server.ini"}
|
||||
osExecutable = os.Executable
|
||||
osStat = os.Stat
|
||||
)
|
||||
|
||||
// Config represents the application configuration.
|
||||
type Config struct {
|
||||
Port int `default:"3030"`
|
||||
LogLevel LogLevel `default:"info" split_words:"true"`
|
||||
DefaultUserName string `default:"admin" split_words:"true"`
|
||||
DefaultUserPass string `default:"admin" split_words:"true"`
|
||||
PassStrength int `default:"10" split_words:"true"`
|
||||
DatabaseDialect string `default:"sqlite3" split_words:"true"`
|
||||
DatabaseConnection string `default:"data/traggo.db" split_words:"true"`
|
||||
}
|
||||
|
||||
// Get loads the application config.
|
||||
func Get() (Config, []FutureLog) {
|
||||
var logs []FutureLog
|
||||
dir, log := getExecutableOrWorkDir()
|
||||
if log != nil {
|
||||
logs = append(logs, *log)
|
||||
}
|
||||
|
||||
for _, file := range getFiles(dir) {
|
||||
_, fileErr := osStat(file)
|
||||
if fileErr == nil {
|
||||
if err := godotenv.Load(file); err != nil {
|
||||
logs = append(logs, FutureLog{
|
||||
Level: zerolog.FatalLevel,
|
||||
Msg: fmt.Sprintf("cannot load file %s: %s", file, err)})
|
||||
} else {
|
||||
logs = append(logs, FutureLog{
|
||||
Level: zerolog.DebugLevel,
|
||||
Msg: fmt.Sprintf("Loading file %s", file)})
|
||||
}
|
||||
} else if os.IsNotExist(fileErr) {
|
||||
continue
|
||||
} else {
|
||||
logs = append(logs, FutureLog{
|
||||
Level: zerolog.WarnLevel,
|
||||
Msg: fmt.Sprintf("cannot read file %s because %s", file, fileErr)})
|
||||
}
|
||||
}
|
||||
|
||||
config := Config{}
|
||||
err := envconfig.Process(prefix, &config)
|
||||
if err != nil {
|
||||
logs = append(logs, FutureLog{
|
||||
Level: zerolog.FatalLevel,
|
||||
Msg: fmt.Sprintf("cannot parse env params: %s", err)})
|
||||
}
|
||||
|
||||
return config, logs
|
||||
}
|
||||
|
||||
func getExecutableOrWorkDir() (string, *FutureLog) {
|
||||
dir, err := getExecutableDir()
|
||||
// when using `go run main.go` the executable lives in th temp directory therefore the env.development
|
||||
// will not be read, this enforces that the current work directory is used in dev mode.
|
||||
if err != nil || mode.Get() == mode.Dev {
|
||||
return filepath.Dir("."), err
|
||||
}
|
||||
return dir, nil
|
||||
}
|
||||
|
||||
func getExecutableDir() (string, *FutureLog) {
|
||||
ex, err := osExecutable()
|
||||
if err != nil {
|
||||
return "", &FutureLog{
|
||||
Level: zerolog.ErrorLevel,
|
||||
Msg: "Could not get path of executable using working directory instead. " + err.Error()}
|
||||
}
|
||||
return filepath.Dir(ex), nil
|
||||
}
|
||||
|
||||
func getFiles(relativeTo string) []string {
|
||||
var result []string
|
||||
for _, file := range files {
|
||||
result = append(result, filepath.Join(relativeTo, file))
|
||||
}
|
||||
homeDir, err := os.UserHomeDir()
|
||||
if err == nil {
|
||||
result = append(result, filepath.Join(homeDir, ".config/traggo/server.ini"))
|
||||
}
|
||||
result = append(result, absoluteFiles...)
|
||||
return result
|
||||
}
|
||||
160
config/config_test.go
Normal file
160
config/config_test.go
Normal file
@@ -0,0 +1,160 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/traggo/server/config/mode"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
absoluteFiles = []string{}
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func TestGet_withoutFiles_containsDefault(t *testing.T) {
|
||||
conf, logs := Get()
|
||||
|
||||
assert.Empty(t, logs)
|
||||
assert.Equal(t, 3030, conf.Port)
|
||||
}
|
||||
|
||||
func TestGet_withoutFiles_usesEnvVariables(t *testing.T) {
|
||||
assert.Nil(t, os.Setenv("TRAGGO_PORT", "9999"))
|
||||
defer os.Unsetenv("TRAGGO_PORT")
|
||||
|
||||
conf, logs := Get()
|
||||
|
||||
assert.Empty(t, logs)
|
||||
assert.Equal(t, 9999, conf.Port)
|
||||
}
|
||||
|
||||
func TestGet_withFile_usesFile(t *testing.T) {
|
||||
defer os.Unsetenv("TRAGGO_PORT")
|
||||
assert.Nil(t, ioutil.WriteFile(".env", []byte("TRAGGO_PORT=5555"), 0777))
|
||||
defer os.Remove(".env")
|
||||
|
||||
conf, logs := Get()
|
||||
|
||||
expected := []FutureLog{{
|
||||
Msg: `Loading file .env`,
|
||||
Level: zerolog.DebugLevel,
|
||||
}}
|
||||
assert.Equal(t, expected, logs)
|
||||
assert.Equal(t, 5555, conf.Port)
|
||||
}
|
||||
|
||||
func TestGet_withInvalidEnvParam_errs(t *testing.T) {
|
||||
assert.Nil(t, os.Setenv("TRAGGO_PORT", "asdasd"))
|
||||
defer os.Unsetenv("TRAGGO_PORT")
|
||||
|
||||
_, logs := Get()
|
||||
|
||||
expected := []FutureLog{{
|
||||
Msg: `cannot parse env params: envconfig.Process: assigning TRAGGO_PORT to Port: converting 'asdasd' to type int. details: strconv.ParseInt: parsing "asdasd": invalid syntax`,
|
||||
Level: zerolog.FatalLevel,
|
||||
}}
|
||||
assert.Equal(t, expected, logs)
|
||||
}
|
||||
|
||||
func TestGet_prodMode_findFileRelativeToExecutable(t *testing.T) {
|
||||
defer os.Unsetenv("TRAGGO_PORT")
|
||||
oldMode := mode.Get()
|
||||
mode.Set(mode.Prod)
|
||||
defer func() {
|
||||
mode.Set(oldMode)
|
||||
}()
|
||||
old := osExecutable
|
||||
defer func() {
|
||||
osExecutable = old
|
||||
}()
|
||||
osExecutable = func() (string, error) {
|
||||
return "./testpath/some.exe", nil
|
||||
}
|
||||
assert.Nil(t, os.MkdirAll("./testpath", 0777))
|
||||
defer os.RemoveAll("./testpath")
|
||||
|
||||
assert.Nil(t, ioutil.WriteFile("./testpath/.env", []byte("TRAGGO_PORT=6666"), 0777))
|
||||
|
||||
conf, logs := Get()
|
||||
|
||||
expected := []FutureLog{{
|
||||
Msg: `Loading file ` + filepath.Join("testpath", ".env"),
|
||||
Level: zerolog.DebugLevel,
|
||||
}}
|
||||
assert.Equal(t, expected, logs)
|
||||
assert.Equal(t, 6666, conf.Port)
|
||||
}
|
||||
|
||||
func TestGet_errsOnOsExecutable(t *testing.T) {
|
||||
defer os.Unsetenv("TRAGGO_PORT")
|
||||
oldMode := mode.Get()
|
||||
mode.Set(mode.Prod)
|
||||
defer func() {
|
||||
mode.Set(oldMode)
|
||||
}()
|
||||
old := osExecutable
|
||||
defer func() {
|
||||
osExecutable = old
|
||||
}()
|
||||
osExecutable = func() (string, error) {
|
||||
return "", errors.New("oops")
|
||||
}
|
||||
|
||||
_, logs := Get()
|
||||
|
||||
expected := []FutureLog{{
|
||||
Msg: `Could not get path of executable using working directory instead. oops`,
|
||||
Level: zerolog.ErrorLevel,
|
||||
}}
|
||||
assert.Equal(t, expected, logs)
|
||||
}
|
||||
|
||||
func TestGet_withoutFilePermission(t *testing.T) {
|
||||
defer os.Unsetenv("TRAGGO_PORT")
|
||||
old := osStat
|
||||
defer func() {
|
||||
osStat = old
|
||||
}()
|
||||
osStat = func(name string) (os.FileInfo, error) {
|
||||
if name == ".env" {
|
||||
return nil, os.ErrPermission
|
||||
}
|
||||
return os.Stat(name)
|
||||
}
|
||||
|
||||
_, logs := Get()
|
||||
|
||||
expected := []FutureLog{{
|
||||
Msg: `cannot read file .env because permission denied`,
|
||||
Level: zerolog.WarnLevel,
|
||||
}}
|
||||
assert.Equal(t, expected, logs)
|
||||
}
|
||||
|
||||
func TestGet_checksAbsoluteFiles(t *testing.T) {
|
||||
defer os.Unsetenv("TRAGGO_PORT")
|
||||
assert.Nil(t, os.MkdirAll("./absolutepath", 0777))
|
||||
defer os.RemoveAll("./absolutepath")
|
||||
path, err := filepath.Abs("./absolutepath/.env")
|
||||
assert.Nil(t, err)
|
||||
absoluteFiles = []string{path}
|
||||
defer func() {
|
||||
absoluteFiles = []string{}
|
||||
}()
|
||||
assert.Nil(t, ioutil.WriteFile("./absolutepath/.env", []byte("TRAGGO_PORT=7777"), 0777))
|
||||
|
||||
conf, logs := Get()
|
||||
|
||||
expected := []FutureLog{{
|
||||
Msg: `Loading file ` + path,
|
||||
Level: zerolog.DebugLevel,
|
||||
}}
|
||||
assert.Equal(t, expected, logs)
|
||||
assert.Equal(t, 7777, conf.Port)
|
||||
}
|
||||
10
config/error.go
Normal file
10
config/error.go
Normal file
@@ -0,0 +1,10 @@
|
||||
package config
|
||||
|
||||
import "github.com/rs/zerolog"
|
||||
|
||||
// FutureLog is an intermediate type for log messages. It is used before the config was loaded because without loaded
|
||||
// config we do not know the log level, so we log these messages once the config was initialized.
|
||||
type FutureLog struct {
|
||||
Level zerolog.Level
|
||||
Msg string
|
||||
}
|
||||
25
config/loglevel.go
Normal file
25
config/loglevel.go
Normal file
@@ -0,0 +1,25 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
)
|
||||
|
||||
// LogLevel type that provides helper methods for decoding.
|
||||
type LogLevel zerolog.Level
|
||||
|
||||
// Decode decodes a string to a log level.
|
||||
func (ll *LogLevel) Decode(value string) error {
|
||||
if level, err := zerolog.ParseLevel(value); err == nil {
|
||||
*ll = LogLevel(level)
|
||||
return nil
|
||||
}
|
||||
*ll = LogLevel(zerolog.InfoLevel)
|
||||
return errors.New("unknown log level")
|
||||
}
|
||||
|
||||
// AsZeroLogLevel converts the LogLevel to a zerolog.Level.
|
||||
func (ll LogLevel) AsZeroLogLevel() zerolog.Level {
|
||||
return zerolog.Level(ll)
|
||||
}
|
||||
22
config/loglevel_test.go
Normal file
22
config/loglevel_test.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestLogLevel_Decode_success(t *testing.T) {
|
||||
ll := new(LogLevel)
|
||||
err := ll.Decode("fatal")
|
||||
assert.Nil(t, err)
|
||||
assert.Equal(t, ll.AsZeroLogLevel(), zerolog.FatalLevel)
|
||||
}
|
||||
|
||||
func TestLogLevel_Decode_fail(t *testing.T) {
|
||||
ll := new(LogLevel)
|
||||
err := ll.Decode("asdasdasdasdasdasd")
|
||||
assert.EqualError(t, err, "unknown log level")
|
||||
assert.Equal(t, ll.AsZeroLogLevel(), zerolog.InfoLevel)
|
||||
}
|
||||
20
config/mode/mode.go
Normal file
20
config/mode/mode.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package mode
|
||||
|
||||
const (
|
||||
// Dev for development mode
|
||||
Dev = "dev"
|
||||
// Prod for production mode
|
||||
Prod = "prod"
|
||||
)
|
||||
|
||||
var mode = Dev
|
||||
|
||||
// Set sets the new mode.
|
||||
func Set(newMode string) {
|
||||
mode = newMode
|
||||
}
|
||||
|
||||
// Get returns the current mode.
|
||||
func Get() string {
|
||||
return mode
|
||||
}
|
||||
17
config/mode/mode_test.go
Normal file
17
config/mode/mode_test.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package mode
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/magiconair/properties/assert"
|
||||
)
|
||||
|
||||
func TestGet(t *testing.T) {
|
||||
mode = Prod
|
||||
assert.Equal(t, Prod, Get())
|
||||
}
|
||||
|
||||
func TestSet(t *testing.T) {
|
||||
Set(Prod)
|
||||
assert.Equal(t, Prod, mode)
|
||||
}
|
||||
37
dashboard/convert/dashboard.go
Normal file
37
dashboard/convert/dashboard.go
Normal file
@@ -0,0 +1,37 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// ToExternalDashboards converts dashboards.
|
||||
func ToExternalDashboards(dashboards []model.Dashboard) ([]*gqlmodel.Dashboard, error) {
|
||||
result := []*gqlmodel.Dashboard{}
|
||||
for _, dashboard := range dashboards {
|
||||
if converted, err := ToExternalDashboard(dashboard); err == nil {
|
||||
result = append(result, converted)
|
||||
} else {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ToExternalDashboard converts a dashboard.
|
||||
func ToExternalDashboard(dashboard model.Dashboard) (*gqlmodel.Dashboard, error) {
|
||||
entries, err := toExternalEntries(dashboard.Entries)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ranges, err := toExternalDashboardsRanges(dashboard.Ranges)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &gqlmodel.Dashboard{
|
||||
ID: dashboard.ID,
|
||||
Name: dashboard.Name,
|
||||
Items: entries,
|
||||
Ranges: ranges,
|
||||
}, nil
|
||||
}
|
||||
39
dashboard/convert/dashboardtag.go
Normal file
39
dashboard/convert/dashboardtag.go
Normal file
@@ -0,0 +1,39 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
func tagFiltersToExternal(tags []model.DashboardTagFilter, include bool) []*gqlmodel.TimeSpanTag {
|
||||
if len(tags) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
result := []*gqlmodel.TimeSpanTag{}
|
||||
for _, tag := range tags {
|
||||
if tag.Include == include {
|
||||
result = append(result, &gqlmodel.TimeSpanTag{
|
||||
Key: tag.Key,
|
||||
Value: tag.StringValue,
|
||||
})
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func TagFiltersToInternal(gqls []*gqlmodel.InputTimeSpanTag, include bool) []model.DashboardTagFilter {
|
||||
result := make([]model.DashboardTagFilter, 0)
|
||||
for _, tag := range gqls {
|
||||
result = append(result, tagFilterToInternal(*tag, include))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func tagFilterToInternal(gqls gqlmodel.InputTimeSpanTag, include bool) model.DashboardTagFilter {
|
||||
return model.DashboardTagFilter{
|
||||
Key: gqls.Key,
|
||||
StringValue: gqls.Value,
|
||||
Include: include,
|
||||
}
|
||||
}
|
||||
59
dashboard/convert/entry.go
Normal file
59
dashboard/convert/entry.go
Normal file
@@ -0,0 +1,59 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
func toExternalEntries(entries []model.DashboardEntry) ([]*gqlmodel.DashboardEntry, error) {
|
||||
result := []*gqlmodel.DashboardEntry{}
|
||||
for _, entry := range entries {
|
||||
converted, err := ToExternalEntry(entry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, converted)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ToExternalEntry converts entries.
|
||||
func ToExternalEntry(entry model.DashboardEntry) (*gqlmodel.DashboardEntry, error) {
|
||||
mobilePosition, err := toExternalPosition(entry.MobilePosition)
|
||||
if err != nil {
|
||||
return &gqlmodel.DashboardEntry{}, err
|
||||
}
|
||||
desktopPos, err := toExternalPosition(entry.DesktopPosition)
|
||||
if err != nil {
|
||||
return &gqlmodel.DashboardEntry{}, err
|
||||
}
|
||||
pos := gqlmodel.ResponsiveDashboardEntryPos{
|
||||
Mobile: enhancePos(mobilePosition, "mobile"),
|
||||
Desktop: enhancePos(desktopPos, "desktop"),
|
||||
}
|
||||
dateRange := &gqlmodel.RelativeOrStaticRange{
|
||||
From: entry.RangeFrom,
|
||||
To: entry.RangeTo,
|
||||
}
|
||||
stats := &gqlmodel.StatsSelection{
|
||||
Interval: ExternalInterval(entry.Interval),
|
||||
Tags: strings.Split(entry.Keys, ","),
|
||||
Range: dateRange,
|
||||
ExcludeTags: tagFiltersToExternal(entry.TagFilters, false),
|
||||
IncludeTags: tagFiltersToExternal(entry.TagFilters, true),
|
||||
}
|
||||
if entry.RangeID != model.NoRangeIDDefined {
|
||||
stats.RangeID = &entry.RangeID
|
||||
stats.Range = nil
|
||||
}
|
||||
return &gqlmodel.DashboardEntry{
|
||||
ID: entry.ID,
|
||||
Title: entry.Title,
|
||||
Total: entry.Total,
|
||||
Pos: &pos,
|
||||
StatsSelection: stats,
|
||||
EntryType: ExternalEntryType(entry.Type),
|
||||
}, nil
|
||||
}
|
||||
46
dashboard/convert/entrytype.go
Normal file
46
dashboard/convert/entrytype.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// InternalEntryType converts entry type.
|
||||
func InternalEntryType(entryType gqlmodel.EntryType) model.DashboardType {
|
||||
switch entryType {
|
||||
case gqlmodel.EntryTypeBarChart:
|
||||
return model.TypeBarChart
|
||||
case gqlmodel.EntryTypePieChart:
|
||||
return model.TypePieChart
|
||||
case gqlmodel.EntryTypeStackedBarChart:
|
||||
return model.TypeStackedBarChart
|
||||
case gqlmodel.EntryTypeLineChart:
|
||||
return model.TypeLineChart
|
||||
case gqlmodel.EntryTypeHorizontalTable:
|
||||
return model.HorizontalTable
|
||||
case gqlmodel.EntryTypeVerticalTable:
|
||||
return model.VerticalTable
|
||||
default:
|
||||
panic("unknown entry type " + entryType)
|
||||
}
|
||||
}
|
||||
|
||||
// ExternalEntryType converts entry type.
|
||||
func ExternalEntryType(entryType model.DashboardType) gqlmodel.EntryType {
|
||||
switch entryType {
|
||||
case model.TypeBarChart:
|
||||
return gqlmodel.EntryTypeBarChart
|
||||
case model.TypePieChart:
|
||||
return gqlmodel.EntryTypePieChart
|
||||
case model.TypeStackedBarChart:
|
||||
return gqlmodel.EntryTypeStackedBarChart
|
||||
case model.TypeLineChart:
|
||||
return gqlmodel.EntryTypeLineChart
|
||||
case model.HorizontalTable:
|
||||
return gqlmodel.EntryTypeHorizontalTable
|
||||
case model.VerticalTable:
|
||||
return gqlmodel.EntryTypeVerticalTable
|
||||
default:
|
||||
panic("unknown entry type " + entryType)
|
||||
}
|
||||
}
|
||||
46
dashboard/convert/interval.go
Normal file
46
dashboard/convert/interval.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// InternalInterval converts interval.
|
||||
func InternalInterval(interval gqlmodel.StatsInterval) model.Interval {
|
||||
switch interval {
|
||||
case gqlmodel.StatsIntervalHourly:
|
||||
return model.IntervalHourly
|
||||
case gqlmodel.StatsIntervalDaily:
|
||||
return model.IntervalDaily
|
||||
case gqlmodel.StatsIntervalWeekly:
|
||||
return model.IntervalWeekly
|
||||
case gqlmodel.StatsIntervalMonthly:
|
||||
return model.IntervalMonthly
|
||||
case gqlmodel.StatsIntervalYearly:
|
||||
return model.IntervalYearly
|
||||
case gqlmodel.StatsIntervalSingle:
|
||||
return model.IntervalSingle
|
||||
default:
|
||||
panic("unknown interval type " + interval)
|
||||
}
|
||||
}
|
||||
|
||||
// ExternalInterval converts interval.
|
||||
func ExternalInterval(interval model.Interval) gqlmodel.StatsInterval {
|
||||
switch interval {
|
||||
case model.IntervalHourly:
|
||||
return gqlmodel.StatsIntervalHourly
|
||||
case model.IntervalDaily:
|
||||
return gqlmodel.StatsIntervalDaily
|
||||
case model.IntervalWeekly:
|
||||
return gqlmodel.StatsIntervalWeekly
|
||||
case model.IntervalMonthly:
|
||||
return gqlmodel.StatsIntervalMonthly
|
||||
case model.IntervalYearly:
|
||||
return gqlmodel.StatsIntervalYearly
|
||||
case model.IntervalSingle:
|
||||
return gqlmodel.StatsIntervalSingle
|
||||
default:
|
||||
panic("unknown interval type " + interval)
|
||||
}
|
||||
}
|
||||
111
dashboard/convert/position.go
Normal file
111
dashboard/convert/position.go
Normal file
@@ -0,0 +1,111 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
"github.com/jinzhu/copier"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
func enhancePos(pos *gqlmodel.DashboardEntryPos, size string) *gqlmodel.DashboardEntryPos {
|
||||
switch size {
|
||||
case "mobile":
|
||||
pos.MinH = 2
|
||||
pos.MinW = 1
|
||||
case "desktop":
|
||||
pos.MinH = 3
|
||||
pos.MinW = 2
|
||||
default:
|
||||
panic("unknown size")
|
||||
}
|
||||
if pos.MinW > pos.W {
|
||||
pos.W = pos.MinW
|
||||
}
|
||||
if pos.MinH > pos.H {
|
||||
pos.H = pos.MinH
|
||||
}
|
||||
return pos
|
||||
}
|
||||
|
||||
// EmptyPos returns a empty position.
|
||||
func EmptyPos() string {
|
||||
internal := internalDashboardPositionV1{
|
||||
Version: "v1",
|
||||
H: 0,
|
||||
W: 0,
|
||||
X: 0,
|
||||
Y: 0,
|
||||
}
|
||||
|
||||
if bytes, err := json.Marshal(&internal); err != nil {
|
||||
panic(err)
|
||||
} else {
|
||||
return string(bytes)
|
||||
}
|
||||
}
|
||||
|
||||
func toInternalPosition(external gqlmodel.InputDashboardEntryPos) (string, error) {
|
||||
internal := internalDashboardPositionV1{Version: "v1"}
|
||||
if err := copier.Copy(&internal, &external); err != nil {
|
||||
return "", err
|
||||
}
|
||||
bytes, err := json.Marshal(&internal)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(bytes), nil
|
||||
}
|
||||
|
||||
// ApplyPos copies the position to the external position.
|
||||
func ApplyPos(entry *model.DashboardEntry, pos *gqlmodel.InputResponsiveDashboardEntryPos) error {
|
||||
if pos == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if pos.Mobile != nil {
|
||||
lpos, err := toInternalPosition(*pos.Mobile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entry.MobilePosition = lpos
|
||||
}
|
||||
if pos.Desktop != nil {
|
||||
mpos, err := toInternalPosition(*pos.Desktop)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entry.DesktopPosition = mpos
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func toExternalPosition(pos string) (*gqlmodel.DashboardEntryPos, error) {
|
||||
if pos == "" {
|
||||
return nil, nil
|
||||
}
|
||||
internal := internalDashboardPositionV1{}
|
||||
if err := json.Unmarshal([]byte(pos), &internal); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if internal.Version != "v1" {
|
||||
log.Error().Interface("pos", internal).Msg("Invalid position version")
|
||||
}
|
||||
external := gqlmodel.DashboardEntryPos{}
|
||||
|
||||
if err := copier.Copy(&external, &internal); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &external, nil
|
||||
}
|
||||
|
||||
type internalDashboardPositionV1 struct {
|
||||
Version string
|
||||
W int `json:"w"`
|
||||
H int `json:"h"`
|
||||
X int `json:"x"`
|
||||
Y int `json:"y"`
|
||||
}
|
||||
46
dashboard/convert/range.go
Normal file
46
dashboard/convert/range.go
Normal file
@@ -0,0 +1,46 @@
|
||||
package convert
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/time"
|
||||
)
|
||||
|
||||
func toExternalDashboardsRanges(ranges []model.DashboardRange) ([]*gqlmodel.NamedDateRange, error) {
|
||||
result := []*gqlmodel.NamedDateRange{}
|
||||
for _, xrange := range ranges {
|
||||
result = append(result, ToExternalDashboardRange(xrange))
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ToExternalDashboardRange converts a range.
|
||||
func ToExternalDashboardRange(xrange model.DashboardRange) *gqlmodel.NamedDateRange {
|
||||
return &gqlmodel.NamedDateRange{
|
||||
ID: xrange.ID,
|
||||
Name: xrange.Name,
|
||||
Editable: xrange.Editable,
|
||||
Range: &gqlmodel.RelativeOrStaticRange{
|
||||
From: xrange.From,
|
||||
To: xrange.To,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// ToInternalDashboardRange converts a range.
|
||||
func ToInternalDashboardRange(xrange gqlmodel.InputNamedDateRange) (model.DashboardRange, error) {
|
||||
if err := time.Validate(xrange.Range.From); err != nil {
|
||||
return model.DashboardRange{}, fmt.Errorf("range from (%s) invalid: %s", xrange.Range.From, err)
|
||||
}
|
||||
if err := time.Validate(xrange.Range.To); err != nil {
|
||||
return model.DashboardRange{}, fmt.Errorf("range to (%s) invalid: %s", xrange.Range.To, err)
|
||||
}
|
||||
return model.DashboardRange{
|
||||
Editable: xrange.Editable,
|
||||
From: xrange.Range.From,
|
||||
To: xrange.Range.To,
|
||||
Name: xrange.Name,
|
||||
}, nil
|
||||
}
|
||||
27
dashboard/create.go
Normal file
27
dashboard/create.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/traggo/server/dashboard/convert"
|
||||
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// CreateDashboard creates a dashboard.
|
||||
func (r *ResolverForDashboard) CreateDashboard(ctx context.Context, name string) (*gqlmodel.Dashboard, error) {
|
||||
userID := auth.GetUser(ctx).ID
|
||||
dashboard := model.Dashboard{
|
||||
UserID: userID,
|
||||
Name: name,
|
||||
}
|
||||
|
||||
create := r.DB.Create(&dashboard)
|
||||
if create.Error != nil {
|
||||
return &gqlmodel.Dashboard{}, create.Error
|
||||
}
|
||||
|
||||
return convert.ToExternalDashboard(dashboard)
|
||||
}
|
||||
106
dashboard/dashboard_test.go
Normal file
106
dashboard/dashboard_test.go
Normal file
@@ -0,0 +1,106 @@
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/test"
|
||||
"github.com/traggo/server/test/fake"
|
||||
)
|
||||
|
||||
func TestDashboard(t *testing.T) {
|
||||
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.User(1)
|
||||
db.User(2)
|
||||
|
||||
resolver := NewResolverForDashboard(db.DB)
|
||||
|
||||
// initial no dashboards
|
||||
user1 := fake.User(1)
|
||||
user2 := fake.User(2)
|
||||
dashboards, err := resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, dashboards)
|
||||
|
||||
dashboard, err := resolver.CreateDashboard(user1, "cool dashboard")
|
||||
require.NoError(t, err)
|
||||
expectAdded := &gqlmodel.Dashboard{
|
||||
ID: 1,
|
||||
Name: "cool dashboard",
|
||||
Ranges: []*gqlmodel.NamedDateRange{},
|
||||
Items: []*gqlmodel.DashboardEntry{},
|
||||
}
|
||||
require.Equal(t, expectAdded, dashboard)
|
||||
dashboards, err = resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []*gqlmodel.Dashboard{
|
||||
{
|
||||
ID: 1,
|
||||
Name: "cool dashboard",
|
||||
Ranges: []*gqlmodel.NamedDateRange{},
|
||||
Items: []*gqlmodel.DashboardEntry{},
|
||||
},
|
||||
}, dashboards)
|
||||
dashboards, err = resolver.Dashboards(user2)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, dashboards)
|
||||
|
||||
dashboard, err = resolver.UpdateDashboard(user2, 1, "kek")
|
||||
require.EqualError(t, err, "dashboard does not exist")
|
||||
require.Nil(t, dashboard)
|
||||
|
||||
dashboard, err = resolver.UpdateDashboard(user2, 55, "kek")
|
||||
require.EqualError(t, err, "dashboard does not exist")
|
||||
require.Nil(t, dashboard)
|
||||
|
||||
dashboard, err = resolver.UpdateDashboard(user1, 1, "kek")
|
||||
require.NoError(t, err)
|
||||
|
||||
dashboards, err = resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []*gqlmodel.Dashboard{
|
||||
{
|
||||
ID: 1,
|
||||
Name: "kek",
|
||||
Ranges: []*gqlmodel.NamedDateRange{},
|
||||
Items: []*gqlmodel.DashboardEntry{},
|
||||
},
|
||||
}, dashboards)
|
||||
|
||||
dashboard, err = resolver.RemoveDashboard(user2, 1)
|
||||
require.EqualError(t, err, "dashboard does not exist")
|
||||
require.Nil(t, dashboard)
|
||||
|
||||
dashboard, err = resolver.RemoveDashboard(user2, 55)
|
||||
require.EqualError(t, err, "dashboard does not exist")
|
||||
require.Nil(t, dashboard)
|
||||
|
||||
dashboard, err = resolver.RemoveDashboard(user1, 1)
|
||||
require.NoError(t, err)
|
||||
|
||||
dashboards, err = resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, dashboards)
|
||||
}
|
||||
|
||||
func TestDeleteDashboard(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
|
||||
dbOne := db.User(1).Dashboard("test")
|
||||
dbOne.Range("r")
|
||||
dbOne.Entry("e")
|
||||
dbTwo := db.User(2).Dashboard("test")
|
||||
dbTwo.Range("r")
|
||||
dbTwo.Entry("e")
|
||||
|
||||
resolver := NewResolverForDashboard(db.DB)
|
||||
_, err := resolver.RemoveDashboard(fake.User(dbOne.User.ID), dbOne.Dashboard.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
dbOne.AssertExists(false).AssertHasEntry("e", false).AssertHasRange("r", false)
|
||||
dbTwo.AssertExists(true).AssertHasEntry("e", true).AssertHasRange("r", true)
|
||||
}
|
||||
27
dashboard/dashboardresolver.go
Normal file
27
dashboard/dashboardresolver.go
Normal file
@@ -0,0 +1,27 @@
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/traggo/server/dashboard/dbrange"
|
||||
"github.com/traggo/server/dashboard/entry"
|
||||
)
|
||||
|
||||
// ResolverForDashboard resolves dashboard specific things.
|
||||
type ResolverForDashboard struct {
|
||||
DB *gorm.DB
|
||||
entry.ResolverForEntry
|
||||
dbrange.ResolverForRange
|
||||
}
|
||||
|
||||
// NewResolverForDashboard creates a new resolver.
|
||||
func NewResolverForDashboard(db *gorm.DB) ResolverForDashboard {
|
||||
return ResolverForDashboard{
|
||||
DB: db,
|
||||
ResolverForEntry: entry.ResolverForEntry{
|
||||
DB: db,
|
||||
},
|
||||
ResolverForRange: dbrange.ResolverForRange{
|
||||
DB: db,
|
||||
},
|
||||
}
|
||||
}
|
||||
28
dashboard/dbrange/add.go
Normal file
28
dashboard/dbrange/add.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package dbrange
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/dashboard/convert"
|
||||
"github.com/traggo/server/dashboard/util"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
)
|
||||
|
||||
// AddDashboardRange adds a dashboard range.
|
||||
func (r *ResolverForRange) AddDashboardRange(ctx context.Context, dashboardID int, rangeArg gqlmodel.InputNamedDateRange) (*gqlmodel.NamedDateRange, error) {
|
||||
userID := auth.GetUser(ctx).ID
|
||||
if _, err := util.FindDashboard(r.DB, userID, dashboardID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rangeToAdd, err := convert.ToInternalDashboardRange(rangeArg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rangeToAdd.DashboardID = dashboardID
|
||||
|
||||
save := r.DB.Create(&rangeToAdd)
|
||||
return convert.ToExternalDashboardRange(rangeToAdd), save.Error
|
||||
}
|
||||
8
dashboard/dbrange/dbrangeresolver.go
Normal file
8
dashboard/dbrange/dbrangeresolver.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package dbrange
|
||||
|
||||
import "github.com/jinzhu/gorm"
|
||||
|
||||
// ResolverForRange resolves range specific things.
|
||||
type ResolverForRange struct {
|
||||
DB *gorm.DB
|
||||
}
|
||||
201
dashboard/dbrange/ranges_test.go
Normal file
201
dashboard/dbrange/ranges_test.go
Normal file
@@ -0,0 +1,201 @@
|
||||
package dbrange_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/traggo/server/dashboard"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/test"
|
||||
"github.com/traggo/server/test/fake"
|
||||
)
|
||||
|
||||
func TestRanges(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
|
||||
resolver := dashboard.NewResolverForDashboard(db.DB)
|
||||
|
||||
// initial no dashboards
|
||||
user1 := fake.User(1)
|
||||
user2 := fake.User(2)
|
||||
db.User(1)
|
||||
db.User(2)
|
||||
dashboards, err := resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, dashboards)
|
||||
|
||||
dashboard, err := resolver.CreateDashboard(user1, "cool dashboard")
|
||||
require.NoError(t, err)
|
||||
expectAdded := &gqlmodel.Dashboard{
|
||||
ID: 1,
|
||||
Name: "cool dashboard",
|
||||
Ranges: []*gqlmodel.NamedDateRange{},
|
||||
Items: []*gqlmodel.DashboardEntry{},
|
||||
}
|
||||
require.Equal(t, expectAdded, dashboard)
|
||||
|
||||
dashboards, err = resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []*gqlmodel.Dashboard{expectAdded}, dashboards)
|
||||
|
||||
dashboards, err = resolver.Dashboards(user2)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, dashboards)
|
||||
|
||||
xrange, err := resolver.AddDashboardRange(user1, dashboard.ID, gqlmodel.InputNamedDateRange{
|
||||
Name: "new range",
|
||||
Editable: false,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now-2d",
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, &gqlmodel.NamedDateRange{
|
||||
ID: 1,
|
||||
Name: "new range",
|
||||
Editable: false,
|
||||
Range: &gqlmodel.RelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now-2d",
|
||||
},
|
||||
}, xrange)
|
||||
_, err = resolver.AddDashboardRange(user1, dashboard.ID, gqlmodel.InputNamedDateRange{
|
||||
Name: "new range",
|
||||
Editable: false,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-1",
|
||||
To: "now-2d",
|
||||
},
|
||||
})
|
||||
require.EqualError(t, err, "range from (now-1) invalid: expected unit at the end but got nothing")
|
||||
_, err = resolver.AddDashboardRange(user1, dashboard.ID, gqlmodel.InputNamedDateRange{
|
||||
Name: "new range",
|
||||
Editable: false,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now-2",
|
||||
},
|
||||
})
|
||||
require.EqualError(t, err, "range to (now-2) invalid: expected unit at the end but got nothing")
|
||||
_, err = resolver.AddDashboardRange(user1, 100, gqlmodel.InputNamedDateRange{
|
||||
Name: "new range",
|
||||
Editable: false,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now-2",
|
||||
},
|
||||
})
|
||||
require.EqualError(t, err, "dashboard does not exist")
|
||||
dashboards, err = resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []*gqlmodel.Dashboard{{
|
||||
ID: 1,
|
||||
Name: "cool dashboard",
|
||||
Ranges: []*gqlmodel.NamedDateRange{{
|
||||
ID: 1,
|
||||
Name: "new range",
|
||||
Editable: false,
|
||||
Range: &gqlmodel.RelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now-2d",
|
||||
},
|
||||
}},
|
||||
Items: []*gqlmodel.DashboardEntry{},
|
||||
}}, dashboards)
|
||||
|
||||
_, err = resolver.UpdateDashboardRange(user2, 1, gqlmodel.InputNamedDateRange{
|
||||
Name: "my range",
|
||||
Editable: true,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now-2d/w",
|
||||
},
|
||||
})
|
||||
require.EqualError(t, err, "dashboard does not exist")
|
||||
xrange, err = resolver.UpdateDashboardRange(user1, 1, gqlmodel.InputNamedDateRange{
|
||||
Name: "my range",
|
||||
Editable: true,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now-2d/w",
|
||||
},
|
||||
})
|
||||
require.Equal(t, &gqlmodel.NamedDateRange{
|
||||
ID: 1,
|
||||
Name: "my range",
|
||||
Editable: true,
|
||||
Range: &gqlmodel.RelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now-2d/w",
|
||||
},
|
||||
}, xrange)
|
||||
_, err = resolver.UpdateDashboardRange(user1, 1, gqlmodel.InputNamedDateRange{
|
||||
Name: "my range",
|
||||
Editable: true,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now-2",
|
||||
},
|
||||
})
|
||||
require.EqualError(t, err, "range to (now-2) invalid: expected unit at the end but got nothing")
|
||||
_, err = resolver.UpdateDashboardRange(user1, 44, gqlmodel.InputNamedDateRange{
|
||||
Name: "my range",
|
||||
Editable: true,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now-2",
|
||||
},
|
||||
})
|
||||
require.EqualError(t, err, "dashboard range does not exist")
|
||||
|
||||
entry, err := resolver.AddDashboardEntry(user1, 1, gqlmodel.EntryTypeBarChart, "other", true, gqlmodel.InputStatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"abc"},
|
||||
RangeID: &xrange.ID,
|
||||
}, &gqlmodel.InputResponsiveDashboardEntryPos{Desktop: &gqlmodel.InputDashboardEntryPos{
|
||||
H: 1,
|
||||
W: 2,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
_, err = resolver.RemoveDashboardRange(user1, xrange.ID)
|
||||
require.EqualError(t, err, "range is used in entries: other")
|
||||
_, err = resolver.RemoveDashboardEntry(user1, entry.ID)
|
||||
require.NoError(t, err)
|
||||
|
||||
dashboards, err = resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []*gqlmodel.Dashboard{{
|
||||
ID: 1,
|
||||
Name: "cool dashboard",
|
||||
Ranges: []*gqlmodel.NamedDateRange{{
|
||||
ID: 1,
|
||||
Name: "my range",
|
||||
Editable: true,
|
||||
Range: &gqlmodel.RelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now-2d/w",
|
||||
},
|
||||
}},
|
||||
Items: []*gqlmodel.DashboardEntry{},
|
||||
}}, dashboards)
|
||||
|
||||
_, err = resolver.RemoveDashboardRange(user2, 1)
|
||||
require.EqualError(t, err, "dashboard does not exist")
|
||||
_, err = resolver.RemoveDashboardRange(user2, 55)
|
||||
require.EqualError(t, err, "dashboard range does not exist")
|
||||
|
||||
dashboards, err = resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, dashboards[0].Ranges, 1)
|
||||
|
||||
_, err = resolver.RemoveDashboardRange(user1, 1)
|
||||
require.NoError(t, err)
|
||||
dashboards, err = resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, dashboards[0].Ranges, 0)
|
||||
|
||||
}
|
||||
43
dashboard/dbrange/remove.go
Normal file
43
dashboard/dbrange/remove.go
Normal file
@@ -0,0 +1,43 @@
|
||||
package dbrange
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/dashboard/convert"
|
||||
"github.com/traggo/server/dashboard/util"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// RemoveDashboardRange removes a dashboard range.
|
||||
func (r *ResolverForRange) RemoveDashboardRange(ctx context.Context, rangeID int) (*gqlmodel.NamedDateRange, error) {
|
||||
userID := auth.GetUser(ctx).ID
|
||||
dashboardRange, err := util.FindDashboardRange(r.DB, rangeID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := util.FindDashboard(r.DB, userID, dashboardRange.DashboardID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entries := []model.DashboardEntry{}
|
||||
if err := r.DB.Where(model.DashboardEntry{RangeID: rangeID}).Find(&entries).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
names := []string{}
|
||||
for _, entry := range entries {
|
||||
names = append(names, entry.Title)
|
||||
}
|
||||
|
||||
if len(entries) != 0 {
|
||||
return nil, errors.New("range is used in entries: " + strings.Join(names, ","))
|
||||
}
|
||||
|
||||
remove := r.DB.Delete(&model.DashboardRange{}, rangeID)
|
||||
return convert.ToExternalDashboardRange(dashboardRange), remove.Error
|
||||
}
|
||||
35
dashboard/dbrange/update.go
Normal file
35
dashboard/dbrange/update.go
Normal file
@@ -0,0 +1,35 @@
|
||||
package dbrange
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/dashboard/convert"
|
||||
"github.com/traggo/server/dashboard/util"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
)
|
||||
|
||||
// UpdateDashboardRange updates a dashboard range.
|
||||
func (r *ResolverForRange) UpdateDashboardRange(ctx context.Context, rangeID int, rangeArg gqlmodel.InputNamedDateRange) (*gqlmodel.NamedDateRange, error) {
|
||||
userID := auth.GetUser(ctx).ID
|
||||
|
||||
dashboardRange, err := util.FindDashboardRange(r.DB, rangeID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := util.FindDashboard(r.DB, userID, dashboardRange.DashboardID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rangeToUpdate, err := convert.ToInternalDashboardRange(rangeArg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rangeToUpdate.DashboardID = dashboardRange.DashboardID
|
||||
rangeToUpdate.ID = dashboardRange.ID
|
||||
|
||||
save := r.DB.Save(rangeToUpdate)
|
||||
return convert.ToExternalDashboardRange(rangeToUpdate), save.Error
|
||||
}
|
||||
77
dashboard/entry/add.go
Normal file
77
dashboard/entry/add.go
Normal file
@@ -0,0 +1,77 @@
|
||||
package entry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/traggo/server/time"
|
||||
|
||||
"github.com/traggo/server/dashboard/convert"
|
||||
"github.com/traggo/server/dashboard/util"
|
||||
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// AddDashboardEntry adds a dashboard entry.
|
||||
func (r *ResolverForEntry) AddDashboardEntry(ctx context.Context, dashboardID int, entryType gqlmodel.EntryType, title string, total bool, stats gqlmodel.InputStatsSelection, pos *gqlmodel.InputResponsiveDashboardEntryPos) (*gqlmodel.DashboardEntry, error) {
|
||||
userID := auth.GetUser(ctx).ID
|
||||
|
||||
if _, err := util.FindDashboard(r.DB, userID, dashboardID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tagFilters := convert.TagFiltersToInternal(stats.ExcludeTags, false)
|
||||
tagFilters = append(tagFilters, convert.TagFiltersToInternal(stats.IncludeTags, true)...)
|
||||
|
||||
if err := tagsDuplicates(tagFilters); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
entry := model.DashboardEntry{
|
||||
Keys: strings.Join(stats.Tags, ","),
|
||||
Type: convert.InternalEntryType(entryType),
|
||||
Title: title,
|
||||
Total: total,
|
||||
DashboardID: dashboardID,
|
||||
Interval: convert.InternalInterval(stats.Interval),
|
||||
MobilePosition: convert.EmptyPos(),
|
||||
DesktopPosition: convert.EmptyPos(),
|
||||
RangeID: -1,
|
||||
TagFilters: tagFilters,
|
||||
}
|
||||
|
||||
if len(stats.Tags) == 0 {
|
||||
return nil, errors.New("at least one tag is required")
|
||||
}
|
||||
|
||||
if err := convert.ApplyPos(&entry, pos); err != nil {
|
||||
return &gqlmodel.DashboardEntry{}, err
|
||||
}
|
||||
|
||||
if stats.RangeID != nil {
|
||||
if _, err := util.FindDashboardRange(r.DB, *stats.RangeID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entry.RangeID = *stats.RangeID
|
||||
} else if stats.Range != nil {
|
||||
entry.RangeID = model.NoRangeIDDefined
|
||||
if err := time.Validate(stats.Range.From); err != nil {
|
||||
return nil, fmt.Errorf("range from (%s) invalid: %s", stats.Range.From, err)
|
||||
}
|
||||
if err := time.Validate(stats.Range.To); err != nil {
|
||||
return nil, fmt.Errorf("range to (%s) invalid: %s", stats.Range.To, err)
|
||||
}
|
||||
entry.RangeFrom = stats.Range.From
|
||||
entry.RangeTo = stats.Range.To
|
||||
}
|
||||
|
||||
if err := r.DB.Save(&entry).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return convert.ToExternalEntry(entry)
|
||||
}
|
||||
8
dashboard/entry/dbentryresolver.go
Normal file
8
dashboard/entry/dbentryresolver.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package entry
|
||||
|
||||
import "github.com/jinzhu/gorm"
|
||||
|
||||
// ResolverForEntry resolves dashboard entry things.
|
||||
type ResolverForEntry struct {
|
||||
DB *gorm.DB
|
||||
}
|
||||
526
dashboard/entry/entries_test.go
Normal file
526
dashboard/entry/entries_test.go
Normal file
@@ -0,0 +1,526 @@
|
||||
package entry_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/traggo/server/dashboard"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/test"
|
||||
"github.com/traggo/server/test/fake"
|
||||
)
|
||||
|
||||
func TestEntries(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
var bVal bool
|
||||
|
||||
resolver := dashboard.NewResolverForDashboard(db.DB)
|
||||
|
||||
// initial no dashboards
|
||||
user1 := fake.User(1)
|
||||
user2 := fake.User(2)
|
||||
db.User(1)
|
||||
db.User(2)
|
||||
dashboards, err := resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Empty(t, dashboards)
|
||||
|
||||
dashboard, err := resolver.CreateDashboard(user1, "cool dashboard")
|
||||
require.NoError(t, err)
|
||||
expectAdded := &gqlmodel.Dashboard{
|
||||
ID: 1,
|
||||
Name: "cool dashboard",
|
||||
Ranges: []*gqlmodel.NamedDateRange{},
|
||||
Items: []*gqlmodel.DashboardEntry{},
|
||||
}
|
||||
require.Equal(t, expectAdded, dashboard)
|
||||
|
||||
_, err = resolver.AddDashboardEntry(user1, 5, gqlmodel.EntryTypeBarChart, "test", false, gqlmodel.InputStatsSelection{
|
||||
Interval: "",
|
||||
Tags: []string{"hhol"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: nil,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now-2d",
|
||||
},
|
||||
}, nil)
|
||||
require.EqualError(t, err, "dashboard does not exist")
|
||||
_, err = resolver.AddDashboardEntry(user1, 1, gqlmodel.EntryTypeBarChart, "test", false, gqlmodel.InputStatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalHourly,
|
||||
Tags: []string{"hhol"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: p(55),
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now-2d",
|
||||
},
|
||||
}, nil)
|
||||
require.EqualError(t, err, "dashboard range does not exist")
|
||||
_, err = resolver.AddDashboardEntry(user2, 1, gqlmodel.EntryTypeBarChart, "test", false, gqlmodel.InputStatsSelection{
|
||||
Interval: "doubly",
|
||||
Tags: []string{"hhol"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: nil,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "",
|
||||
To: "",
|
||||
},
|
||||
}, nil)
|
||||
require.EqualError(t, err, "dashboard does not exist")
|
||||
_, err = resolver.AddDashboardEntry(user1, 1, gqlmodel.EntryTypeBarChart, "test", false, gqlmodel.InputStatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"hhol"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: nil,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-2d",
|
||||
To: "now-2",
|
||||
},
|
||||
}, nil)
|
||||
require.EqualError(t, err, "range to (now-2) invalid: expected unit at the end but got nothing")
|
||||
_, err = resolver.AddDashboardEntry(user1, 1, gqlmodel.EntryTypeBarChart, "test", false, gqlmodel.InputStatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"hhol"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: nil,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-2",
|
||||
To: "now-2d",
|
||||
},
|
||||
}, nil)
|
||||
require.EqualError(t, err, "range from (now-2) invalid: expected unit at the end but got nothing")
|
||||
_, err = resolver.AddDashboardEntry(user1, 1, gqlmodel.EntryTypeBarChart, "test", false, gqlmodel.InputStatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: nil,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-2d",
|
||||
To: "now-2d",
|
||||
},
|
||||
}, nil)
|
||||
require.EqualError(t, err, "at least one tag is required")
|
||||
|
||||
entry, err := resolver.AddDashboardEntry(user1, 1, gqlmodel.EntryTypeBarChart, "test", false, gqlmodel.InputStatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"abc"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: nil,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-2d",
|
||||
To: "now-5d",
|
||||
},
|
||||
}, &gqlmodel.InputResponsiveDashboardEntryPos{Desktop: &gqlmodel.InputDashboardEntryPos{
|
||||
H: 1,
|
||||
W: 2,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
expectedEntry := &gqlmodel.DashboardEntry{
|
||||
ID: 1,
|
||||
Title: "test",
|
||||
Total: false,
|
||||
StatsSelection: &gqlmodel.StatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"abc"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: nil,
|
||||
Range: &gqlmodel.RelativeOrStaticRange{
|
||||
From: "now-2d",
|
||||
To: "now-5d",
|
||||
},
|
||||
},
|
||||
Pos: &gqlmodel.ResponsiveDashboardEntryPos{
|
||||
Desktop: &gqlmodel.DashboardEntryPos{
|
||||
W: 2,
|
||||
H: 3,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
MinW: 2,
|
||||
MinH: 3,
|
||||
},
|
||||
Mobile: &gqlmodel.DashboardEntryPos{
|
||||
W: 1,
|
||||
H: 2,
|
||||
X: 0,
|
||||
Y: 0,
|
||||
MinW: 1,
|
||||
MinH: 2,
|
||||
},
|
||||
},
|
||||
EntryType: gqlmodel.EntryTypeBarChart,
|
||||
}
|
||||
require.Equal(t, expectedEntry, entry)
|
||||
|
||||
dashboards, err = resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, dashboards[0].Items, []*gqlmodel.DashboardEntry{expectedEntry})
|
||||
xrange, err := resolver.AddDashboardRange(user1, 1, gqlmodel.InputNamedDateRange{
|
||||
Name: "range",
|
||||
Editable: false,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-1d",
|
||||
To: "now",
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
_, err = resolver.AddDashboardEntry(user1, 1, gqlmodel.EntryTypeBarChart, "other", false, gqlmodel.InputStatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"abc"},
|
||||
RangeID: p(xrange.ID),
|
||||
}, &gqlmodel.InputResponsiveDashboardEntryPos{Desktop: &gqlmodel.InputDashboardEntryPos{
|
||||
H: 1,
|
||||
W: 2,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
_, err = resolver.RemoveDashboardRange(user1, xrange.ID)
|
||||
require.EqualError(t, err, "range is used in entries: other")
|
||||
|
||||
chart := gqlmodel.EntryTypePieChart
|
||||
_, err = resolver.UpdateDashboardEntry(user2, 1, &chart, nil, nil, nil, nil)
|
||||
require.EqualError(t, err, "dashboard does not exist")
|
||||
_, err = resolver.UpdateDashboardEntry(user1, 3, &chart, nil, nil, nil, nil)
|
||||
require.EqualError(t, err, "entry does not exist")
|
||||
_, err = resolver.UpdateDashboardEntry(user1, 1, &chart, s("cool title"), &bVal, &gqlmodel.InputStatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"kek"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: nil,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-2",
|
||||
To: "now-5d",
|
||||
},
|
||||
}, nil)
|
||||
require.EqualError(t, err, "range from (now-2) invalid: expected unit at the end but got nothing")
|
||||
_, err = resolver.UpdateDashboardEntry(user1, 1, &chart, s("cool title"), &bVal, &gqlmodel.InputStatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"kek"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: nil,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-2d",
|
||||
To: "now-5",
|
||||
},
|
||||
}, nil)
|
||||
require.EqualError(t, err, "range to (now-5) invalid: expected unit at the end but got nothing")
|
||||
dashboards, err = resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []*gqlmodel.DashboardEntry{
|
||||
{
|
||||
ID: 1,
|
||||
Title: "test",
|
||||
Total: false,
|
||||
StatsSelection: &gqlmodel.StatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"abc"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: nil,
|
||||
Range: &gqlmodel.RelativeOrStaticRange{
|
||||
From: "now-2d",
|
||||
To: "now-5d",
|
||||
},
|
||||
},
|
||||
Pos: &gqlmodel.ResponsiveDashboardEntryPos{
|
||||
Desktop: &gqlmodel.DashboardEntryPos{
|
||||
W: 2,
|
||||
H: 3,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
MinW: 2,
|
||||
MinH: 3,
|
||||
},
|
||||
Mobile: &gqlmodel.DashboardEntryPos{
|
||||
W: 1,
|
||||
H: 2,
|
||||
X: 0,
|
||||
Y: 0,
|
||||
MinW: 1,
|
||||
MinH: 2,
|
||||
},
|
||||
},
|
||||
EntryType: gqlmodel.EntryTypeBarChart,
|
||||
},
|
||||
{
|
||||
ID: 2,
|
||||
Title: "other",
|
||||
Total: false,
|
||||
StatsSelection: &gqlmodel.StatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"abc"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: p(1),
|
||||
},
|
||||
Pos: &gqlmodel.ResponsiveDashboardEntryPos{
|
||||
Desktop: &gqlmodel.DashboardEntryPos{
|
||||
W: 2,
|
||||
H: 3,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
MinW: 2,
|
||||
MinH: 3,
|
||||
},
|
||||
Mobile: &gqlmodel.DashboardEntryPos{
|
||||
W: 1,
|
||||
H: 2,
|
||||
X: 0,
|
||||
Y: 0,
|
||||
MinW: 1,
|
||||
MinH: 2,
|
||||
},
|
||||
},
|
||||
EntryType: gqlmodel.EntryTypeBarChart,
|
||||
},
|
||||
}, dashboards[0].Items)
|
||||
_, err = resolver.UpdateDashboardEntry(user1, 1, &chart, s("cool title"), &bVal, &gqlmodel.InputStatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"kek"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: nil,
|
||||
Range: &gqlmodel.InputRelativeOrStaticRange{
|
||||
From: "now-2d",
|
||||
To: "now-12d",
|
||||
},
|
||||
}, &gqlmodel.InputResponsiveDashboardEntryPos{Desktop: &gqlmodel.InputDashboardEntryPos{
|
||||
H: 1,
|
||||
W: 2,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
|
||||
dashboards, err = resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []*gqlmodel.DashboardEntry{
|
||||
{
|
||||
ID: 1,
|
||||
Title: "cool title",
|
||||
Total: false,
|
||||
StatsSelection: &gqlmodel.StatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"kek"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: nil,
|
||||
Range: &gqlmodel.RelativeOrStaticRange{
|
||||
From: "now-2d",
|
||||
To: "now-12d",
|
||||
},
|
||||
},
|
||||
Pos: &gqlmodel.ResponsiveDashboardEntryPos{
|
||||
Desktop: &gqlmodel.DashboardEntryPos{
|
||||
W: 2,
|
||||
H: 3,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
MinW: 2,
|
||||
MinH: 3,
|
||||
},
|
||||
Mobile: &gqlmodel.DashboardEntryPos{
|
||||
W: 1,
|
||||
H: 2,
|
||||
X: 0,
|
||||
Y: 0,
|
||||
MinW: 1,
|
||||
MinH: 2,
|
||||
},
|
||||
},
|
||||
EntryType: gqlmodel.EntryTypePieChart,
|
||||
},
|
||||
{
|
||||
ID: 2,
|
||||
Title: "other",
|
||||
Total: false,
|
||||
StatsSelection: &gqlmodel.StatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"abc"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: p(1),
|
||||
},
|
||||
Pos: &gqlmodel.ResponsiveDashboardEntryPos{
|
||||
Desktop: &gqlmodel.DashboardEntryPos{
|
||||
W: 2,
|
||||
H: 3,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
MinW: 2,
|
||||
MinH: 3,
|
||||
},
|
||||
Mobile: &gqlmodel.DashboardEntryPos{
|
||||
W: 1,
|
||||
H: 2,
|
||||
X: 0,
|
||||
Y: 0,
|
||||
MinW: 1,
|
||||
MinH: 2,
|
||||
},
|
||||
},
|
||||
EntryType: gqlmodel.EntryTypeBarChart,
|
||||
},
|
||||
}, dashboards[0].Items)
|
||||
|
||||
_, err = resolver.UpdateDashboardEntry(user1, 1, &chart, s("cool title"), &bVal, &gqlmodel.InputStatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"kek"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: p(5),
|
||||
}, &gqlmodel.InputResponsiveDashboardEntryPos{Desktop: &gqlmodel.InputDashboardEntryPos{
|
||||
H: 1,
|
||||
W: 2,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
}})
|
||||
require.EqualError(t, err, "dashboard range does not exist")
|
||||
|
||||
_, err = resolver.UpdateDashboardEntry(user1, 1, &chart, s("cool title"), &bVal, &gqlmodel.InputStatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"kek"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: p(xrange.ID),
|
||||
}, &gqlmodel.InputResponsiveDashboardEntryPos{Desktop: &gqlmodel.InputDashboardEntryPos{
|
||||
H: 1,
|
||||
W: 2,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
}})
|
||||
require.NoError(t, err)
|
||||
|
||||
dashboards, err = resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []*gqlmodel.DashboardEntry{
|
||||
{
|
||||
ID: 1,
|
||||
Title: "cool title",
|
||||
Total: false,
|
||||
StatsSelection: &gqlmodel.StatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"kek"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: p(xrange.ID),
|
||||
},
|
||||
Pos: &gqlmodel.ResponsiveDashboardEntryPos{
|
||||
Desktop: &gqlmodel.DashboardEntryPos{
|
||||
W: 2,
|
||||
H: 3,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
MinW: 2,
|
||||
MinH: 3,
|
||||
},
|
||||
Mobile: &gqlmodel.DashboardEntryPos{
|
||||
W: 1,
|
||||
H: 2,
|
||||
X: 0,
|
||||
Y: 0,
|
||||
MinW: 1,
|
||||
MinH: 2,
|
||||
},
|
||||
},
|
||||
EntryType: gqlmodel.EntryTypePieChart,
|
||||
},
|
||||
{
|
||||
ID: 2,
|
||||
Title: "other",
|
||||
Total: false,
|
||||
StatsSelection: &gqlmodel.StatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"abc"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: p(1),
|
||||
},
|
||||
Pos: &gqlmodel.ResponsiveDashboardEntryPos{
|
||||
Desktop: &gqlmodel.DashboardEntryPos{
|
||||
W: 2,
|
||||
H: 3,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
MinW: 2,
|
||||
MinH: 3,
|
||||
},
|
||||
Mobile: &gqlmodel.DashboardEntryPos{
|
||||
W: 1,
|
||||
H: 2,
|
||||
X: 0,
|
||||
Y: 0,
|
||||
MinW: 1,
|
||||
MinH: 2,
|
||||
},
|
||||
},
|
||||
EntryType: gqlmodel.EntryTypeBarChart,
|
||||
},
|
||||
}, dashboards[0].Items)
|
||||
|
||||
_, err = resolver.RemoveDashboardEntry(user2, 1)
|
||||
require.EqualError(t, err, "dashboard does not exist")
|
||||
|
||||
_, err = resolver.RemoveDashboardEntry(user1, 55)
|
||||
require.EqualError(t, err, "entry does not exist")
|
||||
|
||||
_, err = resolver.RemoveDashboardEntry(user1, 1)
|
||||
require.NoError(t, err)
|
||||
|
||||
dashboards, err = resolver.Dashboards(user1)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []*gqlmodel.DashboardEntry{
|
||||
{
|
||||
ID: 2,
|
||||
Title: "other",
|
||||
Total: false,
|
||||
StatsSelection: &gqlmodel.StatsSelection{
|
||||
Interval: gqlmodel.StatsIntervalDaily,
|
||||
Tags: []string{"abc"},
|
||||
ExcludeTags: nil,
|
||||
IncludeTags: nil,
|
||||
RangeID: p(1),
|
||||
},
|
||||
Pos: &gqlmodel.ResponsiveDashboardEntryPos{
|
||||
Desktop: &gqlmodel.DashboardEntryPos{
|
||||
W: 2,
|
||||
H: 3,
|
||||
X: 1,
|
||||
Y: 3,
|
||||
MinW: 2,
|
||||
MinH: 3,
|
||||
},
|
||||
Mobile: &gqlmodel.DashboardEntryPos{
|
||||
W: 1,
|
||||
H: 2,
|
||||
X: 0,
|
||||
Y: 0,
|
||||
MinW: 1,
|
||||
MinH: 2,
|
||||
},
|
||||
},
|
||||
EntryType: gqlmodel.EntryTypeBarChart,
|
||||
},
|
||||
}, dashboards[0].Items)
|
||||
}
|
||||
|
||||
func p(i int) *int {
|
||||
return &i
|
||||
}
|
||||
func s(s string) *string {
|
||||
return &s
|
||||
}
|
||||
34
dashboard/entry/remove.go
Normal file
34
dashboard/entry/remove.go
Normal file
@@ -0,0 +1,34 @@
|
||||
package entry
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/traggo/server/dashboard/convert"
|
||||
"github.com/traggo/server/dashboard/util"
|
||||
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// RemoveDashboardEntry removes a dashboard entry.
|
||||
func (r *ResolverForEntry) RemoveDashboardEntry(ctx context.Context, id int) (*gqlmodel.DashboardEntry, error) {
|
||||
|
||||
userID := auth.GetUser(ctx).ID
|
||||
|
||||
entry, err := util.FindDashboardEntry(r.DB, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := util.FindDashboard(r.DB, userID, entry.DashboardID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
remove := r.DB.Delete(&model.DashboardEntry{}, id)
|
||||
if remove.Error != nil {
|
||||
return &gqlmodel.DashboardEntry{}, remove.Error
|
||||
}
|
||||
|
||||
return convert.ToExternalEntry(entry)
|
||||
}
|
||||
33
dashboard/entry/tagcheck.go
Normal file
33
dashboard/entry/tagcheck.go
Normal file
@@ -0,0 +1,33 @@
|
||||
package entry
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
func tagsDuplicates(tags []model.DashboardTagFilter) error {
|
||||
existingTags := make(map[model.DashboardTagFilter]struct{})
|
||||
|
||||
for _, tag := range tags {
|
||||
if _, ok := existingTags[tag]; ok {
|
||||
tagType := "exclude"
|
||||
if tag.Include {
|
||||
tagType = "include"
|
||||
}
|
||||
|
||||
return fmt.Errorf("%s tags: tag '%s' is present multiple times", tagType, tag.Key+":"+tag.StringValue)
|
||||
} else {
|
||||
copyTag := tag
|
||||
copyTag.Include = !copyTag.Include
|
||||
|
||||
if _, ok := existingTags[copyTag]; ok {
|
||||
return fmt.Errorf("tag '%s' is present in both exclude tags and include tags", tag.Key+":"+tag.StringValue)
|
||||
}
|
||||
}
|
||||
|
||||
existingTags[tag] = struct{}{}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
104
dashboard/entry/update.go
Normal file
104
dashboard/entry/update.go
Normal file
@@ -0,0 +1,104 @@
|
||||
package entry
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/traggo/server/time"
|
||||
|
||||
"github.com/traggo/server/model"
|
||||
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/dashboard/convert"
|
||||
"github.com/traggo/server/dashboard/util"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
)
|
||||
|
||||
// UpdateDashboardEntry updates a dashboard entry.
|
||||
func (r *ResolverForEntry) UpdateDashboardEntry(ctx context.Context, id int, entryType *gqlmodel.EntryType, title *string, total *bool, stats *gqlmodel.InputStatsSelection, pos *gqlmodel.InputResponsiveDashboardEntryPos) (*gqlmodel.DashboardEntry, error) {
|
||||
userID := auth.GetUser(ctx).ID
|
||||
|
||||
entry, err := util.FindDashboardEntry(r.DB, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if _, err := util.FindDashboard(r.DB, userID, entry.DashboardID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if title != nil {
|
||||
entry.Title = *title
|
||||
}
|
||||
|
||||
if total != nil {
|
||||
entry.Total = *total
|
||||
}
|
||||
|
||||
tx := r.DB.Begin()
|
||||
if err := tx.Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
tx.Rollback()
|
||||
panic(r)
|
||||
} else if tx != nil {
|
||||
tx.Rollback()
|
||||
}
|
||||
}()
|
||||
|
||||
if stats != nil {
|
||||
if stats.RangeID != nil {
|
||||
if _, err := util.FindDashboardRange(tx, *stats.RangeID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
entry.RangeID = *stats.RangeID
|
||||
} else if stats.Range != nil {
|
||||
entry.RangeID = model.NoRangeIDDefined
|
||||
if err := time.Validate(stats.Range.From); err != nil {
|
||||
return nil, fmt.Errorf("range from (%s) invalid: %s", stats.Range.From, err)
|
||||
}
|
||||
if err := time.Validate(stats.Range.To); err != nil {
|
||||
return nil, fmt.Errorf("range to (%s) invalid: %s", stats.Range.To, err)
|
||||
}
|
||||
entry.RangeFrom = stats.Range.From
|
||||
entry.RangeTo = stats.Range.To
|
||||
}
|
||||
|
||||
tagFilters := convert.TagFiltersToInternal(stats.ExcludeTags, false)
|
||||
tagFilters = append(tagFilters, convert.TagFiltersToInternal(stats.IncludeTags, true)...)
|
||||
|
||||
if err := tagsDuplicates(tagFilters); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.Where("dashboard_entry_id = ?", id).Delete(new(model.DashboardTagFilter)).Error; err != nil {
|
||||
return nil, fmt.Errorf("failed to update tag filters: %s", err)
|
||||
}
|
||||
|
||||
entry.TagFilters = tagFilters
|
||||
entry.Keys = strings.Join(stats.Tags, ",")
|
||||
entry.Interval = convert.InternalInterval(stats.Interval)
|
||||
}
|
||||
|
||||
if entryType != nil {
|
||||
entry.Type = convert.InternalEntryType(*entryType)
|
||||
}
|
||||
|
||||
if err := convert.ApplyPos(&entry, pos); err != nil {
|
||||
return &gqlmodel.DashboardEntry{}, err
|
||||
}
|
||||
|
||||
if err := tx.Save(entry).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := tx.Commit().Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tx = nil
|
||||
return convert.ToExternalEntry(entry)
|
||||
}
|
||||
31
dashboard/get.go
Normal file
31
dashboard/get.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/traggo/server/dashboard/convert"
|
||||
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// Dashboards returns all dashboards.
|
||||
func (r *ResolverForDashboard) Dashboards(ctx context.Context) ([]*gqlmodel.Dashboard, error) {
|
||||
userID := auth.GetUser(ctx).ID
|
||||
|
||||
dashboards := []model.Dashboard{}
|
||||
|
||||
q := r.DB
|
||||
q = q.Preload("Entries")
|
||||
q = q.Preload("Entries.TagFilters")
|
||||
q = q.Preload("Ranges")
|
||||
|
||||
find := q.Where(&model.Dashboard{UserID: userID}).Find(&dashboards)
|
||||
|
||||
if find.Error != nil {
|
||||
return nil, find.Error
|
||||
}
|
||||
|
||||
return convert.ToExternalDashboards(dashboards)
|
||||
}
|
||||
28
dashboard/remove.go
Normal file
28
dashboard/remove.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/traggo/server/dashboard/convert"
|
||||
"github.com/traggo/server/dashboard/util"
|
||||
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// RemoveDashboard removes a dashboard.
|
||||
func (r *ResolverForDashboard) RemoveDashboard(ctx context.Context, id int) (*gqlmodel.Dashboard, error) {
|
||||
userID := auth.GetUser(ctx).ID
|
||||
|
||||
dashboard, err := util.FindDashboard(r.DB, userID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if err := r.DB.Where(&model.Dashboard{UserID: userID, ID: id}).Delete(&model.Dashboard{}).Error; err != nil {
|
||||
return &gqlmodel.Dashboard{}, err
|
||||
}
|
||||
|
||||
return convert.ToExternalDashboard(dashboard)
|
||||
}
|
||||
45
dashboard/update.go
Normal file
45
dashboard/update.go
Normal file
@@ -0,0 +1,45 @@
|
||||
package dashboard
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/traggo/server/dashboard/convert"
|
||||
|
||||
"github.com/traggo/server/dashboard/util"
|
||||
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// UpdateDashboard updates a dashboard.
|
||||
func (r *ResolverForDashboard) UpdateDashboard(ctx context.Context, id int, name string) (*gqlmodel.Dashboard, error) {
|
||||
userID := auth.GetUser(ctx).ID
|
||||
|
||||
dashboard, err := util.FindDashboard(r.DB, userID, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
dashboard.Name = name
|
||||
|
||||
save := r.DB.Save(dashboard)
|
||||
|
||||
if save.Error != nil {
|
||||
return nil, save.Error
|
||||
}
|
||||
|
||||
var entries []model.DashboardEntry
|
||||
if err := r.DB.Where(&model.DashboardEntry{DashboardID: dashboard.ID}).Find(&entries).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dashboard.Entries = entries
|
||||
|
||||
var ranges []model.DashboardRange
|
||||
if err := r.DB.Where(&model.DashboardRange{DashboardID: dashboard.ID}).Find(&ranges).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dashboard.Ranges = ranges
|
||||
|
||||
return convert.ToExternalDashboard(dashboard)
|
||||
}
|
||||
41
dashboard/util/dashboard.go
Normal file
41
dashboard/util/dashboard.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package util
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// FindDashboard finds a dashboard.
|
||||
func FindDashboard(db *gorm.DB, userID, dashboardID int) (model.Dashboard, error) {
|
||||
dashboard := model.Dashboard{}
|
||||
find := db.Where(&model.Dashboard{UserID: userID, ID: dashboardID}).Find(&dashboard)
|
||||
if find.RecordNotFound() {
|
||||
return dashboard, errors.New("dashboard does not exist")
|
||||
}
|
||||
|
||||
return dashboard, find.Error
|
||||
}
|
||||
|
||||
// FindDashboardRange finds a dashboard range.
|
||||
func FindDashboardRange(db *gorm.DB, rangeID int) (model.DashboardRange, error) {
|
||||
dashboardRange := model.DashboardRange{}
|
||||
find := db.Where(&model.DashboardRange{ID: rangeID}).Find(&dashboardRange)
|
||||
if find.RecordNotFound() {
|
||||
return dashboardRange, errors.New("dashboard range does not exist")
|
||||
}
|
||||
|
||||
return dashboardRange, find.Error
|
||||
}
|
||||
|
||||
// FindDashboardEntry finds a dashboard entry.
|
||||
func FindDashboardEntry(db *gorm.DB, entryID int) (model.DashboardEntry, error) {
|
||||
dashboardEntry := model.DashboardEntry{}
|
||||
find := db.Where(&model.DashboardEntry{ID: entryID}).Find(&dashboardEntry)
|
||||
if find.RecordNotFound() {
|
||||
return dashboardEntry, errors.New("entry does not exist")
|
||||
}
|
||||
|
||||
return dashboardEntry, find.Error
|
||||
}
|
||||
57
database/database.go
Normal file
57
database/database.go
Normal file
@@ -0,0 +1,57 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
_ "github.com/jinzhu/gorm/dialects/mysql" // enable the mysql dialect
|
||||
_ "github.com/jinzhu/gorm/dialects/postgres" // enable the postgres dialect
|
||||
_ "github.com/jinzhu/gorm/dialects/sqlite" // enable the sqlite3 dialect
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traggo/server/logger"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
var mkdirAll = os.MkdirAll
|
||||
|
||||
// New creates a gorm instance.
|
||||
func New(dialect, connection string) (*gorm.DB, error) {
|
||||
createDirectoryIfSqlite(dialect, connection)
|
||||
|
||||
db, err := gorm.Open(dialect, connection)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
db.LogMode(true)
|
||||
db.SetLogger(&logger.DatabaseLogger{})
|
||||
|
||||
// We normally don't need that much connections, so we limit them. F.ex. mysql complains about
|
||||
// "too many connections".
|
||||
db.DB().SetMaxOpenConns(10)
|
||||
|
||||
if dialect == "sqlite3" {
|
||||
// We use the database connection inside the handlers from the http
|
||||
// framework, therefore concurrent access occurs. Sqlite cannot handle
|
||||
// concurrent writes, so we limit sqlite to one connection.
|
||||
// see https://github.com/mattn/go-sqlite3/issues/274
|
||||
db.DB().SetMaxOpenConns(1)
|
||||
db.Exec("PRAGMA foreign_keys = ON")
|
||||
}
|
||||
|
||||
log.Debug().Msg("Auto migrating schema's")
|
||||
db.AutoMigrate(model.All()...)
|
||||
|
||||
log.Debug().Msg("Database initialized")
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func createDirectoryIfSqlite(dialect string, connection string) {
|
||||
if dialect == "sqlite3" {
|
||||
if _, err := os.Stat(filepath.Dir(connection)); os.IsNotExist(err) {
|
||||
if err := mkdirAll(filepath.Dir(connection), 0777); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
56
database/database_test.go
Normal file
56
database/database_test.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/traggo/server/logger"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
logger.Init(zerolog.WarnLevel)
|
||||
os.Exit(m.Run())
|
||||
}
|
||||
|
||||
func TestInvalidDialect(t *testing.T) {
|
||||
_, err := New("asdf", "testdb.db")
|
||||
assert.NotNil(t, err)
|
||||
}
|
||||
|
||||
func TestCreateSqliteFolder(t *testing.T) {
|
||||
// ensure path not exists
|
||||
os.RemoveAll("somepath")
|
||||
|
||||
db, err := New("sqlite3", "somepath/testdb.db")
|
||||
assert.Nil(t, err)
|
||||
assert.DirExists(t, "somepath")
|
||||
db.Close()
|
||||
|
||||
assert.Nil(t, os.RemoveAll("somepath"))
|
||||
}
|
||||
|
||||
func TestWithAlreadyExistingSqliteFolder(t *testing.T) {
|
||||
// ensure path not exists
|
||||
os.RemoveAll("somepath")
|
||||
os.MkdirAll("somepath", 0777)
|
||||
|
||||
db, err := New("sqlite3", "somepath/testdb.db")
|
||||
assert.Nil(t, err)
|
||||
assert.DirExists(t, "somepath")
|
||||
db.Close()
|
||||
|
||||
assert.Nil(t, os.RemoveAll("somepath"))
|
||||
}
|
||||
|
||||
func TestPanicsOnMkdirError(t *testing.T) {
|
||||
os.RemoveAll("somepath")
|
||||
mkdirAll = func(path string, perm os.FileMode) error {
|
||||
return errors.New("ERROR")
|
||||
}
|
||||
assert.Panics(t, func() {
|
||||
New("sqlite3", "somepath/test.db")
|
||||
})
|
||||
}
|
||||
83
device/create.go
Normal file
83
device/create.go
Normal file
@@ -0,0 +1,83 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/jinzhu/copier"
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/auth/rand"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/user/password"
|
||||
)
|
||||
|
||||
var (
|
||||
timeNow = time.Now
|
||||
randToken = rand.Token
|
||||
comparePassword = password.ComparePassword
|
||||
errUserPassWrong = errors.New("username/password combination does not exist")
|
||||
)
|
||||
|
||||
// Login creates a device.
|
||||
func (r *ResolverForDevice) Login(ctx context.Context, username string, pass string, deviceName string, deviceType gqlmodel.DeviceType, cookie bool) (*gqlmodel.Login, error) {
|
||||
|
||||
user := new(model.User)
|
||||
find := r.DB.Where("name = ?", username).Find(user)
|
||||
|
||||
if find.RecordNotFound() {
|
||||
return nil, errUserPassWrong
|
||||
}
|
||||
|
||||
if !comparePassword(user.Pass, []byte(pass)) {
|
||||
return nil, errUserPassWrong
|
||||
}
|
||||
|
||||
return r.createDeviceInternal(ctx, user, deviceName, deviceType, cookie)
|
||||
}
|
||||
|
||||
// CreateDevice creates a device.
|
||||
func (r *ResolverForDevice) CreateDevice(ctx context.Context, deviceName string, deviceType gqlmodel.DeviceType) (*gqlmodel.Login, error) {
|
||||
|
||||
user := auth.GetUser(ctx)
|
||||
|
||||
return r.createDeviceInternal(ctx, user, deviceName, deviceType, false)
|
||||
}
|
||||
|
||||
func (r *ResolverForDevice) createDeviceInternal(ctx context.Context, user *model.User, deviceName string, deviceType gqlmodel.DeviceType, cookie bool) (*gqlmodel.Login, error) {
|
||||
|
||||
token := randToken(20)
|
||||
for !r.DB.Where("token = ?", token).Find(new(model.Device)).RecordNotFound() {
|
||||
token = randToken(20)
|
||||
}
|
||||
|
||||
now := timeNow()
|
||||
device := &model.Device{
|
||||
Token: token,
|
||||
UserID: user.ID,
|
||||
Name: deviceName,
|
||||
Type: model.DeviceType(deviceType),
|
||||
CreatedAt: now.UTC(),
|
||||
ActiveAt: now.UTC(),
|
||||
}
|
||||
|
||||
if err := device.Type.Valid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if cookie {
|
||||
auth.GetCreateSession(ctx)(token, device.Type.Seconds())
|
||||
}
|
||||
|
||||
create := r.DB.Create(device)
|
||||
|
||||
gqlUser := &gqlmodel.User{}
|
||||
copier.Copy(gqlUser, user)
|
||||
gqlDevice := &gqlmodel.Device{}
|
||||
copier.Copy(gqlDevice, device)
|
||||
return &gqlmodel.Login{
|
||||
User: gqlUser,
|
||||
Device: gqlDevice,
|
||||
Token: token}, create.Error
|
||||
}
|
||||
271
device/create_test.go
Normal file
271
device/create_test.go
Normal file
@@ -0,0 +1,271 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/test"
|
||||
)
|
||||
|
||||
var (
|
||||
existingPassword = []byte{1}
|
||||
)
|
||||
|
||||
func TestGQL_Login_fails_userDoesNotExist(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
|
||||
now := test.Time("2018-06-30T18:30:00+02:00")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
login, err := resolver.Login(
|
||||
context.Background(),
|
||||
"jmattheis",
|
||||
"123",
|
||||
"test",
|
||||
gqlmodel.DeviceTypeLongExpiry,
|
||||
false)
|
||||
|
||||
assert.Nil(t, login)
|
||||
assert.Equal(t, errUserPassWrong, err)
|
||||
assertDeviceCount(t, db, 0)
|
||||
}
|
||||
|
||||
func TestGQL_Login_fails_wrongPass(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.Create(&model.User{
|
||||
Name: "jmattheis",
|
||||
ID: 1,
|
||||
Pass: existingPassword,
|
||||
})
|
||||
pwDispose := fakePassword()
|
||||
defer pwDispose()
|
||||
|
||||
now := test.Time("2018-06-30T18:30:00+02:00")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
login, err := resolver.Login(
|
||||
context.Background(),
|
||||
"jmattheis",
|
||||
"123",
|
||||
"test",
|
||||
gqlmodel.DeviceTypeLongExpiry,
|
||||
false)
|
||||
|
||||
assert.Nil(t, login)
|
||||
assert.Equal(t, errUserPassWrong, err)
|
||||
assertDeviceCount(t, db, 0)
|
||||
}
|
||||
|
||||
func TestGQL_Login_succeeds(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.Create(&model.User{
|
||||
Name: "jmattheis",
|
||||
ID: 1,
|
||||
Pass: existingPassword,
|
||||
})
|
||||
pwDispose := fakePassword()
|
||||
defer pwDispose()
|
||||
|
||||
tokenDispose := fakeToken("firstToken")
|
||||
defer tokenDispose()
|
||||
|
||||
now := test.Time("2018-06-30T18:30:00+02:00")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
login, err := resolver.Login(
|
||||
context.Background(),
|
||||
"jmattheis",
|
||||
"unicorn",
|
||||
"test",
|
||||
gqlmodel.DeviceTypeLongExpiry,
|
||||
false)
|
||||
|
||||
assert.Nil(t, err)
|
||||
|
||||
expected := &gqlmodel.Login{
|
||||
Token: "firstToken",
|
||||
User: &gqlmodel.User{Admin: false, ID: 1, Name: "jmattheis"},
|
||||
Device: &gqlmodel.Device{
|
||||
ID: 1,
|
||||
Name: "test",
|
||||
Type: gqlmodel.DeviceTypeLongExpiry,
|
||||
CreatedAt: model.Time(now.UTC()),
|
||||
ActiveAt: model.Time(now.UTC()),
|
||||
},
|
||||
}
|
||||
assert.Equal(t, expected, login)
|
||||
assertDeviceCount(t, db, 1)
|
||||
}
|
||||
|
||||
func TestGQL_CreateDevice_succeeds(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
user := &model.User{
|
||||
Name: "jmattheis",
|
||||
ID: 1,
|
||||
Pass: existingPassword,
|
||||
}
|
||||
db.Create(user)
|
||||
pwDispose := fakePassword()
|
||||
defer pwDispose()
|
||||
|
||||
tokenDispose := fakeToken("firstToken")
|
||||
defer tokenDispose()
|
||||
|
||||
now := test.Time("2018-06-30T18:30:00+02:00")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
login, err := resolver.CreateDevice(
|
||||
auth.WithUser(context.Background(), user),
|
||||
"test",
|
||||
gqlmodel.DeviceTypeLongExpiry)
|
||||
|
||||
assert.Nil(t, err)
|
||||
|
||||
expected := &gqlmodel.Login{
|
||||
Token: "firstToken",
|
||||
User: &gqlmodel.User{Admin: false, ID: 1, Name: "jmattheis"},
|
||||
Device: &gqlmodel.Device{
|
||||
ID: 1,
|
||||
Name: "test",
|
||||
Type: gqlmodel.DeviceTypeLongExpiry,
|
||||
CreatedAt: model.Time(now.UTC()),
|
||||
ActiveAt: model.Time(now.UTC()),
|
||||
},
|
||||
}
|
||||
assert.Equal(t, expected, login)
|
||||
assertDeviceCount(t, db, 1)
|
||||
}
|
||||
|
||||
func TestGQL_Login_setsCookie(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.Create(&model.User{
|
||||
Name: "jmattheis",
|
||||
ID: 1,
|
||||
Pass: existingPassword,
|
||||
})
|
||||
pwDispose := fakePassword()
|
||||
defer pwDispose()
|
||||
|
||||
tokenDispose := fakeToken("firstToken")
|
||||
defer tokenDispose()
|
||||
|
||||
now := test.Time("2018-06-30T18:30:00+02:00")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
|
||||
createSessionToken := ""
|
||||
createSessionAge := 0
|
||||
|
||||
_, err := resolver.Login(
|
||||
auth.WithCreateSession(context.Background(), func(token string, age int) {
|
||||
createSessionToken = token
|
||||
createSessionAge = age
|
||||
}),
|
||||
"jmattheis",
|
||||
"unicorn",
|
||||
"test",
|
||||
gqlmodel.DeviceTypeShortExpiry,
|
||||
true)
|
||||
|
||||
assert.Nil(t, err)
|
||||
|
||||
assert.Equal(t, "firstToken", createSessionToken)
|
||||
assert.Equal(t, 60*60, createSessionAge)
|
||||
assertDeviceCount(t, db, 1)
|
||||
}
|
||||
|
||||
func TestGQL_Login_succeeds_withExistingToken(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.Create(&model.User{
|
||||
Name: "jmattheis",
|
||||
ID: 1,
|
||||
Pass: existingPassword,
|
||||
})
|
||||
db.Create(&model.Device{
|
||||
Name: "test",
|
||||
ID: 1,
|
||||
Token: "firstToken",
|
||||
UserID: 1,
|
||||
})
|
||||
pwDispose := fakePassword()
|
||||
defer pwDispose()
|
||||
|
||||
tokenDispose := fakeToken("firstToken", "secondToken")
|
||||
defer tokenDispose()
|
||||
|
||||
now := test.Time("2018-06-30T18:30:00+02:00")
|
||||
timeDispose := fakeTime(now)
|
||||
defer timeDispose()
|
||||
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
login, err := resolver.Login(
|
||||
context.Background(),
|
||||
"jmattheis",
|
||||
"unicorn",
|
||||
"test",
|
||||
gqlmodel.DeviceTypeShortExpiry,
|
||||
false)
|
||||
|
||||
assert.Nil(t, err)
|
||||
|
||||
assert.Equal(t, "secondToken", login.Token)
|
||||
assertDeviceCount(t, db, 2)
|
||||
}
|
||||
|
||||
func fakePassword() func() {
|
||||
old := comparePassword
|
||||
comparePassword = func(hashedPassword, password []byte) bool {
|
||||
return bytes.Equal(password, []byte("unicorn")) && bytes.Equal(hashedPassword, existingPassword)
|
||||
}
|
||||
return func() {
|
||||
comparePassword = old
|
||||
}
|
||||
}
|
||||
|
||||
func fakeTime(t time.Time) func() {
|
||||
old := timeNow
|
||||
timeNow = func() time.Time {
|
||||
return t
|
||||
}
|
||||
return func() {
|
||||
timeNow = old
|
||||
}
|
||||
}
|
||||
|
||||
func fakeToken(token ...string) func() {
|
||||
old := randToken
|
||||
remaining := token
|
||||
randToken = func(n int) string {
|
||||
if len(remaining) > 0 {
|
||||
used := remaining[0]
|
||||
remaining = remaining[1:]
|
||||
return used
|
||||
}
|
||||
panic("oops no token specified")
|
||||
}
|
||||
return func() {
|
||||
randToken = old
|
||||
}
|
||||
}
|
||||
20
device/current.go
Normal file
20
device/current.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jinzhu/copier"
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
)
|
||||
|
||||
// CurrentDevice returns the current device.
|
||||
func (r *ResolverForDevice) CurrentDevice(ctx context.Context) (*gqlmodel.Device, error) {
|
||||
device := auth.GetDevice(ctx)
|
||||
if device == nil {
|
||||
return nil, nil
|
||||
}
|
||||
var result gqlmodel.Device
|
||||
copier.Copy(&result, device)
|
||||
return &result, nil
|
||||
}
|
||||
53
device/current_test.go
Normal file
53
device/current_test.go
Normal file
@@ -0,0 +1,53 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/test"
|
||||
"github.com/traggo/server/test/fake"
|
||||
)
|
||||
|
||||
func TestGQL_CurrentDevice_withDevice(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
|
||||
device := &model.Device{
|
||||
ID: 2,
|
||||
Name: "Browser",
|
||||
Token: "abcd",
|
||||
UserID: 2,
|
||||
CreatedAt: test.Time("2004-06-30T18:30:00Z"),
|
||||
ActiveAt: test.Time("2015-06-30T18:30:00Z"),
|
||||
Type: model.TypeNoExpiry,
|
||||
}
|
||||
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
result, err := resolver.CurrentDevice(fake.Device(device))
|
||||
|
||||
require.Nil(t, err)
|
||||
expected := &gqlmodel.Device{
|
||||
ID: 2,
|
||||
Name: "Browser",
|
||||
CreatedAt: test.ModelTimeUTC("2004-06-30T18:30:00Z"),
|
||||
ActiveAt: test.ModelTimeUTC("2015-06-30T18:30:00Z"),
|
||||
Type: gqlmodel.DeviceTypeNoExpiry,
|
||||
}
|
||||
|
||||
require.Equal(t, expected, result)
|
||||
}
|
||||
|
||||
func TestGQL_CurrentDevice_noDevice(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
result, err := resolver.CurrentDevice(context.Background())
|
||||
|
||||
require.Nil(t, err)
|
||||
|
||||
require.Nil(t, result)
|
||||
}
|
||||
8
device/deviceresolver.go
Normal file
8
device/deviceresolver.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package device
|
||||
|
||||
import "github.com/jinzhu/gorm"
|
||||
|
||||
// ResolverForDevice resolves device specific things.
|
||||
type ResolverForDevice struct {
|
||||
DB *gorm.DB
|
||||
}
|
||||
20
device/get.go
Normal file
20
device/get.go
Normal file
@@ -0,0 +1,20 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jinzhu/copier"
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// Devices returns all devices.
|
||||
func (r *ResolverForDevice) Devices(ctx context.Context) ([]*gqlmodel.Device, error) {
|
||||
user := auth.GetUser(ctx)
|
||||
var devices []model.Device
|
||||
find := r.DB.Where(&model.Device{UserID: user.ID}).Order("active_at DESC").Find(&devices)
|
||||
var result []*gqlmodel.Device
|
||||
copier.Copy(&result, &devices)
|
||||
return result, find.Error
|
||||
}
|
||||
51
device/get_test.go
Normal file
51
device/get_test.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/test"
|
||||
"github.com/traggo/server/test/fake"
|
||||
)
|
||||
|
||||
func TestGQL_Devices(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.User(1)
|
||||
db.User(2)
|
||||
db.Create(&model.Device{
|
||||
ID: 1,
|
||||
Name: "Android",
|
||||
Token: "abc",
|
||||
UserID: 1,
|
||||
CreatedAt: test.Time("2009-06-30T18:30:00Z"),
|
||||
ActiveAt: test.Time("2018-06-30T18:30:00Z"),
|
||||
Type: model.TypeNoExpiry,
|
||||
})
|
||||
db.Create(&model.Device{
|
||||
ID: 2,
|
||||
Name: "Browser",
|
||||
Token: "abcd",
|
||||
UserID: 2,
|
||||
CreatedAt: test.Time("2004-06-30T18:30:00Z"),
|
||||
ActiveAt: test.Time("2015-06-30T18:30:00Z"),
|
||||
Type: model.TypeNoExpiry,
|
||||
})
|
||||
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
devices, err := resolver.Devices(fake.User(1))
|
||||
|
||||
require.Nil(t, err)
|
||||
expected := []*gqlmodel.Device{
|
||||
{
|
||||
ID: 1,
|
||||
Name: "Android",
|
||||
CreatedAt: test.ModelTimeUTC("2009-06-30T18:30:00Z"),
|
||||
ActiveAt: test.ModelTimeUTC("2018-06-30T18:30:00Z"),
|
||||
Type: gqlmodel.DeviceTypeNoExpiry,
|
||||
},
|
||||
}
|
||||
require.Equal(t, expected, devices)
|
||||
}
|
||||
24
device/remove.go
Normal file
24
device/remove.go
Normal file
@@ -0,0 +1,24 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jinzhu/copier"
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// RemoveDevice removes a device
|
||||
func (r *ResolverForDevice) RemoveDevice(ctx context.Context, id int) (*gqlmodel.Device, error) {
|
||||
device := model.Device{ID: id}
|
||||
if r.DB.Where(&model.Device{UserID: auth.GetUser(ctx).ID}).Find(&device).RecordNotFound() {
|
||||
return nil, fmt.Errorf("device not found")
|
||||
}
|
||||
|
||||
remove := r.DB.Delete(&device)
|
||||
gqlDevice := &gqlmodel.Device{}
|
||||
copier.Copy(gqlDevice, &device)
|
||||
return gqlDevice, remove.Error
|
||||
}
|
||||
18
device/remove_current.go
Normal file
18
device/remove_current.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jinzhu/copier"
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
)
|
||||
|
||||
// RemoveCurrentDevice removes the current authenticated device
|
||||
func (r *ResolverForDevice) RemoveCurrentDevice(ctx context.Context) (*gqlmodel.Device, error) {
|
||||
device := auth.GetDevice(ctx)
|
||||
remove := r.DB.Delete(device)
|
||||
gqlDevice := &gqlmodel.Device{}
|
||||
copier.Copy(gqlDevice, device)
|
||||
return gqlDevice, remove.Error
|
||||
}
|
||||
41
device/remove_current_test.go
Normal file
41
device/remove_current_test.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/test"
|
||||
"github.com/traggo/server/test/fake"
|
||||
)
|
||||
|
||||
func TestGQL_RemoveCurrentDevice_succeeds_removesDevice(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.User(1)
|
||||
device := &model.Device{
|
||||
ID: 55,
|
||||
Name: "Android",
|
||||
Token: "abc",
|
||||
UserID: 1,
|
||||
CreatedAt: test.Time("2009-06-30T18:30:00Z"),
|
||||
ActiveAt: test.Time("2018-06-30T18:30:00Z"),
|
||||
Type: model.TypeNoExpiry,
|
||||
}
|
||||
db.Create(device)
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
gqlDevice, err := resolver.RemoveCurrentDevice(fake.Device(device))
|
||||
require.Nil(t, err)
|
||||
|
||||
expected := &gqlmodel.Device{
|
||||
ID: 55,
|
||||
Name: "Android",
|
||||
CreatedAt: test.ModelTimeUTC("2009-06-30T18:30:00Z"),
|
||||
ActiveAt: test.ModelTimeUTC("2018-06-30T18:30:00Z"),
|
||||
Type: gqlmodel.DeviceTypeNoExpiry,
|
||||
}
|
||||
|
||||
require.Equal(t, expected, gqlDevice)
|
||||
assertDeviceCount(t, db, 0)
|
||||
}
|
||||
58
device/remove_test.go
Normal file
58
device/remove_test.go
Normal file
@@ -0,0 +1,58 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/test"
|
||||
"github.com/traggo/server/test/fake"
|
||||
)
|
||||
|
||||
func TestGQL_RemoveDevice_succeeds_removesDevice(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.User(1)
|
||||
db.Create(&model.Device{
|
||||
ID: 55,
|
||||
Name: "Android",
|
||||
Token: "abc",
|
||||
UserID: 1,
|
||||
CreatedAt: test.Time("2009-06-30T18:30:00+02:00"),
|
||||
ActiveAt: test.Time("2018-06-30T18:30:00+02:00"),
|
||||
Type: model.TypeNoExpiry,
|
||||
})
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
_, err := resolver.RemoveDevice(fake.User(1), 55)
|
||||
require.Nil(t, err)
|
||||
assertDeviceCount(t, db, 0)
|
||||
}
|
||||
|
||||
func TestGQL_RemoveDevice_fails_notExistingDevice(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.User(1)
|
||||
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
_, err := resolver.RemoveDevice(fake.User(1), 55)
|
||||
require.EqualError(t, err, "device not found")
|
||||
}
|
||||
|
||||
func TestGQL_RemoveDevice_fails_notPermission(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.User(1)
|
||||
db.User(2)
|
||||
db.Create(&model.Device{
|
||||
ID: 55,
|
||||
Name: "Android",
|
||||
Token: "abc",
|
||||
UserID: 2,
|
||||
CreatedAt: test.Time("2009-06-30T18:30:00+02:00"),
|
||||
ActiveAt: test.Time("2018-06-30T18:30:00+02:00"),
|
||||
Type: model.TypeNoExpiry,
|
||||
})
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
_, err := resolver.RemoveDevice(fake.User(1), 55)
|
||||
require.EqualError(t, err, "device not found")
|
||||
}
|
||||
29
device/update.go
Normal file
29
device/update.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/jinzhu/copier"
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
// UpdateDevice updates a device.
|
||||
func (r *ResolverForDevice) UpdateDevice(ctx context.Context, id int, name string, deviceType gqlmodel.DeviceType) (*gqlmodel.Device, error) {
|
||||
device := new(model.Device)
|
||||
if r.DB.Where("user_id = ?", auth.GetUser(ctx).ID).Find(device, id).RecordNotFound() {
|
||||
return nil, errors.New("device not found")
|
||||
}
|
||||
|
||||
device.Name = name
|
||||
device.Type = model.DeviceType(deviceType)
|
||||
if err := device.Type.Valid(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
update := r.DB.Save(device)
|
||||
gqlDevice := &gqlmodel.Device{}
|
||||
copier.Copy(gqlDevice, device)
|
||||
return gqlDevice, update.Error
|
||||
}
|
||||
94
device/update_test.go
Normal file
94
device/update_test.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/test"
|
||||
"github.com/traggo/server/test/fake"
|
||||
)
|
||||
|
||||
func TestGQL_UpdateDevice_succeeds_updatesDevice(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.Create(&model.User{
|
||||
Name: "jmattheis",
|
||||
ID: 1,
|
||||
Admin: true,
|
||||
})
|
||||
db.Create(&model.Device{
|
||||
Name: "old name",
|
||||
ID: 1,
|
||||
UserID: 1,
|
||||
CreatedAt: test.Time("2009-06-30T18:30:00Z"),
|
||||
ActiveAt: test.Time("2018-06-30T18:30:00Z"),
|
||||
Type: model.TypeNoExpiry,
|
||||
})
|
||||
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
device, err := resolver.UpdateDevice(fake.User(1), 1, "updated name", gqlmodel.DeviceTypeShortExpiry)
|
||||
require.Nil(t, err)
|
||||
|
||||
expected := &gqlmodel.Device{
|
||||
Name: "updated name",
|
||||
ID: 1,
|
||||
CreatedAt: test.ModelTimeUTC("2009-06-30T18:30:00Z"),
|
||||
ActiveAt: test.ModelTimeUTC("2018-06-30T18:30:00Z"),
|
||||
Type: gqlmodel.DeviceTypeShortExpiry,
|
||||
}
|
||||
require.Equal(t, expected, device)
|
||||
assertDeviceCount(t, db, 1)
|
||||
assertDeviceExist(t, db, model.Device{
|
||||
Name: "updated name",
|
||||
ID: 1,
|
||||
UserID: 1,
|
||||
CreatedAt: test.Time("2009-06-30T18:30:00Z"),
|
||||
ActiveAt: test.Time("2018-06-30T18:30:00Z"),
|
||||
Type: model.TypeShortExpiry,
|
||||
})
|
||||
}
|
||||
|
||||
func TestGQL_UpdateDevice_fails_notExistingDevice(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.Create(&model.User{
|
||||
Name: "jmattheis",
|
||||
ID: 1,
|
||||
Admin: true,
|
||||
})
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
_, err := resolver.UpdateDevice(fake.User(1), 3, "tst", gqlmodel.DeviceTypeShortExpiry)
|
||||
require.EqualError(t, err, "device not found")
|
||||
|
||||
assertDeviceCount(t, db, 0)
|
||||
}
|
||||
|
||||
func TestGQL_UpdateDevice_fails_noPermissions(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.Create(&model.User{
|
||||
Name: "jmattheis",
|
||||
ID: 1,
|
||||
Admin: true,
|
||||
})
|
||||
db.Create(&model.User{
|
||||
Name: "broderp",
|
||||
ID: 2,
|
||||
Admin: true,
|
||||
})
|
||||
db.Create(&model.Device{
|
||||
Name: "old name",
|
||||
ID: 66,
|
||||
UserID: 2,
|
||||
CreatedAt: test.Time("2009-06-30T18:30:00Z"),
|
||||
ActiveAt: test.Time("2018-06-30T18:30:00Z"),
|
||||
Type: model.TypeNoExpiry,
|
||||
})
|
||||
resolver := ResolverForDevice{DB: db.DB}
|
||||
_, err := resolver.UpdateDevice(fake.User(1), 66, "tst", gqlmodel.DeviceTypeNoExpiry)
|
||||
require.EqualError(t, err, "device not found")
|
||||
|
||||
assertDeviceCount(t, db, 1)
|
||||
}
|
||||
23
device/utils_test.go
Normal file
23
device/utils_test.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package device
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/test"
|
||||
)
|
||||
|
||||
func assertDeviceExist(t *testing.T, db *test.Database, expected model.Device) {
|
||||
foundDevice := new(model.Device)
|
||||
find := db.Find(foundDevice, expected.ID)
|
||||
require.Nil(t, find.Error)
|
||||
require.NotNil(t, foundDevice)
|
||||
require.Equal(t, expected, *foundDevice)
|
||||
}
|
||||
|
||||
func assertDeviceCount(t *testing.T, db *test.Database, expected int) {
|
||||
count := new(int)
|
||||
db.Model(new(model.Device)).Count(count)
|
||||
require.Equal(t, expected, *count)
|
||||
}
|
||||
15
docker-compose.yml
Normal file
15
docker-compose.yml
Normal file
@@ -0,0 +1,15 @@
|
||||
version: "3.9"
|
||||
services:
|
||||
traggo:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: docker/Dockerfile.dev
|
||||
environment:
|
||||
TRAGGO_DEFAULT_USER_NAME: "admin"
|
||||
TRAGGO_DEFAULT_USER_PASS: "admin"
|
||||
|
||||
TRAGGO_LOG_LEVEL: debug
|
||||
ports:
|
||||
- 3030:3030
|
||||
volumes:
|
||||
- .traggodata:/opt/traggo/data
|
||||
6
docker/Dockerfile
Normal file
6
docker/Dockerfile
Normal file
@@ -0,0 +1,6 @@
|
||||
FROM scratch
|
||||
LABEL org.opencontainers.image.source="https://github.com/traggo/server"
|
||||
WORKDIR /opt/traggo
|
||||
COPY traggo /opt/traggo
|
||||
EXPOSE 3030
|
||||
ENTRYPOINT ["./traggo"]
|
||||
1
docker/Dockerfile.build
Normal file
1
docker/Dockerfile.build
Normal file
@@ -0,0 +1 @@
|
||||
FROM ghcr.io/goreleaser/goreleaser-cross:v1.27.0
|
||||
15
docker/Dockerfile.dev
Normal file
15
docker/Dockerfile.dev
Normal file
@@ -0,0 +1,15 @@
|
||||
FROM golang:1.18.1 as builder
|
||||
|
||||
RUN apt-get update && apt-get install --yes nodejs npm && npm install --global yarn
|
||||
|
||||
WORKDIR /app
|
||||
COPY . .
|
||||
|
||||
ENV GO111MODULE=on
|
||||
RUN make download-tools install generate build-bin-local
|
||||
|
||||
FROM scratch
|
||||
WORKDIR /opt/traggo
|
||||
COPY --from=builder /app/build/traggo-server /opt/traggo/traggo
|
||||
EXPOSE 3030
|
||||
ENTRYPOINT ["./traggo"]
|
||||
44
go.mod
Normal file
44
go.mod
Normal file
@@ -0,0 +1,44 @@
|
||||
module github.com/traggo/server
|
||||
|
||||
require (
|
||||
github.com/99designs/gqlgen v0.17.85
|
||||
github.com/gorilla/mux v1.8.1
|
||||
github.com/jinzhu/copier v0.4.0
|
||||
github.com/jinzhu/gorm v1.9.2
|
||||
github.com/jmattheis/go-timemath v1.0.1
|
||||
github.com/joho/godotenv v1.5.1
|
||||
github.com/kelseyhightower/envconfig v1.4.0
|
||||
github.com/magiconair/properties v1.8.10
|
||||
github.com/phayes/freeport v0.0.0-20220201140144-74d24b5ae9f5
|
||||
github.com/rs/zerolog v1.34.0
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/vektah/gqlparser/v2 v2.5.31
|
||||
golang.org/x/crypto v0.46.0
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go v0.34.0 // indirect
|
||||
github.com/agnivade/levenshtein v1.2.1 // indirect
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/denisenkom/go-mssqldb v0.0.0-20181014144952-4e0d7dc8888f // indirect
|
||||
github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 // indirect
|
||||
github.com/go-sql-driver/mysql v1.4.1 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 // indirect
|
||||
github.com/gofrs/uuid v3.1.0+incompatible // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.0 // indirect
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
|
||||
github.com/jinzhu/inflection v0.0.0-20180308033659-04140366298a // indirect
|
||||
github.com/jinzhu/now v0.0.0-20181116074157-8ec929ed50c3 // indirect
|
||||
github.com/lib/pq v1.0.0 // indirect
|
||||
github.com/mattn/go-colorable v0.1.14 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.10.0 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/sosodev/duration v1.3.1 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
google.golang.org/appengine v1.3.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
go 1.24.0
|
||||
103
go.sum
Normal file
103
go.sum
Normal file
@@ -0,0 +1,103 @@
|
||||
cloud.google.com/go v0.34.0 h1:eOI3/cP2VTU6uZLDYAoic+eyzzB9YyGmJ7eIjl8rOPg=
|
||||
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
github.com/99designs/gqlgen v0.17.85 h1:EkGx3U2FDcxQm8YDLQSpXIAVmpDyZ3IcBMOJi2nH1S0=
|
||||
github.com/99designs/gqlgen v0.17.85/go.mod h1:yvs8s0bkQlRfqg03YXr3eR4OQUowVhODT/tHzCXnbOU=
|
||||
github.com/PuerkitoBio/goquery v1.11.0 h1:jZ7pwMQXIITcUXNH83LLk+txlaEy6NVOfTuP43xxfqw=
|
||||
github.com/PuerkitoBio/goquery v1.11.0/go.mod h1:wQHgxUOU3JGuj3oD/QFfxUdlzW6xPHfqyHre6VMY4DQ=
|
||||
github.com/agnivade/levenshtein v1.2.1 h1:EHBY3UOn1gwdy/VbFwgo4cxecRznFk7fKWN1KOX7eoM=
|
||||
github.com/agnivade/levenshtein v1.2.1/go.mod h1:QVVI16kDrtSuwcpd0p1+xMC6Z/VfhtCyDIjcwga4/DU=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883 h1:bvNMNQO63//z+xNgfBlViaCIJKLlCJ6/fmUseuG0wVQ=
|
||||
github.com/andreyvit/diff v0.0.0-20170406064948-c7f18ee00883/go.mod h1:rCTlJbsFo29Kk6CurOXKm700vrz8f0KW0JNfpkRJY/8=
|
||||
github.com/andybalholm/cascadia v1.3.3 h1:AG2YHrzJIm4BZ19iwJ/DAua6Btl3IwJX+VI4kktS1LM=
|
||||
github.com/andybalholm/cascadia v1.3.3/go.mod h1:xNd9bqTn98Ln4DwST8/nG+H0yuB8Hmgu1YHNnWw0GeA=
|
||||
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0 h1:jfIu9sQUG6Ig+0+Ap1h4unLjW6YQJpKZVmUzxsD4E/Q=
|
||||
github.com/arbovm/levenshtein v0.0.0-20160628152529-48b4e1c0c4d0/go.mod h1:t2tdKJDJF9BV14lnkjHmOQgcvEKgtqs5a1N3LNdJhGE=
|
||||
github.com/coreos/go-systemd/v22 v22.5.0/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/denisenkom/go-mssqldb v0.0.0-20181014144952-4e0d7dc8888f h1:WH0w/R4Yoey+04HhFxqZ6VX6I0d7RMyw5aXQ9UTvQPs=
|
||||
github.com/denisenkom/go-mssqldb v0.0.0-20181014144952-4e0d7dc8888f/go.mod h1:xN/JuLBIz4bjkxNmByTiV1IbhfnYb6oo99phBn4Eqhc=
|
||||
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54 h1:SG7nF6SRlWhcT7cNTs5R6Hk4V2lcmLz2NsG2VnInyNo=
|
||||
github.com/dgryski/trifles v0.0.0-20230903005119-f50d829f2e54/go.mod h1:if7Fbed8SFyPtHLHbg49SI7NAdJiC5WIA09pe59rfAA=
|
||||
github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y=
|
||||
github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0=
|
||||
github.com/go-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA=
|
||||
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=
|
||||
github.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/gofrs/uuid v3.1.0+incompatible h1:q2rtkjaKT4YEr6E1kamy0Ha4RtepWlQBedyHx0uzKwA=
|
||||
github.com/gofrs/uuid v3.1.0+incompatible/go.mod h1:b2aQJv3Z4Fp6yNu3cdSllBxTCLRxnplIgP/c0N/04lM=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
|
||||
github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
|
||||
github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc=
|
||||
github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/jinzhu/copier v0.4.0 h1:w3ciUoD19shMCRargcpm0cm91ytaBhDvuRpz1ODO/U8=
|
||||
github.com/jinzhu/copier v0.4.0/go.mod h1:DfbEm0FYsaqBcKcFuvmOZb218JkPGtvSHsKg8S8hyyg=
|
||||
github.com/jinzhu/gorm v1.9.2 h1:lCvgEaqe/HVE+tjAR2mt4HbbHAZsQOv3XAZiEZV37iw=
|
||||
github.com/jinzhu/gorm v1.9.2/go.mod h1:Vla75njaFJ8clLU1W44h34PjIkijhjHIYnZxMqCdxqo=
|
||||
github.com/jinzhu/inflection v0.0.0-20180308033659-04140366298a h1:eeaG9XMUvRBYXJi4pg1ZKM7nxc5AfXfojeLLW7O5J3k=
|
||||
github.com/jinzhu/inflection v0.0.0-20180308033659-04140366298a/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v0.0.0-20181116074157-8ec929ed50c3 h1:xvj06l8iSwiWpYgm8MbPp+naBg+pwfqmdXabzqPCn/8=
|
||||
github.com/jinzhu/now v0.0.0-20181116074157-8ec929ed50c3/go.mod h1:oHTiXerJ20+SfYcrdlBO7rzZRJWGwSTQ0iUY2jI6Gfc=
|
||||
github.com/jmattheis/go-timemath v1.0.1 h1:AY8bIDpD35nlWC5rhG+V4nLQ0OanU9omBcx0ahApT68=
|
||||
github.com/jmattheis/go-timemath v1.0.1/go.mod h1:/zMgCjpruOIsZPBFAPJ3F1ei09hAywu3PT9Eyd8tmaA=
|
||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||
github.com/kelseyhightower/envconfig v1.4.0 h1:Im6hONhd3pLkfDFsbRgu68RDNkGF1r3dvMUtDTo2cv8=
|
||||
github.com/kelseyhightower/envconfig v1.4.0/go.mod h1:cccZRl6mQpaq41TPp5QxidR+Sa3axMbJDNb//FQX6Gg=
|
||||
github.com/lib/pq v1.0.0 h1:X5PMW56eZitiTeO7tKzZxFCSpbFZJtkMMooicw2us9A=
|
||||
github.com/lib/pq v1.0.0/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE=
|
||||
github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg=
|
||||
github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=
|
||||
github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=
|
||||
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
|
||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.10.0 h1:jbhqpg7tQe4SupckyijYiy0mJJ/pRyHvXf7JdWK860o=
|
||||
github.com/mattn/go-sqlite3 v1.10.0/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
|
||||
github.com/phayes/freeport v0.0.0-20220201140144-74d24b5ae9f5 h1:Ii+DKncOVM8Cu1Hc+ETb5K+23HdAMvESYE3ZJ5b5cMI=
|
||||
github.com/phayes/freeport v0.0.0-20220201140144-74d24b5ae9f5/go.mod h1:iIss55rKnNBTvrwdmkUpLnDpZoAHvWaiq5+iMmen4AE=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rs/xid v1.6.0/go.mod h1:7XoLgs4eV+QndskICGsho+ADou8ySMSjJKDIan90Nz0=
|
||||
github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
|
||||
github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
|
||||
github.com/sergi/go-diff v1.3.1 h1:xkr+Oxo4BOQKmkn/B9eMK0g5Kg/983T9DqqPHwYqD+8=
|
||||
github.com/sergi/go-diff v1.3.1/go.mod h1:aMJSSKb2lpPvRNec0+w3fl7LP9IOFzdc9Pa4NFbPK1I=
|
||||
github.com/sosodev/duration v1.3.1 h1:qtHBDMQ6lvMQsL15g4aopM4HEfOaYuhWBw3NPTtlqq4=
|
||||
github.com/sosodev/duration v1.3.1/go.mod h1:RQIBBX0+fMLc/D9+Jb/fwvVmo0eZvDDEERAikUR6SDg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/vektah/gqlparser/v2 v2.5.31 h1:YhWGA1mfTjID7qJhd1+Vxhpk5HTgydrGU9IgkWBTJ7k=
|
||||
github.com/vektah/gqlparser/v2 v2.5.31/go.mod h1:c1I28gSOVNzlfc4WuDlqU7voQnsqI6OG2amkBAFmgts=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
google.golang.org/appengine v1.3.0 h1:FBSsiFRMz3LBeXIomRnVzrQwSDj4ibvcRexLG0LZGQk=
|
||||
google.golang.org/appengine v1.3.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
15
gqlgen.yml
Normal file
15
gqlgen.yml
Normal file
@@ -0,0 +1,15 @@
|
||||
schema: schema.graphql
|
||||
|
||||
exec:
|
||||
filename: generated/gqlschema/generated.go
|
||||
package: gqlschema
|
||||
|
||||
model:
|
||||
filename: generated/gqlmodel/generated.go
|
||||
package: gqlmodel
|
||||
|
||||
models:
|
||||
Time:
|
||||
model: github.com/traggo/server/model.Time
|
||||
|
||||
struct_tag: json
|
||||
13
graphql/directive.go
Normal file
13
graphql/directive.go
Normal file
@@ -0,0 +1,13 @@
|
||||
package graphql
|
||||
|
||||
import (
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/generated/gqlschema"
|
||||
)
|
||||
|
||||
// NewDirective creates a new directive.
|
||||
func NewDirective() gqlschema.DirectiveRoot {
|
||||
return gqlschema.DirectiveRoot{
|
||||
HasRole: auth.HasRole(),
|
||||
}
|
||||
}
|
||||
32
graphql/handler.go
Normal file
32
graphql/handler.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package graphql
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/99designs/gqlgen/handler"
|
||||
"github.com/traggo/server/generated/gqlschema"
|
||||
"github.com/traggo/server/logger"
|
||||
)
|
||||
|
||||
// Handler combines graphql handler and playground handler.
|
||||
func Handler(endpoint string, resolvers gqlschema.ResolverRoot, directives gqlschema.DirectiveRoot) http.HandlerFunc {
|
||||
gqlHandler := handler.GraphQL(gqlschema.NewExecutableSchema(gqlschema.Config{
|
||||
Resolvers: resolvers,
|
||||
Directives: directives,
|
||||
}), handler.RequestMiddleware(logger.GQLLog()))
|
||||
playground := handler.Playground("Traggo Playground", endpoint)
|
||||
|
||||
return func(writer http.ResponseWriter, request *http.Request) {
|
||||
if acceptHTMLAndNotJSON(request) {
|
||||
playground.ServeHTTP(writer, request)
|
||||
} else {
|
||||
gqlHandler.ServeHTTP(writer, request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func acceptHTMLAndNotJSON(request *http.Request) bool {
|
||||
val := request.Header.Get("Accept")
|
||||
return strings.Contains(val, "text/html") && !strings.Contains(val, "application/json")
|
||||
}
|
||||
42
graphql/handler_test.go
Normal file
42
graphql/handler_test.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package graphql
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/test"
|
||||
)
|
||||
|
||||
func TestHandler_jsonOverHtml(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
resolver := NewResolver(db.DB, 4, model.Version{})
|
||||
handler := Handler("/gql", resolver, NewDirective())
|
||||
req := httptest.NewRequest("GET", "/gql?query="+url.QueryEscape("query {currentUser {name}}"), strings.NewReader(""))
|
||||
req.Header.Set("Accept", "text/html;application/json")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, req)
|
||||
require.Equal(t, "application/graphql-response+json", recorder.Header().Get("Content-Type"))
|
||||
require.JSONEq(t, `
|
||||
{
|
||||
"data": { "currentUser": null }
|
||||
}
|
||||
`, recorder.Body.String())
|
||||
}
|
||||
|
||||
func TestHandler_htmlIfNotJson(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
resolver := NewResolver(db.DB, 4, model.Version{})
|
||||
handler := Handler("/gql", resolver, NewDirective())
|
||||
req := httptest.NewRequest("get", "/gql", strings.NewReader(""))
|
||||
req.Header.Set("Accept", "text/html;application/xml")
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, req)
|
||||
|
||||
require.Contains(t, recorder.Body.String(), "Traggo Playground")
|
||||
}
|
||||
71
graphql/resolver.go
Normal file
71
graphql/resolver.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package graphql
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/traggo/server/dashboard"
|
||||
"github.com/traggo/server/setting"
|
||||
|
||||
"github.com/jinzhu/copier"
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/traggo/server/device"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/generated/gqlschema"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/statistics"
|
||||
"github.com/traggo/server/tag"
|
||||
"github.com/traggo/server/timespan"
|
||||
"github.com/traggo/server/user"
|
||||
)
|
||||
|
||||
// NewResolver combines all resolvers to a resolver root.
|
||||
func NewResolver(db *gorm.DB, passStrength int, version model.Version) gqlschema.ResolverRoot {
|
||||
return &resolver{
|
||||
ResolverForUser: user.ResolverForUser{
|
||||
DB: db,
|
||||
PassStrength: passStrength,
|
||||
},
|
||||
ResolverForTag: tag.ResolverForTag{
|
||||
DB: db,
|
||||
},
|
||||
ResolverForDevice: device.ResolverForDevice{
|
||||
DB: db,
|
||||
},
|
||||
ResolverForTimeSpan: timespan.ResolverForTimeSpan{
|
||||
DB: db,
|
||||
},
|
||||
ResolverForStatistics: statistics.ResolverForStatistics{
|
||||
DB: db,
|
||||
},
|
||||
ResolverForSettings: setting.ResolverForSettings{
|
||||
DB: db,
|
||||
},
|
||||
ResolverForDashboard: dashboard.NewResolverForDashboard(db),
|
||||
version: version,
|
||||
}
|
||||
}
|
||||
|
||||
type resolver struct {
|
||||
user.ResolverForUser
|
||||
tag.ResolverForTag
|
||||
device.ResolverForDevice
|
||||
timespan.ResolverForTimeSpan
|
||||
statistics.ResolverForStatistics
|
||||
version model.Version
|
||||
setting.ResolverForSettings
|
||||
dashboard.ResolverForDashboard
|
||||
}
|
||||
|
||||
func (r *resolver) RootMutation() gqlschema.RootMutationResolver {
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *resolver) RootQuery() gqlschema.RootQueryResolver {
|
||||
return r
|
||||
}
|
||||
|
||||
func (r *resolver) Version(ctx context.Context) (*gqlmodel.Version, error) {
|
||||
gql := &gqlmodel.Version{}
|
||||
copier.Copy(gql, r.version)
|
||||
return gql, nil
|
||||
}
|
||||
22
graphql/resolver_test.go
Normal file
22
graphql/resolver_test.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package graphql
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/traggo/server/generated/gqlmodel"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/test"
|
||||
)
|
||||
|
||||
func TestNewResolver_doesNotThrow(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
resolver := NewResolver(db.DB, 4, model.Version{Name: "oops", BuildDate: "date", Commit: "aeu"})
|
||||
resolver.RootMutation()
|
||||
resolver.RootQuery()
|
||||
version, e := resolver.RootQuery().Version(context.Background())
|
||||
assert.NoError(t, e)
|
||||
assert.Equal(t, &gqlmodel.Version{Name: "oops", BuildDate: "date", Commit: "aeu"}, version)
|
||||
}
|
||||
224
hack/datagen/datagen.go
Normal file
224
hack/datagen/datagen.go
Normal file
@@ -0,0 +1,224 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
gotime "time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traggo/server/database"
|
||||
"github.com/traggo/server/logger"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/time"
|
||||
"github.com/traggo/server/user/password"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger.Init(zerolog.InfoLevel)
|
||||
rand.Seed(0)
|
||||
var from string
|
||||
flag.StringVar(&from, "from", "now/y", "from")
|
||||
var to string
|
||||
flag.StringVar(&to, "to", "now", "to")
|
||||
|
||||
db, err := database.New("sqlite3", "data.db")
|
||||
noErr(err)
|
||||
defer db.Close()
|
||||
|
||||
log.Info().Msg("Creating User ...")
|
||||
user := &model.User{
|
||||
Name: "admin",
|
||||
Pass: password.CreatePassword("admin", 10),
|
||||
Admin: true,
|
||||
}
|
||||
noErr(db.Create(user).Error)
|
||||
log.Info().Msg("... Done")
|
||||
uID := user.ID
|
||||
|
||||
log.Info().Msg("Creating Tags ...")
|
||||
|
||||
db.Create(&model.TagDefinition{
|
||||
Key: "type",
|
||||
UserID: uID,
|
||||
Color: "#fff",
|
||||
})
|
||||
db.Create(&model.TagDefinition{
|
||||
Key: "issue",
|
||||
UserID: uID,
|
||||
Color: "#fff",
|
||||
})
|
||||
db.Create(&model.TagDefinition{
|
||||
Key: "meeting",
|
||||
UserID: uID,
|
||||
Color: "#fff",
|
||||
})
|
||||
db.Create(&model.TagDefinition{
|
||||
Key: "with",
|
||||
UserID: uID,
|
||||
Color: "#fff",
|
||||
})
|
||||
db.Create(&model.TagDefinition{
|
||||
Key: "misc",
|
||||
UserID: uID,
|
||||
Color: "#fff",
|
||||
})
|
||||
db.Create(&model.TagDefinition{
|
||||
Key: "proj",
|
||||
UserID: uID,
|
||||
Color: "#fff",
|
||||
})
|
||||
log.Info().Msg("... Done")
|
||||
|
||||
now := gotime.Now().UTC()
|
||||
fromTime, err := time.ParseTime(now, from, true, gotime.Monday)
|
||||
noErr(err)
|
||||
toTime, err := time.ParseTime(now, to, false, gotime.Sunday)
|
||||
noErr(err)
|
||||
|
||||
buckets := []bucket{
|
||||
{
|
||||
TimeSpans: generateSupport(),
|
||||
weight: 100,
|
||||
},
|
||||
{
|
||||
TimeSpans: generateMeeting(),
|
||||
weight: 30,
|
||||
},
|
||||
{
|
||||
TimeSpans: generateIssueType("gotify", "review"),
|
||||
weight: 100,
|
||||
Active: 6,
|
||||
},
|
||||
{
|
||||
TimeSpans: generateIssueType("gotify", "work"),
|
||||
weight: 100,
|
||||
Active: 6,
|
||||
},
|
||||
{
|
||||
TimeSpans: generateIssueType("traggo", "review"),
|
||||
weight: 100,
|
||||
Active: 6,
|
||||
},
|
||||
{
|
||||
TimeSpans: generateIssueType("traggo", "work"),
|
||||
weight: 100,
|
||||
Active: 6,
|
||||
},
|
||||
}
|
||||
|
||||
sum := 0
|
||||
for _, bucket := range buckets {
|
||||
sum += bucket.weight
|
||||
}
|
||||
|
||||
currentNow := fromTime
|
||||
|
||||
log.Info().Msg("Creating TimeSpans ...")
|
||||
for i := 1; currentNow.Before(toTime); i++ {
|
||||
selected := randInt(0, sum)
|
||||
current := 0
|
||||
var bucket bucket
|
||||
for _, bucket = range buckets {
|
||||
current += bucket.weight
|
||||
if current > selected {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
duration := gotime.Minute * gotime.Duration(randInt(1, 150))
|
||||
|
||||
ts := bucket.TimeSpans[randInt(0, len(bucket.TimeSpans))]
|
||||
end := currentNow.Add(duration)
|
||||
db.Create(&model.TimeSpan{
|
||||
Tags: ts.Tags,
|
||||
UserID: uID,
|
||||
StartUserTime: currentNow,
|
||||
StartUTC: currentNow,
|
||||
EndUserTime: &end,
|
||||
EndUTC: &end,
|
||||
OffsetUTC: 0,
|
||||
})
|
||||
currentNow = end.Add(gotime.Minute * gotime.Duration(randInt(1, 20)))
|
||||
if i%500 == 0 {
|
||||
log.Info().Msgf("Inserted %d ...", i)
|
||||
}
|
||||
}
|
||||
log.Info().Msg("... Done")
|
||||
}
|
||||
|
||||
func generateIssueType(proj, t string) []timeSpan {
|
||||
numbers := []int{}
|
||||
for i := 1; i <= 1000; i++ {
|
||||
numbers = append(numbers, i)
|
||||
}
|
||||
|
||||
result := []timeSpan{}
|
||||
for _, number := range numbers {
|
||||
result = append(result, timeSpan{
|
||||
Tags: []model.TimeSpanTag{
|
||||
{Key: "proj", StringValue: proj},
|
||||
{Key: "type", StringValue: t},
|
||||
{Key: "issue", StringValue: fmt.Sprintf("%X-%d", proj, number)},
|
||||
},
|
||||
Runtime: gotime.Hour * 24 * 12,
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func generateMeeting() []timeSpan {
|
||||
names := []string{"weekly", "retro", "company", "team", "feature"}
|
||||
|
||||
result := []timeSpan{}
|
||||
for _, name := range names {
|
||||
result = append(result, timeSpan{
|
||||
Tags: []model.TimeSpanTag{
|
||||
{Key: "type", StringValue: "meeting"},
|
||||
{Key: "meeting", StringValue: name},
|
||||
},
|
||||
Runtime: gotime.Duration(-1),
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func generateSupport() []timeSpan {
|
||||
names := []string{"Tom", "Jerry", "Nico", "Anton", "Noob", "Alex", "Bob", "jmattheis", "nicories"}
|
||||
|
||||
result := []timeSpan{}
|
||||
for _, name := range names {
|
||||
result = append(result, timeSpan{
|
||||
Tags: []model.TimeSpanTag{
|
||||
{Key: "type", StringValue: "support"},
|
||||
{Key: "with", StringValue: name},
|
||||
},
|
||||
Runtime: gotime.Duration(-1),
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
type bucket struct {
|
||||
TimeSpans []timeSpan
|
||||
Active int
|
||||
CurrentlyActive []timeSpan
|
||||
weight int
|
||||
}
|
||||
|
||||
type timeSpan struct {
|
||||
ActiveSince gotime.Time
|
||||
Runtime gotime.Duration
|
||||
Tags []model.TimeSpanTag
|
||||
}
|
||||
|
||||
func noErr(err error) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
func randInt(min int, max int) int {
|
||||
return min + rand.Intn(max-min)
|
||||
}
|
||||
69
logger/database.go
Normal file
69
logger/database.go
Normal file
@@ -0,0 +1,69 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
var (
|
||||
sqlRegexp = regexp.MustCompile(`\?`)
|
||||
)
|
||||
|
||||
// DatabaseLogger logs sql queries
|
||||
type DatabaseLogger struct {
|
||||
}
|
||||
|
||||
// Print pretty prints the gorm.DB log values
|
||||
// Mostly copied from https://github.com/jinzhu/gorm/blob/master/logger.go
|
||||
func (l *DatabaseLogger) Print(values ...interface{}) {
|
||||
if len(values) > 1 {
|
||||
var (
|
||||
sql string
|
||||
formattedValues []string
|
||||
level = values[0]
|
||||
)
|
||||
|
||||
if level == "sql" {
|
||||
for _, value := range values[4].([]interface{}) {
|
||||
indirectValue := reflect.Indirect(reflect.ValueOf(value))
|
||||
if indirectValue.IsValid() {
|
||||
value = indirectValue.Interface()
|
||||
if t, ok := value.(time.Time); ok {
|
||||
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", t.Format("2006-01-02 15:04:05")))
|
||||
} else if _, ok := value.([]byte); ok {
|
||||
formattedValues = append(formattedValues, "'<binary>'")
|
||||
} else {
|
||||
formattedValues = append(formattedValues, fmt.Sprintf("'%v'", value))
|
||||
}
|
||||
} else {
|
||||
formattedValues = append(formattedValues, "NULL")
|
||||
}
|
||||
}
|
||||
|
||||
formattedValuesLength := len(formattedValues)
|
||||
for index, value := range sqlRegexp.Split(values[3].(string), -1) {
|
||||
sql += value
|
||||
if index < formattedValuesLength {
|
||||
sql += formattedValues[index]
|
||||
}
|
||||
}
|
||||
|
||||
log.Debug().Str("took", values[2].(time.Duration).String()).Int64("rows", values[5].(int64)).Msg("SQL: " + sql)
|
||||
} else if level == "log" {
|
||||
if len(values) > 2 {
|
||||
if err, ok := values[2].(error); ok {
|
||||
log.Error().Err(err).Msg("Database error")
|
||||
return
|
||||
}
|
||||
}
|
||||
log.Debug().Msg(fmt.Sprint(values[2:]...))
|
||||
} else {
|
||||
log.Error().Msgf("DatabaseLogger: cannot handle level %#v", level)
|
||||
}
|
||||
}
|
||||
// ignore empty log
|
||||
}
|
||||
96
logger/database_test.go
Normal file
96
logger/database_test.go
Normal file
@@ -0,0 +1,96 @@
|
||||
package logger_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/traggo/server/logger"
|
||||
"github.com/traggo/server/test"
|
||||
)
|
||||
|
||||
type Test struct {
|
||||
Password []byte
|
||||
NullValue *string
|
||||
Placeholder string
|
||||
Date time.Time
|
||||
Number uint
|
||||
}
|
||||
|
||||
func TestDatabaseLogger_Success(t *testing.T) {
|
||||
someTime, _ := time.Parse("2006/01/02", "2017/01/02")
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.AutoMigrate(&Test{})
|
||||
|
||||
fakeLog := test.NewLogger(t)
|
||||
defer fakeLog.Dispose()
|
||||
|
||||
db.Create(&Test{
|
||||
Password: []byte{1},
|
||||
Date: someTime,
|
||||
NullValue: nil,
|
||||
Number: 1,
|
||||
Placeholder: "hello there",
|
||||
})
|
||||
|
||||
expected := `SQL: INSERT INTO "tests" ("password","null_value","placeholder","date","number") VALUES ('<binary>',NULL,'hello there','2017-01-02 00:00:00','1')`
|
||||
|
||||
fakeLog.AssertCount(1)
|
||||
fakeLog.AssertEntryExists(test.Entry{Level: zerolog.DebugLevel, Message: expected})
|
||||
}
|
||||
|
||||
func TestDatabaseLogger_Error(t *testing.T) {
|
||||
db := test.InMemoryDB(t)
|
||||
defer db.Close()
|
||||
db.AutoMigrate(&Test{})
|
||||
|
||||
fakeLog := test.NewLogger(t)
|
||||
defer fakeLog.Dispose()
|
||||
|
||||
// column id doesn't exists
|
||||
db.Model(new(Test)).Where("id = ?", 5).Update("number", 6)
|
||||
|
||||
expectedOne := `SQL: UPDATE "tests" SET "number" = '6' WHERE (id = '5')`
|
||||
expectedTwo := `Database error`
|
||||
|
||||
fakeLog.AssertCount(2)
|
||||
fakeLog.AssertEntryExists(test.Entry{Level: zerolog.DebugLevel, Message: expectedOne})
|
||||
fakeLog.AssertEntryExists(test.Entry{Level: zerolog.ErrorLevel, Message: expectedTwo})
|
||||
}
|
||||
|
||||
func TestDatabaseLogger_EmptyLog(t *testing.T) {
|
||||
fakeLog := test.NewLogger(t)
|
||||
defer fakeLog.Dispose()
|
||||
|
||||
databaseLogger := logger.DatabaseLogger{}
|
||||
databaseLogger.Print([]interface{}{})
|
||||
|
||||
fakeLog.AssertCount(0)
|
||||
}
|
||||
|
||||
func TestDatabaseLogger_UnkownType(t *testing.T) {
|
||||
fakeLog := test.NewLogger(t)
|
||||
defer fakeLog.Dispose()
|
||||
|
||||
databaseLogger := logger.DatabaseLogger{}
|
||||
databaseLogger.Print("abc", "somevalue")
|
||||
|
||||
expected := `DatabaseLogger: cannot handle level "abc"`
|
||||
|
||||
fakeLog.AssertCount(1)
|
||||
fakeLog.AssertEntryExists(test.Entry{Level: zerolog.ErrorLevel, Message: expected})
|
||||
}
|
||||
|
||||
func TestDatabaseLogger_LogWithoutError(t *testing.T) {
|
||||
fakeLog := test.NewLogger(t)
|
||||
defer fakeLog.Dispose()
|
||||
|
||||
databaseLogger := logger.DatabaseLogger{}
|
||||
databaseLogger.Print("log", "somefile", "my log message")
|
||||
|
||||
expected := `my log message`
|
||||
|
||||
fakeLog.AssertCount(1)
|
||||
fakeLog.AssertEntryExists(test.Entry{Level: zerolog.DebugLevel, Message: expected})
|
||||
}
|
||||
50
logger/gql.go
Normal file
50
logger/gql.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
|
||||
"github.com/99designs/gqlgen/graphql"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
var (
|
||||
passRegEx = regexp.MustCompile(`pass\s*:\s*"(?:[^"\\]|\\.)*"`)
|
||||
)
|
||||
|
||||
// GQLLog logs graphql queries, mutations and errors.
|
||||
func GQLLog() graphql.ResponseMiddleware {
|
||||
return func(ctx context.Context, next graphql.ResponseHandler) *graphql.Response {
|
||||
start := time.Now()
|
||||
result := next(ctx)
|
||||
elapsed := time.Now().Sub(start)
|
||||
errs := graphql.GetErrors(ctx)
|
||||
rawQuery := graphql.GetRequestContext(ctx).RawQuery
|
||||
|
||||
if len(errs) > 0 {
|
||||
var errorStrings []string
|
||||
for _, err := range errs {
|
||||
errorStrings = append(errorStrings, err.Error())
|
||||
}
|
||||
|
||||
log.Error().Strs("error", errorStrings).Str("took", elapsed.String()).Msg("GQL: " + toOneLine(hidePassword(rawQuery)))
|
||||
} else if log.Debug().Enabled() {
|
||||
log.Debug().Str("took", elapsed.String()).Msg("GQL: " + toOneLine(hidePassword(rawQuery)))
|
||||
}
|
||||
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
func toOneLine(s string) string {
|
||||
return strings.Join(strings.FieldsFunc(s, func(r rune) bool {
|
||||
return unicode.IsSpace(r) || r == '\n' || r == '\r'
|
||||
}), " ")
|
||||
}
|
||||
|
||||
func hidePassword(s string) string {
|
||||
return passRegEx.ReplaceAllString(s, `pass:"<hidden>"`)
|
||||
}
|
||||
15
logger/logger.go
Normal file
15
logger/logger.go
Normal file
@@ -0,0 +1,15 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
)
|
||||
|
||||
// Init initializes the logger
|
||||
func Init(lvl zerolog.Level) {
|
||||
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout, TimeFormat: time.RFC3339}).Level(lvl)
|
||||
log.Debug().Msg("Logger initialized")
|
||||
}
|
||||
14
logger/logger_test.go
Normal file
14
logger/logger_test.go
Normal file
@@ -0,0 +1,14 @@
|
||||
package logger_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traggo/server/logger"
|
||||
)
|
||||
|
||||
func TestInit_LoggingWorks(t *testing.T) {
|
||||
logger.Init(zerolog.InfoLevel)
|
||||
log.Info().Msg("test logging")
|
||||
}
|
||||
100
main.go
Normal file
100
main.go
Normal file
@@ -0,0 +1,100 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/rs/zerolog"
|
||||
"github.com/rs/zerolog/log"
|
||||
"github.com/traggo/server/auth"
|
||||
"github.com/traggo/server/config"
|
||||
"github.com/traggo/server/config/mode"
|
||||
"github.com/traggo/server/database"
|
||||
"github.com/traggo/server/graphql"
|
||||
"github.com/traggo/server/logger"
|
||||
"github.com/traggo/server/model"
|
||||
"github.com/traggo/server/server"
|
||||
"github.com/traggo/server/ui"
|
||||
"github.com/traggo/server/user/password"
|
||||
)
|
||||
|
||||
var (
|
||||
// BuildMode will be set via ldflags
|
||||
BuildMode = mode.Dev
|
||||
// BuildCommit will be set via ldflags
|
||||
BuildCommit = "-"
|
||||
// BuildVersion will be set via ldflags
|
||||
BuildVersion = "develop"
|
||||
// BuildDate will be set via ldflags
|
||||
BuildDate = "unknown"
|
||||
)
|
||||
|
||||
func main() {
|
||||
mode.Set(BuildMode)
|
||||
|
||||
version := model.Version{Commit: BuildCommit, BuildDate: BuildDate, Name: BuildVersion}
|
||||
|
||||
conf, errs := config.Get()
|
||||
logger.Init(conf.LogLevel.AsZeroLogLevel())
|
||||
log.Info().Str("commit", BuildCommit).Str("buildDate", BuildDate).Str("buildMode", BuildMode).Str("version", BuildVersion).Msg("Traggo")
|
||||
|
||||
exit := false
|
||||
for _, err := range errs {
|
||||
log.WithLevel(err.Level).Msg(err.Msg)
|
||||
exit = exit || err.Level == zerolog.FatalLevel || err.Level == zerolog.PanicLevel
|
||||
}
|
||||
if exit {
|
||||
os.Exit(1)
|
||||
}
|
||||
log.Debug().Interface("config", conf).Msg("Using")
|
||||
|
||||
db := initDatabase(conf)
|
||||
|
||||
stopCleanUp := initCleanUp(db)
|
||||
|
||||
router := initRouter(db, conf, version)
|
||||
|
||||
log.Info().Int("port", conf.Port).Msg("Start listening")
|
||||
if err := server.Start(router, conf.Port); err != nil {
|
||||
log.Fatal().Err(err).Msg("Server Error")
|
||||
}
|
||||
stopCleanUp <- true
|
||||
}
|
||||
|
||||
func initRouter(db *gorm.DB, conf config.Config, version model.Version) *mux.Router {
|
||||
gqlHandler := graphql.Handler(
|
||||
"/graphql",
|
||||
graphql.NewResolver(db, conf.PassStrength, version),
|
||||
graphql.NewDirective())
|
||||
|
||||
router := mux.NewRouter()
|
||||
router.Use(auth.Middleware(db))
|
||||
router.HandleFunc("/graphql", gqlHandler)
|
||||
ui.Register(router)
|
||||
return router
|
||||
}
|
||||
|
||||
func initDatabase(conf config.Config) *gorm.DB {
|
||||
db, err := database.New(conf.DatabaseDialect, conf.DatabaseConnection)
|
||||
if err != nil {
|
||||
log.Fatal().Err(err).Msg("Failed to connect to the database")
|
||||
}
|
||||
c := new(int)
|
||||
if db.Model(new(model.User)).Count(c); *c == 0 {
|
||||
log.Info().Msg("Creating default user.")
|
||||
db.Create(&model.User{
|
||||
Name: conf.DefaultUserName,
|
||||
Pass: password.CreatePassword(conf.DefaultUserPass, conf.PassStrength),
|
||||
Admin: true})
|
||||
}
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
func initCleanUp(db *gorm.DB) chan<- bool {
|
||||
stopCleanUp := make(chan bool)
|
||||
go auth.CleanUp(db, time.Minute*10, stopCleanUp)
|
||||
return stopCleanUp
|
||||
}
|
||||
17
model/all.go
Normal file
17
model/all.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package model
|
||||
|
||||
// All returns all schema instances.
|
||||
func All() []interface{} {
|
||||
return []interface{}{
|
||||
new(TagDefinition),
|
||||
new(User),
|
||||
new(Device),
|
||||
new(TimeSpan),
|
||||
new(TimeSpanTag),
|
||||
new(UserSetting),
|
||||
new(Dashboard),
|
||||
new(DashboardEntry),
|
||||
new(DashboardTagFilter),
|
||||
new(DashboardRange),
|
||||
}
|
||||
}
|
||||
17
model/all_test.go
Normal file
17
model/all_test.go
Normal file
@@ -0,0 +1,17 @@
|
||||
package model_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/traggo/server/model"
|
||||
)
|
||||
|
||||
func TestAll_NoDuplicateEntries(t *testing.T) {
|
||||
all := model.All()
|
||||
var checkedItems []interface{}
|
||||
for _, item := range all {
|
||||
assert.NotContains(t, checkedItems, item)
|
||||
checkedItems = append(checkedItems, item)
|
||||
}
|
||||
}
|
||||
106
model/dashboard.go
Normal file
106
model/dashboard.go
Normal file
@@ -0,0 +1,106 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// DashboardRange a named range of a dashboard.
|
||||
type DashboardRange struct {
|
||||
ID int `gorm:"primary_key;unique_index;AUTO_INCREMENT"`
|
||||
Name string
|
||||
DashboardID int `gorm:"type:int REFERENCES dashboards(id) ON DELETE CASCADE"`
|
||||
Editable bool
|
||||
From string
|
||||
To string
|
||||
}
|
||||
|
||||
// Dashboard a dashboard
|
||||
type Dashboard struct {
|
||||
ID int `gorm:"primary_key;unique_index;AUTO_INCREMENT"`
|
||||
UserID int `gorm:"type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
Name string
|
||||
Entries []DashboardEntry
|
||||
Ranges []DashboardRange
|
||||
}
|
||||
|
||||
// DashboardEntry an entry which represents a diagram in a dashboard.
|
||||
type DashboardEntry struct {
|
||||
ID int `gorm:"primary_key;unique_index;AUTO_INCREMENT"`
|
||||
DashboardID int `gorm:"type:int REFERENCES dashboards(id) ON DELETE CASCADE"`
|
||||
Title string
|
||||
Total bool `gorm:"default:false"`
|
||||
Type DashboardType
|
||||
Keys string
|
||||
Interval Interval
|
||||
RangeID int
|
||||
RangeFrom string
|
||||
RangeTo string
|
||||
TagFilters []DashboardTagFilter
|
||||
|
||||
MobilePosition string
|
||||
DesktopPosition string
|
||||
}
|
||||
|
||||
// DashboardTagFilter a tag for filtering timespans
|
||||
type DashboardTagFilter struct {
|
||||
DashboardEntryID int `gorm:"type:int REFERENCES dashboard_entries(id) ON DELETE CASCADE"`
|
||||
Key string
|
||||
StringValue string
|
||||
Include bool
|
||||
}
|
||||
|
||||
// DashboardType the dashboard type
|
||||
type DashboardType string
|
||||
|
||||
// Value for db
|
||||
func (t DashboardType) Value() (driver.Value, error) {
|
||||
return string(t), nil
|
||||
}
|
||||
|
||||
// Scan for db
|
||||
func (t *DashboardType) Scan(value interface{}) error {
|
||||
s, ok := value.([]byte)
|
||||
if !ok {
|
||||
return fmt.Errorf("expected string but was %#v", value)
|
||||
}
|
||||
*t = DashboardType(s)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Interval the interval in which the diagram data should be grouped.
|
||||
type Interval string
|
||||
|
||||
// Value for db
|
||||
func (t Interval) Value() (driver.Value, error) {
|
||||
return string(t), nil
|
||||
}
|
||||
|
||||
// Scan for db
|
||||
func (t *Interval) Scan(value interface{}) error {
|
||||
s, ok := value.([]byte)
|
||||
if !ok {
|
||||
return fmt.Errorf("expected string but was %#v", value)
|
||||
}
|
||||
*t = Interval(s)
|
||||
return nil
|
||||
}
|
||||
|
||||
// No lint errors please.
|
||||
const (
|
||||
TypePieChart DashboardType = "piechart"
|
||||
TypeBarChart DashboardType = "barchart"
|
||||
TypeLineChart DashboardType = "linechart"
|
||||
HorizontalTable DashboardType = "horizontaltable"
|
||||
VerticalTable DashboardType = "verticaltable"
|
||||
TypeStackedBarChart DashboardType = "stackedbarchart"
|
||||
|
||||
IntervalHourly Interval = "hourly"
|
||||
IntervalDaily Interval = "daily"
|
||||
IntervalWeekly Interval = "weekly"
|
||||
IntervalMonthly Interval = "monthly"
|
||||
IntervalYearly Interval = "yearly"
|
||||
IntervalSingle Interval = "single"
|
||||
|
||||
NoRangeIDDefined = -1
|
||||
)
|
||||
68
model/device.go
Normal file
68
model/device.go
Normal file
@@ -0,0 +1,68 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"database/sql/driver"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Device represents something which can connect to traggo
|
||||
type Device struct {
|
||||
ID int `gorm:"primary_key;unique_index;AUTO_INCREMENT"`
|
||||
Token string `gorm:"unique"`
|
||||
Name string
|
||||
UserID int `gorm:"type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
CreatedAt time.Time
|
||||
Type DeviceType
|
||||
ActiveAt time.Time
|
||||
}
|
||||
|
||||
// DeviceType the device type
|
||||
type DeviceType string
|
||||
|
||||
// Value for db
|
||||
func (t DeviceType) Value() (driver.Value, error) {
|
||||
return string(t), nil
|
||||
}
|
||||
|
||||
// Scan for db
|
||||
func (t *DeviceType) Scan(value interface{}) error {
|
||||
s, ok := value.([]byte)
|
||||
if !ok {
|
||||
return fmt.Errorf("expected []byte but was %#v", value)
|
||||
}
|
||||
*t = DeviceType(s)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Seconds returns the amount of seconds after the device expires.
|
||||
func (t DeviceType) Seconds() int {
|
||||
switch t {
|
||||
case TypeLongExpiry:
|
||||
return 60 * 60 * 24 * 30
|
||||
case TypeShortExpiry:
|
||||
return 60 * 60
|
||||
case TypeNoExpiry:
|
||||
return 60 * 60 * 24 * 365
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
// Valid checks if the device type is valid.
|
||||
func (t DeviceType) Valid() error {
|
||||
switch t {
|
||||
case TypeNoExpiry, TypeShortExpiry, TypeLongExpiry:
|
||||
return nil
|
||||
default:
|
||||
return errors.New("unknown device type")
|
||||
}
|
||||
}
|
||||
|
||||
// Device types
|
||||
const (
|
||||
TypeShortExpiry DeviceType = "ShortExpiry"
|
||||
TypeLongExpiry DeviceType = "LongExpiry"
|
||||
TypeNoExpiry DeviceType = "NoExpiry"
|
||||
)
|
||||
26
model/device_test.go
Normal file
26
model/device_test.go
Normal file
@@ -0,0 +1,26 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func Test(t *testing.T) {
|
||||
dType := DeviceType("abc")
|
||||
require.Error(t, dType.Valid(), "unknown type")
|
||||
|
||||
require.Equal(t, TypeShortExpiry.Seconds(), 3600)
|
||||
require.Equal(t, TypeLongExpiry.Seconds(), 2592000)
|
||||
require.Equal(t, TypeNoExpiry.Seconds(), 31536000)
|
||||
value, err := TypeNoExpiry.Value()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, value, "NoExpiry")
|
||||
require.Nil(t, TypeNoExpiry.Valid())
|
||||
|
||||
var scan DeviceType
|
||||
|
||||
err = scan.Scan([]byte("NoExpiry"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, TypeNoExpiry, scan)
|
||||
}
|
||||
49
model/setting.go
Normal file
49
model/setting.go
Normal file
@@ -0,0 +1,49 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
// UserSetting a setting for a user.
|
||||
type UserSetting struct {
|
||||
UserID int `gorm:"primary_key;unique_index"`
|
||||
Theme string
|
||||
DateLocale string
|
||||
FirstDayOfTheWeek string
|
||||
DateTimeInputStyle string
|
||||
}
|
||||
|
||||
// Settings constants
|
||||
const (
|
||||
ThemeGruvboxDark = "GruvboxDark"
|
||||
ThemeGruvboxLight = "GruvboxLight"
|
||||
ThemeMaterialDark = "MaterialDark"
|
||||
ThemeMaterialLight = "MaterialLight"
|
||||
|
||||
DateLocaleGerman = "German"
|
||||
DateLocaleAmerican = "American"
|
||||
DateLocaleAmerican24h = "American24h"
|
||||
DateLocaleBritish = "British"
|
||||
DateLocaleAustralian = "Australian"
|
||||
|
||||
DateTimeInputFancy = "Fancy"
|
||||
DateTimeInputNative = "Native"
|
||||
)
|
||||
|
||||
var daysOfWeek = map[string]time.Weekday{
|
||||
"Sunday": time.Sunday,
|
||||
"Monday": time.Monday,
|
||||
"Tuesday": time.Tuesday,
|
||||
"Wednesday": time.Wednesday,
|
||||
"Thursday": time.Thursday,
|
||||
"Friday": time.Friday,
|
||||
"Saturday": time.Saturday,
|
||||
}
|
||||
|
||||
// FirstDayOfTheWeekTimeWeekday returns the configured first day of the week.
|
||||
func (s UserSetting) FirstDayOfTheWeekTimeWeekday() time.Weekday {
|
||||
return daysOfWeek[s.FirstDayOfTheWeek]
|
||||
}
|
||||
|
||||
// LastDayOfTheWeekTimeWeekday returns the configured last day of the week.
|
||||
func (s UserSetting) LastDayOfTheWeekTimeWeekday() time.Weekday {
|
||||
return daysOfWeek[(daysOfWeek[s.FirstDayOfTheWeek] - 1).String()]
|
||||
}
|
||||
9
model/tagdefinition.go
Normal file
9
model/tagdefinition.go
Normal file
@@ -0,0 +1,9 @@
|
||||
package model
|
||||
|
||||
// TagDefinition describes a tag.
|
||||
type TagDefinition struct {
|
||||
Key string
|
||||
UserID int `gorm:"type:int REFERENCES users(id) ON DELETE CASCADE"`
|
||||
Color string
|
||||
Usages int `gorm:"-"`
|
||||
}
|
||||
48
model/time.go
Normal file
48
model/time.go
Normal file
@@ -0,0 +1,48 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Time scalar type for graphql
|
||||
type Time time.Time
|
||||
|
||||
// Time returns the wrapped time
|
||||
func (t Time) Time() time.Time {
|
||||
return time.Time(t)
|
||||
}
|
||||
|
||||
// OmitTimeZone omits the time zone and removes a utc date.
|
||||
func (t Time) OmitTimeZone() time.Time {
|
||||
x := t.Time()
|
||||
return time.Date(x.Year(), x.Month(), x.Day(), x.Hour(), x.Minute(), x.Second(), x.Nanosecond(), time.UTC)
|
||||
}
|
||||
|
||||
// UTC changes the timezone to utc.
|
||||
func (t Time) UTC() time.Time {
|
||||
return t.Time().UTC()
|
||||
}
|
||||
|
||||
// MarshalGQL implements the graphql.Marshaler interface
|
||||
func (t Time) MarshalGQL(w io.Writer) {
|
||||
if _, err := w.Write([]byte(fmt.Sprintf(`"%s"`, t.Time().Format(time.RFC3339)))); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
|
||||
// UnmarshalGQL implements the graphql.Unmarshaler interface
|
||||
func (t *Time) UnmarshalGQL(v interface{}) error {
|
||||
raw, ok := v.(string)
|
||||
if !ok {
|
||||
return fmt.Errorf("time must be a string")
|
||||
}
|
||||
|
||||
parse, err := time.Parse(time.RFC3339, raw)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*t = Time(parse)
|
||||
return nil
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user