├── .dockerignore
├── .github
└── workflows
│ ├── rtabby.yml
│ └── rust-clippy.yml
├── .gitignore
├── Cargo.toml
├── Dockerfile
├── LICENSE
├── README.md
├── build.rs
├── dev.md
├── diesel.toml
├── docker-compose-sqlite.yml
├── docker-compose.yml
├── migrations
├── .keep
├── 2023-01-04-185203_init
│ ├── down.sql
│ └── up.sql
└── 2023-12-21-031738_create_users
│ ├── down.sql
│ └── up.sql
├── migrations_sqlite
├── .keep
├── 2023-01-04-185203_init
│ ├── down.sql
│ └── up.sql
└── 2023-12-09-170536_create_users
│ ├── down.sql
│ └── up.sql
├── scripts
├── mariadb-static-build.sh
└── zlib-static-build.sh
├── src
├── app_config.rs
├── auth.rs
├── env.rs
├── error.rs
├── login
│ ├── env.rs
│ ├── error.rs
│ ├── mod.rs
│ ├── models.rs
│ ├── providers
│ │ ├── github.rs
│ │ ├── gitlab.rs
│ │ ├── google.rs
│ │ ├── microsoft.rs
│ │ └── mod.rs
│ ├── routes.rs
│ └── services.rs
├── main.rs
├── models
│ ├── config.rs
│ ├── mod.rs
│ └── user.rs
├── routes
│ ├── config.rs
│ ├── mod.rs
│ └── user.rs
├── schema.rs
├── storage.rs
└── tls.rs
├── users.exemple.yml
└── web
├── static
├── favicon.svg
├── script.js
└── styles.css
└── templates
├── login.html
└── success.html
/.dockerignore:
--------------------------------------------------------------------------------
1 | target
2 | Dockerfile
3 | .dockerignore
4 | .git
5 | .gitignore
6 | data.db
7 | .env
8 | users.yml
9 | config
10 | build
11 | lib
12 | mariadb-connector-c-3.3.3-src.tar.gz
13 | mariadb-connector-c-3.3.3-src
14 | zlib.tar.gz
15 | zlib
16 |
--------------------------------------------------------------------------------
/.github/workflows/rtabby.yml:
--------------------------------------------------------------------------------
1 | name: rTabby
2 |
3 | on:
4 | push:
5 | branches: [ "master" ]
6 | tags: [ 'v*.*.*' ]
7 | pull_request:
8 | branches: [ "master" ]
9 | release:
10 | types: [published]
11 |
12 | env:
13 | CARGO_TERM_COLOR: always
14 | # Make sure CI fails on all warnings, including Clippy lints
15 | RUSTFLAGS: "-Dwarnings"
16 | REGISTRY: ghcr.io
17 | IMAGE_NAME: ${{ github.repository }}
18 |
19 | jobs:
20 | build:
21 | name: Rust Build
22 | runs-on: ubuntu-latest
23 | steps:
24 | - uses: actions/checkout@v3
25 | - name: Build
26 | run: cargo build --verbose
27 | - name: Run tests
28 | run: cargo test --verbose
29 |
30 | docker:
31 | strategy:
32 | matrix:
33 | db: [mysql, sqlite]
34 | minimal: [true, false]
35 | name: Docker
36 | if: ${{ always() && contains(join(needs.*.result, ','), 'success') }}
37 | needs: [build]
38 | runs-on: ubuntu-latest
39 | permissions:
40 | contents: read
41 | packages: write
42 | # This is used to complete the identity challenge
43 | # with sigstore/fulcio when running outside of PRs.
44 | id-token: write
45 |
46 | steps:
47 | - name: Checkout repository
48 | uses: actions/checkout@v3
49 |
50 | # Install the cosign tool except on PR
51 | # https://github.com/sigstore/cosign-installer
52 | - name: Install cosign
53 | if: ${{ github.event_name == 'release' }}
54 | uses: sigstore/cosign-installer@v3.5.0
55 | with:
56 | cosign-release: 'v2.2.4'
57 |
58 | - name: Set up QEMU
59 | if: ${{ github.event_name == 'release' }}
60 | uses: docker/setup-qemu-action@v3
61 |
62 | # Set up BuildKit Docker container builder to be able to build
63 | # multi-platform images and export cache
64 | # https://github.com/docker/setup-buildx-action
65 | - name: Set up Docker Buildx
66 | uses: docker/setup-buildx-action@f95db51fddba0c2d1ec667646a06c2ce06100226 # v3.0.0
67 |
68 | # Login against a Docker registry except on PR
69 | # https://github.com/docker/login-action
70 | - name: Log into registry ${{ env.REGISTRY }}
71 | if: ${{ github.event_name == 'release' }}
72 | uses: docker/login-action@343f7c4344506bcbf9b4de18042ae17996df046d # v3.0.0
73 | with:
74 | registry: ${{ env.REGISTRY }}
75 | username: ${{ github.actor }}
76 | password: ${{ secrets.GITHUB_TOKEN }}
77 |
78 | - name: Prepare
79 | id: prep
80 | env:
81 | REF: ${{ github.ref }}
82 | run: |
83 | if [[ "$REF" == "refs/tags/v"* ]]; then
84 | tag=$(git describe --tags $(git rev-list --tags --max-count=1))
85 | tag=${tag:1}
86 | else
87 | tag=$(git log -1 --format="%cd" --date=short | sed s/-//g)
88 | fi
89 | echo "TAG=$tag" >> $GITHUB_OUTPUT
90 | echo "GIT_COMMIT=$(echo $(git rev-parse HEAD) | cut -c1-7)" >> $GITHUB_OUTPUT
91 |
92 | # Extract metadata (tags, labels) for Docker
93 | # https://github.com/docker/metadata-action
94 | - name: Extract Docker metadata
95 | id: meta
96 | uses: docker/metadata-action@96383f45573cb7f253c731d3b3ab81c87ef81934 # v5.0.0
97 | with:
98 | images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
99 | flavor: |
100 | latest=false
101 | tags: |
102 | type=semver, pattern={{version}}, enable=${{ matrix.db == 'mysql' }}, suffix=${{ matrix.minimal && '-minimal' || '' }}
103 | type=semver, pattern={{version}}, suffix=-${{ matrix.db }}${{ matrix.minimal && '-minimal' || '' }}
104 | type=sha, format=short
105 | type=raw, value=latest, enable=${{ matrix.db == 'mysql' }}, suffix=${{ matrix.minimal && '-minimal' || '' }}
106 | type=raw, value=latest, suffix=-${{ matrix.db }}${{ matrix.minimal && '-minimal' || '' }}
107 | type=raw, value=${{ matrix.db }}, suffix=${{ matrix.minimal && '-minimal' || '' }}
108 |
109 | # Build and push Docker image with Buildx
110 | # https://github.com/docker/build-push-action
111 | - name: Build and push Docker image
112 | id: build-and-push
113 | uses: docker/build-push-action@0565240e2d4ab88bba5387d719585280857ece09 # v5.0.0
114 | with:
115 | context: .
116 | platforms: linux/amd64${{ github.event_name == 'release' && ',linux/arm64' || '' }}
117 | push: ${{ github.event_name == 'release' }}
118 | tags: ${{ steps.meta.outputs.tags }}
119 | labels: ${{ steps.meta.outputs.labels }}
120 | cache-from: type=gha
121 | cache-to: type=gha,mode=max
122 | build-args: |
123 | GIT_COMMIT=${{ steps.prep.outputs.GIT_COMMIT }}
124 | FEATURE_FLAGS=-F|${{ matrix.db }}-bundle${{ !matrix.minimal && '|-F|all-login' || '' }}
125 |
126 | # Sign the resulting Docker image digest except on PRs.
127 | # This will only write to the public Rekor transparency log when the Docker
128 | # repository is public to avoid leaking data. If you would like to publish
129 | # transparency data even for private images, pass --force to cosign below.
130 | # https://github.com/sigstore/cosign
131 | - name: Sign the published Docker image
132 | if: ${{ github.event_name == 'release' }}
133 | env:
134 | # https://docs.github.com/en/actions/security-guides/security-hardening-for-github-actions#using-an-intermediate-environment-variable
135 | TAGS: ${{ steps.meta.outputs.tags }}
136 | DIGEST: ${{ steps.build-and-push.outputs.digest }}
137 | # This step uses the identity token to provision an ephemeral certificate
138 | # against the sigstore community Fulcio instance.
139 | run: echo "${TAGS}" | xargs -I {} cosign sign --yes {}@${DIGEST}
140 |
--------------------------------------------------------------------------------
/.github/workflows/rust-clippy.yml:
--------------------------------------------------------------------------------
1 | # This workflow uses actions that are not certified by GitHub.
2 | # They are provided by a third-party and are governed by
3 | # separate terms of service, privacy policy, and support
4 | # documentation.
5 | # rust-clippy is a tool that runs a bunch of lints to catch common
6 | # mistakes in your Rust code and help improve your Rust code.
7 | # More details at https://github.com/rust-lang/rust-clippy
8 | # and https://rust-lang.github.io/rust-clippy/
9 |
10 | name: rust-clippy analyze
11 |
12 | on:
13 | push:
14 | branches: [ "master" ]
15 | pull_request:
16 | # The branches below must be a subset of the branches above
17 | branches: [ "master" ]
18 | schedule:
19 | - cron: '31 7 * * 3'
20 |
21 | jobs:
22 | rust-clippy-analyze:
23 | name: Run rust-clippy analyzing
24 | runs-on: ubuntu-latest
25 | permissions:
26 | contents: read
27 | security-events: write
28 | actions: read # only required for a private repository by github/codeql-action/upload-sarif to get the Action run status
29 | steps:
30 | - name: Checkout code
31 | uses: actions/checkout@v2
32 |
33 | - name: Install Rust toolchain
34 | uses: actions-rs/toolchain@16499b5e05bf2e26879000db0c1d13f7e13fa3af #@v1
35 | with:
36 | profile: minimal
37 | toolchain: stable
38 | components: clippy
39 | override: true
40 |
41 | - name: Install required cargo
42 | run: cargo install clippy-sarif sarif-fmt
43 |
44 | - name: Run rust-clippy
45 | run:
46 | cargo clippy
47 | --all-features
48 | --message-format=json | clippy-sarif | tee rust-clippy-results.sarif | sarif-fmt
49 | continue-on-error: true
50 |
51 | - name: Upload analysis results to GitHub
52 | uses: github/codeql-action/upload-sarif@v1
53 | with:
54 | sarif_file: rust-clippy-results.sarif
55 | wait-for-processing: true
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Generated by Cargo
2 | # will have compiled files and executables
3 | debug/
4 | target/
5 |
6 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
7 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
8 | Cargo.lock
9 |
10 | # These are backup files generated by rustfmt
11 | **/*.rs.bk
12 |
13 | # MSVC Windows builds of rustc generate these, which store debugging information
14 | *.pdb
15 |
16 | .env
17 | /vendor
18 | data.db
19 | users.yml
20 | /config
21 | /build
22 | /lib
23 |
24 | mariadb-connector-c-3.3.3-src.tar.gz
25 | /mariadb-connector-c-3.3.3-src
26 |
27 | zlib.tar.gz
28 | zlib
29 |
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "rtabby-web-api"
3 | version = "0.4.2"
4 | edition = "2021"
5 |
6 | [features]
7 | default = ["mysql", "all-login"]
8 | dotenv = ["dep:dotenvy"]
9 | mysql = ["diesel/mysql"]
10 | mysql-bundle = ["mysql"]
11 | sqlite = ["diesel/sqlite"]
12 | sqlite-bundle = ["sqlite", "libsqlite3-sys/bundled"]
13 | third-party-login = ["dep:actix-session", "dep:tera", "dep:reqwest", "dep:actix-files"]
14 | google-login = ["third-party-login"]
15 | github-login = ["third-party-login"]
16 | gitlab-login = ["third-party-login"]
17 | microsoft-login = ["third-party-login"]
18 | all-login = ["google-login", "github-login", "gitlab-login", "microsoft-login"]
19 |
20 | [dev-dependencies]
21 | dotenvy = "0.15.6"
22 |
23 | [dependencies]
24 | env_logger = "0.11.3"
25 | log = "0.4.16"
26 | dotenvy = {version = "0.15.6", optional = true}
27 | rustls = "0.21.7"
28 | rustls-pemfile = "1.0.0"
29 | actix-web = { version = "4.5.1", features = ["rustls-0_21"] }
30 | actix-web-httpauth = "0.8.1"
31 | actix-session = { version = "0.9.0", features = ["cookie-session"], optional = true }
32 | actix-files = { version = "0.6.5", optional = true }
33 | chrono = { version = "0.4.22", features = ["serde"] }
34 | libsqlite3-sys = { version = "0", optional = true }
35 | diesel = { version = "2.1.4", features = ["chrono", "r2d2"] }
36 | diesel_migrations = "2.1.0"
37 | serde = { version = "1.0.152", features = ["derive"] }
38 | serde_yaml = "0.9.16"
39 | uuid = { version = "1.6.1", features = ["serde", "v4"] }
40 | tera = { version = "1", optional = true }
41 | reqwest = { version = "0.12.4", features = ["json", "rustls-tls"], default-features = false, optional = true }
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | # syntax=docker/dockerfile:1
2 | FROM rust:1.76-alpine AS builder
3 | ARG FEATURE_FLAGS="-F|mysql-bundle|-F|all-login"
4 | WORKDIR /build
5 | COPY . .
6 |
7 | RUN apk add --no-cache build-base
8 |
9 | RUN if [[ "$FEATURE_FLAGS" == *"mysql-bundle"* ]]; then \
10 | apk add --no-cache binutils mariadb-dev musl-dev bash cmake curl && \
11 | bash scripts/mariadb-static-build.sh && \
12 | bash scripts/zlib-static-build.sh && \
13 | ar x lib/libmysqlclient.a && \
14 | ar x /lib/libz.a && \
15 | ar x /usr/lib/libc.a && \
16 | ar rcs /build/lib/libmysqlclient.a *.o *.lo && \
17 | rm -rf *.o *.lo; \
18 | fi
19 |
20 | RUN if [[ "$FEATURE_FLAGS" == *"login"* ]]; then \
21 | echo "login enabled"; \
22 | else \
23 | rm -rf /build/web/*; \
24 | fi
25 |
26 |
27 | RUN cargo build --release --no-default-features --target-dir /build/target/docker $(echo "$FEATURE_FLAGS" | sed 's/|/ /g')
28 |
29 | FROM scratch
30 | ARG GIT_COMMIT
31 |
32 | WORKDIR /config
33 |
34 | COPY --from=builder /build/target/docker/release/rtabby-web-api /
35 | COPY --from=builder /build/users.exemple.yml .
36 | COPY --from=builder /build/web/ /www/web/
37 | ENV STATIC_FILES_BASE_DIR=/www/web/
38 | ENV GIT_COMMIT=$GIT_COMMIT
39 |
40 | CMD ["/rtabby-web-api"]
41 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
Tabby Web (API only)
4 |
5 |
6 | Tabby Web API for Config Sync writen in Rust
7 |
8 |
9 |
10 |
11 |
12 | 
13 |
14 | ## About The Project / Disclamer
15 |
16 | **This project has been made on educational purpose. It is not a fork of Eugeny/tabby-web and not affiliated to @Eugeny Tabby terminal project. You can't expect any support from there while using this project.**
17 |
18 | As tabby web public instance app.tabby.sh has been discontinued. I decided to publish this as it provides a light, quick and easy way to deploy your own tabby config sync service. However, keep in mind that you used it at your own risk.
19 |
20 | ## Getting Started
21 |
22 | Run your own instance with docker compose.
23 |
24 | ### Prerequisites
25 |
26 | * Linux (AMD64/x86_64/Arm64) with docker engine.
27 | * Arm64 -> 0.4.0 and later [#14](https://github.com/Clem-Fern/rtabby-web-api/issues/14)
28 |
29 | ### Installation
30 |
31 | Create a directory which will contain your `docker-compose.yml` and `config` volume.
32 | ```sh
33 | mkdir -p rtabby-web-api/config
34 | cd rtabby-web-api
35 | ```
36 |
37 | rtabby-web-api store tabby's configuration in a database. You can choose between mysql or sqlite database. Third-party login will also be stored in database.
38 |
39 | * Mysql
40 | ```sh
41 | # pwd /../../rtabby-web-api
42 | wget https://raw.githubusercontent.com/Clem-Fern/rtabby-web-api/master/docker-compose.yml
43 | ```
44 |
45 | * Sqlite
46 | ```sh
47 | # pwd /../../rtabby-web-api
48 | wget https://raw.githubusercontent.com/Clem-Fern/rtabby-web-api/master/docker-compose-sqlite.yml -O docker-compose.yml
49 | ```
50 |
51 | ### Configuration
52 |
53 | 1. Create `config` directory. It will be used to store your config and certificate(not mandatory)
54 |
55 | ```sh
56 | # pwd /../../rtabby-web-api
57 | mkdir config
58 | touch config/users.yml
59 | # otherwise users.yml file will be created at first start
60 | ```
61 |
62 | 2. Tabby uses a token to authenticate user. You have to create your own user with his token in `users.yml` to be able to use the sync service.
63 |
64 | ```yaml
65 | users:
66 | #...
67 | - name: 'You'
68 | token: 'token'
69 | #...
70 | ```
71 | Token must be a valid and unique uuid v4. You can create one [here](https://www.uuidgenerator.net/version4).
72 |
73 | rTabby supports OAuth2 providers like Github, Gitlab, Google or Microsoft. You can enable them by adding OAuth client and secret through env var in your `docker-compose.yml`.
74 |
75 | ```yml
76 | environment:
77 | - DATABASE_URL=mysql://tabby:tabby@db/tabby
78 | #- GITHUB_APP_CLIENT_ID=
79 | #- GITHUB_APP_CLIENT_SECRET=
80 | #- GITLAB_APP_CLIENT_ID=
81 | #- GITLAB_APP_CLIENT_SECRET=
82 | #- GOOGLE_APP_CLIENT_ID=
83 | #- GOOGLE_APP_CLIENT_SECRET=
84 | #- MICROSOFT_APP_CLIENT_ID=
85 | #- MICROSOFT_APP_CLIENT_SECRET=
86 | ```
87 |
88 | Browse to `http:///login` to authenticate and create your user and token.
89 |
90 | 3. (Optional) SSL/TLS
91 |
92 | Place your key and certificate into `config` directory. Then add the following lines in `docker-compose.yml` :
93 | ```yaml
94 | ports:
95 | - "8080:8080"
96 | environment:
97 | - DATABASE_URL=mysql://tabby:tabby@db/tabby
98 | - SSL_CERTIFICATE=cert.pem
99 | - SSL_CERTIFICATE_KEY=cert.key
100 | volumes:
101 | - ./config:/config
102 | ```
103 |
104 | 4. Miscellaneous
105 |
106 | rtabby-web-api get his configurations from env vars. Available tweaks :
107 |
108 | | ENV VAR | DESCRIPTION | EXAMPLE | DEFAULT |
109 | |---------|-------------|---------|---------|
110 | |DATABASE_URL|Url to database|sqlite:///config/db.sqlite|-|
111 | |CONFIG_FILE|Url to configuration file (Optional)|my_config.yml|users.yml|
112 | |BIND_ADDR|Address listening on (Optional)|0.0.0.0|0.0.0.0|
113 | |BIND_PORT|Port listening on (Optional)|8989|8080|
114 | |SSL_CERTIFICATE|Server certificate (Optional)|cert.pem|None|
115 | |SSL_CERTIFICATE_KEY|Server certificate private key(Optional)|private.key|None|
116 | |CLEANUP_USERS|Delete configurations own by unknown user (Be careful)(Optional)|true|false|
117 | |HTTPS_CALLBACK|Third party login, enable https on callback uri(Optional)|true|false|
118 |
119 | ## Usage
120 |
121 | * To deploy
122 | ```sh
123 | docker compose up -d
124 | ```
125 |
126 | * To shut down your deployment:
127 | ```sh
128 | docker compose down
129 | ```
130 |
131 | ## Contributing
132 |
133 | Build dependencies:
134 | * Docker
135 | * libmysqlclient for the Mysql backend (diesel depend on this)
136 | * Rust 1.65 or later
137 | * Diesel-rs to interact with migrations and schemas
138 |
139 | Feel free to fork, request some features, submit issue or PR. Even give me some tips if you want, to help improve my code and knowledge in Rust ;)
140 |
--------------------------------------------------------------------------------
/build.rs:
--------------------------------------------------------------------------------
1 | fn main() {
2 | #[cfg(feature = "mysql-bundle")]
3 | mysqlclient_static();
4 | }
5 |
6 | #[cfg(feature = "mysql-bundle")]
7 | fn mysqlclient_static() {
8 | println!("cargo:rustc-link-search=native=lib");
9 | println!("cargo:rustc-link-lib=static=mysqlclient");
10 | }
--------------------------------------------------------------------------------
/dev.md:
--------------------------------------------------------------------------------
1 | # Contribute / Development
2 |
3 | ## Dependencies
4 | Rust + Cargo + Diesel-cli (libmysql)
5 | ```
6 | # Ex. Debian
7 | sudo apt update
8 | sudo apt install default-libmysqlclient-dev
9 | cargo install diesel_cli --no-default-features --features mysql
10 | ```
11 |
12 | ## Run in development
13 | Create a .env file with DATABASE_URL pointing to your mariadb server
14 | ```
15 | echo 'DATABASE_URL=mysql://tabby:tabby@db/tabby' >> .env # change DATABASE_URL
16 | cp users.exemple.yml users.yml
17 | cargo run -F dotenv # Use dotenv feature to load the .env
18 | ```
19 |
20 | ## Quick start mariadb server docker
21 | ```
22 | docker run -d --name tabby-mariadb --env MARIADB_USER=tabby --env MARIADB_PASSWORD=tabby --env MARIADB_DATABASE=tabby --env MARIADB_RANDOM_ROOT_PASSWORD=yes -p 3306:3306 mariadb:latest
23 | ```
24 |
25 |
--------------------------------------------------------------------------------
/diesel.toml:
--------------------------------------------------------------------------------
1 | # For documentation on how to configure this file,
2 | # see https://diesel.rs/guides/configuring-diesel-cli
3 |
4 | [print_schema]
5 | file = "src/schema.rs"
6 |
7 | [migrations_directory]
8 | dir = "migrations"
9 |
--------------------------------------------------------------------------------
/docker-compose-sqlite.yml:
--------------------------------------------------------------------------------
1 | services:
2 | rtabby:
3 | container_name: rtabby-web-api
4 |
5 | image: ghcr.io/clem-fern/rtabby-web-api:sqlite
6 | # Minimal image without third party login
7 | #image: ghcr.io/clem-fern/rtabby-web-api:sqlite-minimal
8 |
9 | # Build image from local rtabby repository
10 | #build:
11 | # context: .
12 | # args:
13 | # - FEATURE_FLAGS=-F|sqlite-bundle|-F|all-login
14 | # - GIT_COMMIT=${GIT_COMMIT}
15 | # Optional: Minimal image without third party login
16 | # - FEATURE_FLAGS=-F|sqlite-bundle
17 |
18 | # If running as root, setup your user/volume owner UID and GID
19 | #user: "1000:1000"
20 |
21 | cap_add:
22 | - "CAP_DAC_OVERRIDE"
23 | cap_drop: ['ALL']
24 | read_only: true
25 |
26 | ports:
27 | - "8080:8080"
28 | environment:
29 | - DATABASE_URL=sqlite:///config/db.sqlite
30 | #- GITHUB_APP_CLIENT_ID=
31 | #- GITHUB_APP_CLIENT_SECRET=
32 | #- GITLAB_APP_CLIENT_ID=
33 | #- GITLAB_APP_CLIENT_SECRET=
34 | #- GOOGLE_APP_CLIENT_ID=
35 | #- GOOGLE_APP_CLIENT_SECRET=
36 | #- MICROSOFT_APP_CLIENT_ID=
37 | #- MICROSOFT_APP_CLIENT_SECRET=
38 | volumes:
39 | - ./config:/config
40 | networks:
41 | - frontend
42 | networks:
43 | frontend:
44 | name: rtabby_net_frontend
--------------------------------------------------------------------------------
/docker-compose.yml:
--------------------------------------------------------------------------------
1 | services:
2 | rtabby:
3 | container_name: rtabby-web-api
4 |
5 | image: ghcr.io/clem-fern/rtabby-web-api:latest
6 | # Minimal image without third party login
7 | #image: ghcr.io/clem-fern/rtabby-web-api:latest-minimal
8 |
9 | # Build image from local rtabby repository
10 | #build:
11 | # context: .
12 | # args:
13 | # - GIT_COMMIT=${GIT_COMMIT}
14 | # Optional: Minimal image without third party login
15 | # - FEATURE_FLAGS=-F|mysql-bundle
16 |
17 | # If running as root, setup your user/volume owner UID and GID
18 | #user: "1000:1000"
19 |
20 | cap_add:
21 | - "CAP_DAC_OVERRIDE"
22 | cap_drop: ['ALL']
23 | read_only: true
24 |
25 | ports:
26 | - "8080:8080"
27 | environment:
28 | - DATABASE_URL=mysql://tabby:tabby@db/tabby
29 | #- GITHUB_APP_CLIENT_ID=
30 | #- GITHUB_APP_CLIENT_SECRET=
31 | #- GITLAB_APP_CLIENT_ID=
32 | #- GITLAB_APP_CLIENT_SECRET=
33 | #- GOOGLE_APP_CLIENT_ID=
34 | #- GOOGLE_APP_CLIENT_SECRET=
35 | #- MICROSOFT_APP_CLIENT_ID=
36 | #- MICROSOFT_APP_CLIENT_SECRET=
37 |
38 | volumes:
39 | - ./config:/config
40 | networks:
41 | - frontend
42 | - default
43 | depends_on:
44 | db:
45 | condition: 'service_healthy'
46 | db:
47 | container_name: rtabby-database
48 | image: mariadb:latest
49 | cap_add:
50 | - "CAP_CHOWN"
51 | - "CAP_DAC_OVERRIDE"
52 | - "CAP_SETGID"
53 | - "CAP_SETUID"
54 | cap_drop: ['ALL']
55 | read_only: true
56 | tmpfs:
57 | - /run/mysqld/
58 | - /tmp
59 | volumes:
60 | - database:/var/lib/mysql
61 | environment:
62 | - MARIADB_MYSQL_LOCALHOST_USER=true
63 | - MARIADB_RANDOM_ROOT_PASSWORD=yes
64 | - MARIADB_DATABASE=tabby
65 | - MARIADB_USER=tabby
66 | - MARIADB_PASSWORD=tabby
67 | healthcheck:
68 | test: ["CMD", "/usr/local/bin/healthcheck.sh", "--su-mysql", "--innodb_initialized"]
69 | interval: 5s
70 | timeout: 5s
71 | retries: 20
72 | start_period: 6s
73 | volumes:
74 | database:
75 | networks:
76 | default:
77 | name: rtabby_net_backend
78 | internal: true
79 | frontend:
80 | name: rtabby_net_frontend
--------------------------------------------------------------------------------
/migrations/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Clem-Fern/rtabby-web-api/c44f41839834f716a0d02f49311c6c0da5ddb08b/migrations/.keep
--------------------------------------------------------------------------------
/migrations/2023-01-04-185203_init/down.sql:
--------------------------------------------------------------------------------
1 | DROP TABLE configs;
--------------------------------------------------------------------------------
/migrations/2023-01-04-185203_init/up.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE configs (
2 | id INTEGER auto_increment NOT NULL PRIMARY KEY,
3 | name VARCHAR(255) NOT NULL,
4 | user VARCHAR(255) NULL,
5 | content MEDIUMTEXT NOT NULL DEFAULT '{}',
6 | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
7 | modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
8 | ) AUTO_INCREMENT = 1000;
--------------------------------------------------------------------------------
/migrations/2023-12-21-031738_create_users/down.sql:
--------------------------------------------------------------------------------
1 | -- This file should undo anything in `up.sql`
2 | DROP TABLE users;
--------------------------------------------------------------------------------
/migrations/2023-12-21-031738_create_users/up.sql:
--------------------------------------------------------------------------------
1 | -- Your SQL goes here
2 | CREATE TABLE users (
3 | id INTEGER auto_increment NOT NULL PRIMARY KEY,
4 | name VARCHAR(255) NOT NULL,
5 | user_id VARCHAR(255) NOT NULL,
6 | platform VARCHAR(255) NOT NULL,
7 | token VARCHAR(255) NOT NULL UNIQUE,
8 | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
9 | modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
10 | ) AUTO_INCREMENT = 1000;
--------------------------------------------------------------------------------
/migrations_sqlite/.keep:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Clem-Fern/rtabby-web-api/c44f41839834f716a0d02f49311c6c0da5ddb08b/migrations_sqlite/.keep
--------------------------------------------------------------------------------
/migrations_sqlite/2023-01-04-185203_init/down.sql:
--------------------------------------------------------------------------------
1 | DROP TABLE configs;
--------------------------------------------------------------------------------
/migrations_sqlite/2023-01-04-185203_init/up.sql:
--------------------------------------------------------------------------------
1 | CREATE TABLE configs (
2 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,
3 | name VARCHAR(255) NOT NULL,
4 | user VARCHAR(255) NULL,
5 | content MEDIUMTEXT NOT NULL DEFAULT '{}',
6 | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
7 | modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
8 | );
--------------------------------------------------------------------------------
/migrations_sqlite/2023-12-09-170536_create_users/down.sql:
--------------------------------------------------------------------------------
1 | -- This file should undo anything in `up.sql`
2 | DROP TABLE users;
--------------------------------------------------------------------------------
/migrations_sqlite/2023-12-09-170536_create_users/up.sql:
--------------------------------------------------------------------------------
1 | -- Your SQL goes here
2 | CREATE TABLE users (
3 | id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,
4 | name VARCHAR(255) NOT NULL,
5 | user_id VARCHAR(255) NOT NULL,
6 | platform VARCHAR(255) NOT NULL,
7 | token VARCHAR(255) NOT NULL UNIQUE,
8 | created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
9 | modified_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
10 | );
--------------------------------------------------------------------------------
/scripts/mariadb-static-build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | # https://github.com/Diggsey - https://github.com/sgrif/mysqlclient-sys/issues/17
4 | curl -LO https://downloads.mariadb.com/Connectors/c/connector-c-3.3.3/mariadb-connector-c-3.3.3-src.tar.gz
5 | tar xzf mariadb-connector-c-3.3.3-src.tar.gz
6 | mkdir lib
7 | mkdir build
8 | cd build
9 | sed 's/STRING(STRIP ${extra_dynamic_LDFLAGS} extra_dynamic_LDFLAGS)//' -i ../mariadb-connector-c-3.3.3-src/mariadb_config/CMakeLists.txt
10 | sed 's/LIST(REMOVE_DUPLICATES extra_dynamic_LDFLAGS)//' -i ../mariadb-connector-c-3.3.3-src/mariadb_config/CMakeLists.txt
11 | LDFLAGS=-L/usr/local/musl/lib cmake -DOPENSSL_USE_STATIC_LIBS=1 -DWITH_SSL=/usr/local/musl -DWITH_CURL=0 ../mariadb-connector-c-3.3.3-src
12 | make mariadbclient
13 | cp libmariadb/libmariadbclient.a ../lib/libmysqlclient.a
--------------------------------------------------------------------------------
/scripts/zlib-static-build.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | mkdir zlib
4 | curl -LO https://zlib.net/current/zlib.tar.gz
5 | tar xzf zlib.tar.gz --strip-components=1 -C zlib
6 | cd zlib
7 | ./configure --prefix=/ --static
8 | make
9 | make install
--------------------------------------------------------------------------------
/src/app_config.rs:
--------------------------------------------------------------------------------
1 | use log::warn;
2 | use serde::Deserialize;
3 | use crate::models::user::{LocalUser, UserWithoutToken};
4 | use crate::error::ConfigError;
5 | use std::collections::HashMap;
6 | use std::fs::File;
7 | use std::path::Path;
8 | use std::io::Write;
9 |
10 | #[derive(Clone, Debug, Deserialize)]
11 | pub struct AppConfig {
12 | pub users: Vec,
13 | }
14 |
15 | pub fn load_file(file: &str) -> Result {
16 | let config_file = std::fs::File::open(file).map_err(ConfigError::Io)?;
17 | serde_yaml::from_reader(config_file).map_err(ConfigError::Yaml)
18 | }
19 |
20 | pub fn create_config_file_if_not_exist(file: &str) -> Result<(), ConfigError> {
21 | let path = Path::new(file);
22 | if path.exists() {
23 | Ok(())
24 | } else {
25 | let mut config = File::create(path)?;
26 | write!(config, include_str!("../users.exemple.yml"))?;
27 | Err(ConfigError::NoConfig(String::from(file)))
28 | }
29 | }
30 |
31 | #[derive(Clone, Debug, Default)]
32 | pub struct MappedAppConfig {
33 | pub users: HashMap,
34 | }
35 |
36 | impl From for MappedAppConfig {
37 | fn from(config: AppConfig) -> MappedAppConfig {
38 | let mut users_map: HashMap = HashMap::new();
39 | for user in config.users {
40 | if users_map.contains_key(&user.token) {
41 | warn!("Config : Skipping user {}, which is not unique in the configuration", &user.token);
42 | } else {
43 | users_map.insert(user.token.clone(), user.clone().into());
44 | }
45 | }
46 |
47 | MappedAppConfig {
48 | users: users_map,
49 | }
50 |
51 | }
52 | }
--------------------------------------------------------------------------------
/src/auth.rs:
--------------------------------------------------------------------------------
1 | use crate::app_config::MappedAppConfig;
2 | use actix_web::{dev::ServiceRequest, error::ErrorUnauthorized, web, Error};
3 | use actix_web_httpauth::extractors::bearer::BearerAuth;
4 | use log::warn;
5 |
6 | pub async fn bearer_auth_validator(
7 | req: ServiceRequest,
8 | credentials: BearerAuth,
9 | ) -> Result {
10 | let default = web::Data::new(MappedAppConfig::default());
11 | let users: &Vec = &req
12 | .app_data::>()
13 | .unwrap_or(&default)
14 | .users
15 | .clone()
16 | .into_keys()
17 | .collect();
18 |
19 | let token = String::from(credentials.token());
20 |
21 | if users.contains(&token) {
22 | return Ok(req);
23 | }
24 |
25 | #[cfg(feature = "third-party-login")]
26 | {
27 | use crate::login::models::User;
28 | use crate::storage::DbPool;
29 | use actix_web::error::ErrorInternalServerError;
30 |
31 | let pool = req.app_data::>().unwrap().clone();
32 | let token = token.clone();
33 |
34 | let result = web::block(move || {
35 | let mut conn = pool.get()?;
36 | User::get_user_by_token(&mut conn, &token)
37 | })
38 | .await;
39 |
40 | match result {
41 | Ok(result) => match result {
42 | Ok(result) => {
43 | if let Some(_user) = result {
44 | return Ok(req);
45 | }
46 | }
47 | Err(err) => return Err((ErrorInternalServerError(err), req)),
48 | },
49 | Err(err) => return Err((ErrorInternalServerError(err), req)),
50 | }
51 | }
52 |
53 | warn!(
54 | "Authentification failed for {:?}",
55 | req.connection_info().peer_addr()
56 | );
57 | Err((ErrorUnauthorized("Invalide authentication token !"), req))
58 | }
59 |
--------------------------------------------------------------------------------
/src/env.rs:
--------------------------------------------------------------------------------
1 | #[cfg(feature = "dotenv")]
2 | extern crate dotenvy;
3 |
4 | pub const ENV_CONFIG_FILE: &str = "CONFIG_FILE";
5 | pub const ENV_BIND_ADDR: &str = "BIND_ADDR";
6 | pub const ENV_BIND_PORT: &str = "BIND_PORT";
7 | pub const ENV_SSL_CERTIFICATE: &str = "SSL_CERTIFICATE";
8 | pub const ENV_SSL_CERTIFICATE_KEY: &str = "SSL_CERTIFICATE_KEY";
9 | pub const ENV_CLEANUP_USERS: &str = "CLEANUP_USERS";
10 |
11 | pub const ENV_DATABASE_URL: &str = "DATABASE_URL";
12 |
13 | pub fn init() {
14 | // LOAD ENV VAR from .env if dotenv feature is enable
15 | #[cfg(feature = "dotenv")]
16 | {
17 | dotenvy::dotenv().expect(".env file not found");
18 | }
19 | }
20 |
21 | pub use std::env::*;
22 |
--------------------------------------------------------------------------------
/src/error.rs:
--------------------------------------------------------------------------------
1 | use std::error;
2 | use std::fmt;
3 | use std::io;
4 | use diesel::r2d2;
5 |
6 | use crate::models::DbError;
7 |
8 | #[derive(Debug)]
9 | pub enum StorageError {
10 | Migration(Box),
11 | R2d2(r2d2::PoolError),
12 | #[allow(dead_code)]
13 | Db(DbError),
14 | DbConnection(diesel::ConnectionError)
15 | }
16 |
17 | impl error::Error for StorageError {}
18 |
19 | impl fmt::Display for StorageError {
20 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
21 | match *self {
22 | Self::Migration(ref err) => write!(f, "Failed to initialize databse storage (diesel migrations): {err}"),
23 | Self::R2d2(ref err) => write!(f, "Failed to initialize database storage (r2d2 pool manager): {err}"),
24 | Self::Db(ref err) => write!(f, "Encountered error on database query: {err}"),
25 | Self::DbConnection(ref err) => write!(f, "Encountered error on database connection: {err}"),
26 | }
27 | }
28 | }
29 |
30 | impl From> for StorageError {
31 | fn from(err: Box) -> StorageError {
32 | StorageError::Migration(err)
33 | }
34 | }
35 |
36 | impl From for StorageError {
37 | fn from(err: r2d2::PoolError) -> StorageError {
38 | StorageError::R2d2(err)
39 | }
40 | }
41 |
42 | impl From for StorageError {
43 | fn from(err: diesel::ConnectionError) -> StorageError {
44 | StorageError::DbConnection(err)
45 | }
46 | }
47 |
48 | impl From for StorageError {
49 | fn from(err: diesel::result::Error) -> StorageError {
50 | StorageError::Db(Box::new(err))
51 | }
52 | }
53 |
54 | #[derive(Debug)]
55 | pub enum TlsError {
56 | Io(io::Error),
57 | Rustls(rustls::Error)
58 | }
59 |
60 | impl error::Error for TlsError {}
61 |
62 | impl fmt::Display for TlsError {
63 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
64 | match *self {
65 | Self::Io(ref err) => write!(f, "Encountered IO error while building tls configuration: {err}"),
66 | Self::Rustls(ref err) => write!(f, "Encountered Rustls error while building tls configuration: {err}"),
67 | }
68 | }
69 | }
70 |
71 | impl From for TlsError {
72 | fn from(err: rustls::Error) -> TlsError {
73 | TlsError::Rustls(err)
74 | }
75 | }
76 |
77 | impl From for TlsError {
78 | fn from(err: io::Error) -> TlsError {
79 | TlsError::Io(err)
80 | }
81 | }
82 |
83 | #[derive(Debug)]
84 | pub enum ConfigError {
85 | Io(io::Error),
86 | Yaml(serde_yaml::Error),
87 | #[allow(dead_code)]
88 | DuplicatedEntry(String),
89 | NoConfig(String),
90 | }
91 |
92 | impl error::Error for ConfigError {}
93 |
94 | impl fmt::Display for ConfigError {
95 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
96 | match *self {
97 | Self::Io(ref err) => write!(f, "Encountered IO error while building deserializing configuration: {err}"),
98 | Self::Yaml(ref err) => write!(f, "Encountered Yaml error while building deserializing configuration: {err}"),
99 | Self::DuplicatedEntry(ref entry) => write!(f, "The following data is not unique in configuration: {entry}"),
100 | Self::NoConfig(ref entry) => write!(f, "{entry} configuration not found. The file has beeen created from template. Edit {entry} to add your own users.")
101 | }
102 | }
103 | }
104 |
105 | impl From for ConfigError {
106 | fn from(err: io::Error) -> ConfigError {
107 | ConfigError::Io(err)
108 | }
109 | }
--------------------------------------------------------------------------------
/src/login/env.rs:
--------------------------------------------------------------------------------
1 | pub const ENV_STATIC_FILES_BASE_DIR: &str = "STATIC_FILES_BASE_DIR";
2 | pub const ENV_USE_HTTPS: &str = "USE_HTTPS";
3 | pub const ENV_HTTPS_CALLBACK: &str = "HTTPS_CALLBACK";
4 |
5 | use crate::env as app_env;
6 |
7 | pub fn static_files_base_dir() -> String {
8 | app_env::var(ENV_STATIC_FILES_BASE_DIR).unwrap_or("./web/".to_string())
9 | }
--------------------------------------------------------------------------------
/src/login/error.rs:
--------------------------------------------------------------------------------
1 | use std::error;
2 | use std::fmt;
3 |
4 | #[derive(Debug)]
5 | pub enum ProviderError {
6 | NotFound(String),
7 | }
8 |
9 | impl std::error::Error for ProviderError {}
10 |
11 | impl fmt::Display for ProviderError {
12 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
13 | match *self {
14 | Self::NotFound(ref provider) => {
15 | write!(f, "Specified provider does not exist: {provider}")
16 | }
17 | }
18 | }
19 | }
20 |
21 | #[derive(Debug)]
22 | pub enum OauthError {
23 | UserInfo(reqwest::Error),
24 | AccessToken(reqwest::Error),
25 | }
26 |
27 | impl error::Error for OauthError {}
28 |
29 | impl fmt::Display for OauthError {
30 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
31 | match *self {
32 | Self::UserInfo(ref err) => write!(f, "Unable to retreive OAuth user info: {err}"),
33 | Self::AccessToken(ref err) => write!(f, "Unable to retreive OAuth user access token: {err}"),
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/src/login/mod.rs:
--------------------------------------------------------------------------------
1 | mod env;
2 | pub mod models;
3 | pub mod providers;
4 | pub mod routes;
5 | pub mod services;
6 | pub mod error;
7 |
8 | use crate::env as app_env;
9 |
10 | use actix_web::http::uri::Scheme;
11 |
12 | use log::warn;
13 | #[cfg(feature = "github-login")]
14 | use providers::github;
15 | #[cfg(feature = "gitlab-login")]
16 | use providers::gitlab;
17 | #[cfg(feature = "google-login")]
18 | use providers::google;
19 | #[cfg(feature = "microsoft-login")]
20 | use providers::microsoft;
21 |
22 | use self::providers::OauthInfo;
23 |
24 | #[derive(Clone, Debug)]
25 | pub struct ProvidersConfig {
26 | pub https_callback: bool,
27 | pub available_providers: Vec,
28 | }
29 |
30 | impl ProvidersConfig {
31 |
32 | pub fn get_callback_scheme(&self) -> Scheme {
33 | if self.https_callback {
34 | Scheme::HTTPS
35 | } else {
36 | Scheme::HTTP
37 | }
38 | }
39 |
40 | }
41 |
42 | pub fn get_provider_config() -> ProvidersConfig {
43 |
44 | let https_callback = if app_env::var(env::ENV_HTTPS_CALLBACK).is_ok() {
45 | app_env::var(env::ENV_HTTPS_CALLBACK).unwrap_or(String::from("false")).to_lowercase().parse().unwrap_or(false)
46 | } else if app_env::var(env::ENV_USE_HTTPS).is_ok() {
47 | // DEPRECATED
48 | warn!("\"USE_HTTPS\" deprecated. Use \"HTTPS_CALLBACK\" instead.");
49 | app_env::var(env::ENV_USE_HTTPS).unwrap_or(String::from("0")) == "1"
50 | } else {
51 | false
52 | };
53 |
54 | let mut available_providers: Vec = vec![];
55 |
56 | #[cfg(feature = "github-login")]
57 | if app_env::var(github::env::ENV_GITHUB_APP_CLIENT_ID).is_ok()
58 | && app_env::var(github::env::ENV_GITHUB_APP_CLIENT_SECRET).is_ok()
59 | {
60 | available_providers.push(providers::Provider::Github(OauthInfo {
61 | client_id: app_env::var(github::env::ENV_GITHUB_APP_CLIENT_ID).unwrap(),
62 | client_secret: app_env::var(github::env::ENV_GITHUB_APP_CLIENT_SECRET).unwrap(),
63 | }));
64 | }
65 |
66 | #[cfg(feature = "gitlab-login")]
67 | if app_env::var(gitlab::env::ENV_GITLAB_APP_CLIENT_ID).is_ok()
68 | && app_env::var(gitlab::env::ENV_GITLAB_APP_CLIENT_SECRET).is_ok()
69 | {
70 | available_providers.push(providers::Provider::Gitlab(OauthInfo {
71 | client_id: app_env::var(gitlab::env::ENV_GITLAB_APP_CLIENT_ID).unwrap(),
72 | client_secret: app_env::var(gitlab::env::ENV_GITLAB_APP_CLIENT_SECRET).unwrap(),
73 | }));
74 | }
75 |
76 | #[cfg(feature = "google-login")]
77 | if app_env::var(google::env::ENV_GOOGLE_APP_CLIENT_ID).is_ok()
78 | && app_env::var(google::env::ENV_GOOGLE_APP_CLIENT_SECRET).is_ok()
79 | {
80 | available_providers.push(providers::Provider::Google(OauthInfo {
81 | client_id: app_env::var(google::env::ENV_GOOGLE_APP_CLIENT_ID).unwrap(),
82 | client_secret: app_env::var(google::env::ENV_GOOGLE_APP_CLIENT_SECRET).unwrap(),
83 | }));
84 | }
85 |
86 | #[cfg(feature = "microsoft-login")]
87 | if app_env::var(microsoft::env::ENV_MICROSOFT_APP_CLIENT_ID).is_ok()
88 | && app_env::var(microsoft::env::ENV_MICROSOFT_APP_CLIENT_SECRET).is_ok()
89 | {
90 | available_providers.push(providers::Provider::Microsoft(OauthInfo {
91 | client_id: app_env::var(microsoft::env::ENV_MICROSOFT_APP_CLIENT_ID).unwrap(),
92 | client_secret: app_env::var(microsoft::env::ENV_MICROSOFT_APP_CLIENT_SECRET).unwrap(),
93 | }));
94 | }
95 |
96 | ProvidersConfig {
97 | https_callback,
98 | available_providers
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/src/login/models.rs:
--------------------------------------------------------------------------------
1 | use serde::{Deserialize, Serialize};
2 | use crate::models::DbError;
3 | use crate::models::user::uuid_validator;
4 |
5 | use diesel::{
6 | BoolExpressionMethods, ExpressionMethods, Identifiable, Insertable,
7 | OptionalExtension, QueryDsl, Queryable,
8 | RunQueryDsl,
9 | };
10 | use crate::storage::DbConnection;
11 | use chrono::NaiveDateTime;
12 |
13 | use crate::schema::users;
14 | use crate::schema::users::dsl::users as all_users;
15 |
16 | #[derive(Clone, Debug, Serialize, Deserialize, Identifiable, Queryable)]
17 | #[diesel(table_name = users)]
18 | #[diesel(primary_key(id))]
19 | pub struct User {
20 | pub id: i32,
21 | pub name: String,
22 | pub user_id: String,
23 | pub platform: String,
24 | #[serde(deserialize_with = "uuid_validator")]
25 | pub token: String,
26 |
27 | pub created_at: NaiveDateTime,
28 | pub modified_at: NaiveDateTime,
29 | }
30 |
31 | #[derive(Insertable)]
32 | #[diesel(table_name = users)]
33 | pub struct NewUser {
34 | pub name: String,
35 | pub user_id: String,
36 | pub platform: String,
37 | pub token: String,
38 | }
39 |
40 | impl User {
41 |
42 | pub fn insert_new_user_config(
43 | conn: &mut DbConnection,
44 | new_user: NewUser,
45 | ) -> Result<(), DbError> {
46 |
47 | match conn {
48 | #[cfg(feature = "mysql")]
49 | DbConnection::Mysql(ref mut conn) => {
50 | diesel::insert_into(all_users)
51 | .values(&new_user)
52 | .execute(conn)?;
53 | },
54 | #[cfg(feature = "sqlite")]
55 | DbConnection::Sqlite(ref mut conn) => {
56 | diesel::insert_into(all_users)
57 | .values(&new_user)
58 | .execute(conn)?;
59 | }
60 | }
61 |
62 | Ok(())
63 | }
64 |
65 |
66 | pub fn get_user_by_token(
67 | conn: &mut DbConnection,
68 | in_token: &str,
69 | ) -> Result