├── .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 | ![License](https://img.shields.io/github/license/Clem-Fern/rtabby-web-api) 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, DbError> { 70 | use crate::schema::users::dsl::*; 71 | 72 | Ok(all_users 73 | .filter(token.eq(in_token)) 74 | .first::(conn) 75 | .optional()?) 76 | } 77 | 78 | pub fn get_user( 79 | conn: &mut DbConnection, 80 | in_user_id: &str, 81 | in_platform: &str, 82 | ) -> Result, DbError> { 83 | use crate::schema::users::dsl::*; 84 | 85 | Ok(all_users 86 | .filter(platform.eq(in_platform).and(user_id.eq(in_user_id))) 87 | .first::(conn) 88 | .optional()?) 89 | } 90 | 91 | pub fn delete_user(conn: &mut DbConnection, user: User) -> Result<(), DbError> { 92 | diesel::delete(&user).execute(conn)?; 93 | 94 | Ok(()) 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/login/providers/github.rs: -------------------------------------------------------------------------------- 1 | use crate::login::error::OauthError; 2 | use crate::login::providers::{get_user_info, get_access_token, OauthInfo, OauthUserInfo}; 3 | 4 | pub mod env { 5 | pub const ENV_GITHUB_APP_CLIENT_ID: &str = "GITHUB_APP_CLIENT_ID"; 6 | pub const ENV_GITHUB_APP_CLIENT_SECRET: &str = "GITHUB_APP_CLIENT_SECRET"; 7 | } 8 | 9 | pub const GITHUB_OAUTH_AUTHORIZE_URL: &str = "https://github.com/login/oauth/authorize"; 10 | pub const GITHUB_OAUTH_ACCESS_TOKEN_URL: &str = "https://github.com/login/oauth/access_token"; 11 | pub const GITHUB_OAUTH_USER_INFO_URL: &str = "https://api.github.com/user"; 12 | 13 | pub type GithubOauthUserInfo = OauthUserInfo; 14 | 15 | pub async fn user_info(oauth: &OauthInfo, token: String) -> Result { 16 | let token = get_access_token(GITHUB_OAUTH_ACCESS_TOKEN_URL, token, oauth.client_id.clone(), oauth.client_secret.clone(), "authorization_code", None).await?; 17 | get_user_info(GITHUB_OAUTH_USER_INFO_URL, token).await.map_err(OauthError::UserInfo)?.json::().await.map_err(OauthError::UserInfo) 18 | } -------------------------------------------------------------------------------- /src/login/providers/gitlab.rs: -------------------------------------------------------------------------------- 1 | use crate::login::error::OauthError; 2 | use crate::login::providers::{get_user_info, get_access_token, OauthInfo, OauthUserInfo}; 3 | use actix_web::http::uri::Scheme; 4 | 5 | pub mod env { 6 | pub const ENV_GITLAB_APP_CLIENT_ID: &str = "GITLAB_APP_CLIENT_ID"; 7 | pub const ENV_GITLAB_APP_CLIENT_SECRET: &str = "GITLAB_APP_CLIENT_SECRET"; 8 | } 9 | 10 | pub const GITLAB_OAUTH_AUTHORIZE_URL: &str = "https://gitlab.com/oauth/authorize"; 11 | pub const GITLAB_OAUTH_ACCESS_TOKEN_URL: &str = "https://gitlab.com/oauth/token"; 12 | pub const GITLAB_OAUTH_USER_INFO_URL: &str = "https://gitlab.com/api/v4/user"; 13 | 14 | pub type GitlabOauthUserInfo = OauthUserInfo; 15 | 16 | pub async fn user_info(scheme: Scheme, oauth: &OauthInfo, host: String, token: String) -> Result { 17 | let redirect_uri = format!("{}://{}/login/gitlab/callback", scheme, host); 18 | let token = get_access_token(GITLAB_OAUTH_ACCESS_TOKEN_URL, token, oauth.client_id.clone(), oauth.client_secret.clone(), "authorization_code", Some(redirect_uri)).await?; 19 | get_user_info(GITLAB_OAUTH_USER_INFO_URL, token).await.map_err(OauthError::UserInfo)?.json::().await.map_err(OauthError::UserInfo) 20 | } 21 | -------------------------------------------------------------------------------- /src/login/providers/google.rs: -------------------------------------------------------------------------------- 1 | use crate::login::error::OauthError; 2 | use crate::login::providers::{get_user_info, get_access_token, OauthInfo, OauthUserInfo}; 3 | use actix_web::http::uri::Scheme; 4 | 5 | pub mod env { 6 | pub const ENV_GOOGLE_APP_CLIENT_ID: &str = "GOOGLE_APP_CLIENT_ID"; 7 | pub const ENV_GOOGLE_APP_CLIENT_SECRET: &str = "GOOGLE_APP_CLIENT_SECRET"; 8 | } 9 | 10 | pub const GOOGLE_OAUTH_AUTHORIZE_URL: &str = "https://accounts.google.com/o/oauth2/v2/auth"; 11 | pub const GOOGLE_OAUTH_ACCESS_TOKEN_URL: &str = "https://accounts.google.com/o/oauth2/token"; 12 | pub const GOOGLE_OAUTH_USER_INFO_URL: &str = "https://www.googleapis.com/oauth2/v1/userinfo"; 13 | 14 | pub type GoogleOauthUserInfo = OauthUserInfo; 15 | 16 | pub async fn user_info(scheme: Scheme, oauth: &OauthInfo, host: String, code: String) -> Result { 17 | let redirect_uri = format!("{}://{}/login/google/callback", scheme, host); 18 | let token = get_access_token(GOOGLE_OAUTH_ACCESS_TOKEN_URL, code, oauth.client_id.clone(), oauth.client_secret.clone(), "authorization_code", Some(redirect_uri)).await?; 19 | get_user_info(GOOGLE_OAUTH_USER_INFO_URL, token).await.map_err(OauthError::UserInfo)?.json::().await.map_err(OauthError::UserInfo) 20 | } 21 | -------------------------------------------------------------------------------- /src/login/providers/microsoft.rs: -------------------------------------------------------------------------------- 1 | use crate::login::error::OauthError; 2 | use crate::login::providers::{get_user_info, get_access_token, OauthInfo, OauthUserInfo}; 3 | use actix_web::http::uri::Scheme; 4 | use serde::Deserialize; 5 | 6 | pub mod env { 7 | pub const ENV_MICROSOFT_APP_CLIENT_ID: &str = "MICROSOFT_APP_CLIENT_ID"; 8 | pub const ENV_MICROSOFT_APP_CLIENT_SECRET: &str = "MICROSOFT_APP_CLIENT_SECRET"; 9 | } 10 | 11 | pub const MICROSOFT_OAUTH_AUTHORIZE_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize"; 12 | pub const MICROSOFT_OAUTH_ACCESS_TOKEN_URL: &str = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token"; 13 | pub const MICROSOFT_OAUTH_USER_INFO_URL: &str = "https://graph.microsoft.com/v1.0/me"; 14 | 15 | #[derive(Debug, Deserialize)] 16 | pub struct MicrosoftOauthUserInfo { 17 | id: String, 18 | #[serde(rename = "displayName")] 19 | display_name: String, 20 | } 21 | 22 | 23 | impl From for OauthUserInfo { 24 | fn from(val: MicrosoftOauthUserInfo) -> Self { 25 | OauthUserInfo { 26 | id: val.id, 27 | name: val.display_name, 28 | } 29 | } 30 | } 31 | 32 | pub async fn user_info(scheme: Scheme, oauth: &OauthInfo, host: String, code: String) -> Result { 33 | let redirect_uri = format!("{}://{}/login/microsoft/callback", scheme, host); 34 | let token = get_access_token(MICROSOFT_OAUTH_ACCESS_TOKEN_URL, code, oauth.client_id.clone(), oauth.client_secret.clone(), "authorization_code", Some(redirect_uri)).await?; 35 | get_user_info(MICROSOFT_OAUTH_USER_INFO_URL, token).await.map_err(OauthError::UserInfo)?.json::().await.map_err(OauthError::UserInfo) 36 | } 37 | -------------------------------------------------------------------------------- /src/login/providers/mod.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "github-login")] 2 | pub mod github; 3 | #[cfg(feature = "gitlab-login")] 4 | pub mod gitlab; 5 | #[cfg(feature = "google-login")] 6 | pub mod google; 7 | #[cfg(feature = "microsoft-login")] 8 | pub mod microsoft; 9 | 10 | use serde::{Deserialize, Serialize}; 11 | use std::collections::HashMap; 12 | use std::fmt; 13 | use super::error::OauthError; 14 | 15 | use actix_web::http::uri::Scheme; 16 | 17 | #[derive(Clone, Debug)] 18 | pub struct OauthInfo { 19 | pub client_id: String, 20 | pub client_secret: String, 21 | } 22 | 23 | #[derive(Debug, Deserialize)] 24 | pub struct OauthUserInfo { 25 | id: I, 26 | name: N, 27 | } 28 | 29 | // Gitlab / Github 30 | impl From> for OauthUserInfo { 31 | fn from(val: OauthUserInfo) -> Self { 32 | OauthUserInfo { 33 | id: format!("{}", val.id), 34 | name: val.name, 35 | } 36 | } 37 | } 38 | 39 | #[derive(Clone, Debug, Serialize)] 40 | pub struct Platform { 41 | pub name: String, 42 | pub url: String, 43 | } 44 | 45 | #[derive(Clone, Debug)] 46 | pub enum Provider { 47 | #[cfg(feature = "github-login")] 48 | Github(OauthInfo), 49 | #[cfg(feature = "gitlab-login")] 50 | Gitlab(OauthInfo), 51 | #[cfg(feature = "google-login")] 52 | Google(OauthInfo), 53 | #[cfg(feature = "microsoft-login")] 54 | Microsoft(OauthInfo), 55 | } 56 | 57 | impl Provider { 58 | pub fn name(&self) -> String { 59 | self.to_string().to_lowercase() 60 | } 61 | 62 | pub fn get_oauth_info(&self) -> OauthInfo { 63 | match self { 64 | #[cfg(feature = "github-login")] 65 | Self::Github(oauth) => oauth.clone(), 66 | #[cfg(feature = "gitlab-login")] 67 | Self::Gitlab(oauth) => oauth.clone(), 68 | #[cfg(feature = "google-login")] 69 | Self::Google(oauth) => oauth.clone(), 70 | #[cfg(feature = "microsoft-login")] 71 | Self::Microsoft(oauth) => oauth.clone(), 72 | } 73 | } 74 | 75 | fn get_login_url_params(&self, scheme: Scheme, host: String, state: String) -> Vec<(&str, String)> { 76 | let mut params = vec![ 77 | ("client_id", self.get_oauth_info().client_id), 78 | ("state", state), 79 | ("redirect_uri", format!("{}://{}/login/{}/callback", scheme, host, self.name())), 80 | ]; 81 | 82 | #[cfg(feature = "github-login")] 83 | if !matches!(self, Self::Github(_)) { 84 | params.push(("response_type", "code".to_string())); 85 | } 86 | 87 | match self { 88 | #[cfg(feature = "gitlab-login")] 89 | Self::Gitlab(_) => { 90 | params.push(("scope", "read_user".to_string())); 91 | } 92 | #[cfg(feature = "google-login")] 93 | Self::Google(_) => { 94 | params.push(("scope", "https://www.googleapis.com/auth/userinfo.profile".to_string())); 95 | }, 96 | #[cfg(feature = "microsoft-login")] 97 | Self::Microsoft(_) => { 98 | params.push(("scope", "https://graph.microsoft.com/User.Read".to_string())); 99 | }, 100 | #[cfg(feature = "github-login")] 101 | _ => {}, 102 | } 103 | 104 | params 105 | } 106 | 107 | pub fn get_login_url(&self, scheme: Scheme, host: String, state: String) -> String { 108 | 109 | let params = self.get_login_url_params(scheme, host, state); 110 | 111 | let oauth_url = match self { 112 | #[cfg(feature = "github-login")] 113 | Self::Github(_) => github::GITHUB_OAUTH_AUTHORIZE_URL, 114 | #[cfg(feature = "gitlab-login")] 115 | Self::Gitlab(_) => gitlab::GITLAB_OAUTH_AUTHORIZE_URL, 116 | #[cfg(feature = "google-login")] 117 | Self::Google(_) => google::GOOGLE_OAUTH_AUTHORIZE_URL, 118 | #[cfg(feature = "microsoft-login")] 119 | Self::Microsoft(_) => microsoft::MICROSOFT_OAUTH_AUTHORIZE_URL, 120 | }; 121 | 122 | reqwest::Url::parse_with_params(oauth_url, params).unwrap().to_string() 123 | } 124 | 125 | #[allow(unused_variables)] 126 | pub async fn get_user_info(&self, scheme: Scheme, host: String, token: String) -> Result { 127 | let user_info: OauthUserInfo = match self { 128 | #[cfg(feature = "github-login")] 129 | Self::Github(oauth) => github::user_info(oauth, token).await?.into(), 130 | #[cfg(feature = "gitlab-login")] 131 | Self::Gitlab(oauth) => gitlab::user_info(scheme, oauth, host, token).await?.into(), 132 | #[cfg(feature = "google-login")] 133 | Self::Google(oauth) => google::user_info(scheme, oauth, host, token).await?, 134 | #[cfg(feature = "microsoft-login")] 135 | Self::Microsoft(oauth) => microsoft::user_info(scheme, oauth, host, token).await?.into(), 136 | }; 137 | 138 | Ok(ThirdPartyUserInfo { 139 | id: user_info.id, 140 | name: user_info.name, 141 | platform: self.name(), 142 | }) 143 | } 144 | 145 | } 146 | 147 | impl From for Platform { 148 | fn from(provider: Provider) -> Platform { 149 | Platform { 150 | name: provider.to_string(), 151 | url: format!("login/{}", provider.name()), 152 | } 153 | } 154 | } 155 | 156 | impl fmt::Display for Provider { 157 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 158 | match self { 159 | #[cfg(feature = "github-login")] 160 | Self::Github(_) => write!(f, "Github"), 161 | #[cfg(feature = "gitlab-login")] 162 | Self::Gitlab(_) => write!(f, "Gitlab"), 163 | #[cfg(feature = "google-login")] 164 | Self::Google(_) => write!(f, "Google"), 165 | #[cfg(feature = "microsoft-login")] 166 | Self::Microsoft(_) => write!(f, "Microsoft"), 167 | } 168 | } 169 | } 170 | 171 | #[derive(Debug, Deserialize)] 172 | pub struct Body { 173 | access_token: String, 174 | } 175 | 176 | pub async fn get_user_info(url: &str, token: String) -> Result { 177 | let client = reqwest::Client::new(); 178 | 179 | client 180 | .get(url) 181 | .header("Authorization", format!("Bearer {}", token)) 182 | .header("User-Agent", "actix-web/3.3.2") 183 | .send() 184 | .await 185 | } 186 | 187 | async fn get_access_token( 188 | url: &str, 189 | code: String, 190 | client_id: String, 191 | client_secret: String, 192 | grant_type: &str, 193 | redirect_uri: Option, 194 | ) -> Result { 195 | let client = reqwest::Client::new(); 196 | let mut map = HashMap::new(); 197 | map.insert("code", code); 198 | map.insert("client_id", client_id); 199 | map.insert("client_secret", client_secret); 200 | map.insert("grant_type", String::from(grant_type)); 201 | if let Some(redirect_uri) = redirect_uri { 202 | map.insert("redirect_uri", redirect_uri); 203 | } 204 | 205 | let res = client 206 | .post(url) 207 | .form(&map) 208 | .header("Accept", "application/json") 209 | .send() 210 | .await.map_err(OauthError::AccessToken)?; 211 | 212 | Ok(res.json::().await.map_err(OauthError::AccessToken)?.access_token) 213 | } 214 | 215 | #[derive(Debug, Deserialize)] 216 | pub struct ThirdPartyUserInfo { 217 | pub id: String, 218 | pub name: String, 219 | pub platform: String, 220 | } 221 | -------------------------------------------------------------------------------- /src/login/routes.rs: -------------------------------------------------------------------------------- 1 | use actix_web::http::header::ContentType; 2 | use actix_web::{get, web, Error, HttpRequest, HttpResponse}; 3 | 4 | use serde::Deserialize; 5 | use tera::Tera; 6 | 7 | use crate::login::error::ProviderError; 8 | use crate::login::providers::Platform; 9 | use crate::login::ProvidersConfig; 10 | use crate::storage::DbPool; 11 | use log::{error, info}; 12 | 13 | use crate::login::models::{NewUser, User}; 14 | 15 | use crate::env as app_; 16 | use crate::login::env; 17 | 18 | use uuid::Uuid; 19 | 20 | #[derive(Debug, Deserialize)] 21 | pub struct Params { 22 | code: String, 23 | state: String, 24 | } 25 | 26 | #[get("")] 27 | async fn home( 28 | req: HttpRequest, 29 | providers_config: web::Data, 30 | ) -> Result { 31 | if let Some(token) = req.cookie("token") { 32 | let mut context = tera::Context::new(); 33 | context.insert("token", &token.value()); 34 | let version = env!("CARGO_PKG_VERSION"); 35 | if let Ok(hash) = app_::var("GIT_COMMIT") { 36 | context.insert("version", &format!("{} ({})", version, hash)); 37 | } else { 38 | context.insert("version", &version); 39 | } 40 | let body = Tera::new(&(env::static_files_base_dir() + "templates/**/*")) 41 | .map_err(actix_web::error::ErrorInternalServerError)? 42 | .render("success.html", &context) 43 | .map_err(actix_web::error::ErrorInternalServerError)?; 44 | return Ok(HttpResponse::build(actix_web::http::StatusCode::OK) 45 | .content_type(ContentType::html()) 46 | .body(body)); 47 | } 48 | 49 | let platforms: Vec = providers_config 50 | .available_providers 51 | .clone() 52 | .into_iter() 53 | .map(|p| p.into()) 54 | .collect(); 55 | 56 | let mut context = tera::Context::new(); 57 | context.insert("platforms", &platforms); 58 | let version = env!("CARGO_PKG_VERSION"); 59 | if let Ok(hash) = app_::var("GIT_COMMIT") { 60 | context.insert("version", &format!("{} ({})", version, hash)); 61 | } else { 62 | context.insert("version", &version); 63 | } 64 | let body = Tera::new(&(env::static_files_base_dir() + "templates/**/*")) 65 | .map_err(actix_web::error::ErrorInternalServerError)? 66 | .render("login.html", &context) 67 | .map_err(actix_web::error::ErrorInternalServerError)?; 68 | 69 | Ok(HttpResponse::Ok() 70 | .content_type(ContentType::html()) 71 | .body(body)) 72 | } 73 | 74 | #[get("/{login}")] 75 | async fn login( 76 | provider_name: web::Path, 77 | providers_config: web::Data, 78 | req: HttpRequest, 79 | ) -> Result { 80 | let provider_name = provider_name.into_inner(); 81 | let provider = providers_config 82 | .available_providers 83 | .clone() 84 | .into_iter() 85 | .find(|p| p.name().eq(&provider_name)) 86 | .ok_or(ProviderError::NotFound(provider_name)) 87 | .map_err(actix_web::error::ErrorBadRequest)?; 88 | 89 | let host = req.connection_info().host().to_string(); 90 | let state = Uuid::new_v4().to_string(); 91 | 92 | let login_url = provider.get_login_url(providers_config.get_callback_scheme(), host, state.clone()); 93 | 94 | let mut response = HttpResponse::TemporaryRedirect() 95 | .append_header(("Location", login_url)) 96 | .finish(); 97 | 98 | let ret = response.add_cookie( 99 | &actix_web::cookie::Cookie::build("state", &state) 100 | .path("/") 101 | .expires( 102 | actix_web::cookie::time::OffsetDateTime::now_utc() 103 | + actix_web::cookie::time::Duration::minutes(5), 104 | ) 105 | .finish(), 106 | ); 107 | 108 | if let Err(err) = ret { 109 | error!("add cookie failed: {}", err); 110 | return Ok(HttpResponse::InternalServerError().finish()); 111 | } 112 | Ok(response) 113 | } 114 | 115 | #[get("/{login}/callback")] 116 | async fn login_callback( 117 | provider_name: web::Path, 118 | providers_config: web::Data, 119 | info: web::Query, 120 | pool: web::Data, 121 | req: HttpRequest, 122 | ) -> Result { 123 | let provider_name = provider_name.into_inner(); 124 | let provider = providers_config 125 | .available_providers 126 | .clone() 127 | .into_iter() 128 | .find(|p| p.name().eq(&provider_name)) 129 | .ok_or(ProviderError::NotFound(provider_name)) 130 | .map_err(actix_web::error::ErrorBadRequest)?; 131 | 132 | if let Some(state) = req.cookie("state") { 133 | if state.value() != info.state { 134 | error!("state not match"); 135 | let rediret = HttpResponse::Found() 136 | .append_header(("Location", "/")) 137 | .finish(); 138 | return Ok(rediret); 139 | } 140 | } else { 141 | error!("state not found"); 142 | let rediret = HttpResponse::Found() 143 | .append_header(("Location", "/login")) 144 | .finish(); 145 | return Ok(rediret); 146 | } 147 | 148 | let host = req.connection_info().host().to_string(); 149 | 150 | let user_info = provider 151 | .get_user_info(providers_config.get_callback_scheme(), host, info.code.clone()) 152 | .await 153 | .map_err(actix_web::error::ErrorInternalServerError)?; 154 | 155 | info!("user id: {}", user_info.id); 156 | let mut context = tera::Context::new(); 157 | 158 | let clone_pool = pool.clone(); 159 | let mid = user_info.id.clone(); 160 | let mplatform = user_info.platform.clone(); 161 | let current_user = web::block(move || { 162 | let mut conn = clone_pool.get()?; 163 | User::get_user(&mut conn, &mid, &mplatform) 164 | }) 165 | .await 166 | .map_err(actix_web::error::ErrorInternalServerError)?; 167 | 168 | let current_user_token: String; 169 | if let Ok(Some(current_user)) = current_user { 170 | current_user_token = current_user.token; 171 | context.insert("token", ¤t_user_token); 172 | } else { 173 | let new_uuid = Uuid::new_v4().to_string(); 174 | let new_user = NewUser { 175 | name: user_info.name, 176 | user_id: user_info.id, 177 | platform: user_info.platform, 178 | token: new_uuid.clone(), 179 | }; 180 | web::block(move || { 181 | let mut conn = pool.get()?; 182 | User::insert_new_user_config(&mut conn, new_user) 183 | }) 184 | .await? 185 | .map_err(actix_web::error::ErrorInternalServerError)?; 186 | 187 | context.insert("token", &new_uuid); 188 | current_user_token = new_uuid; 189 | } 190 | 191 | // redirect to login success page with 302, and set cookie 192 | let redirect = HttpResponse::Found() 193 | .append_header(("Location", "/")) 194 | .cookie( 195 | actix_web::cookie::Cookie::build("token", ¤t_user_token) 196 | .path("/") 197 | .finish(), 198 | ) 199 | .finish(); 200 | Ok(redirect) 201 | } 202 | 203 | pub fn user_login_route_config(cfg: &mut web::ServiceConfig) { 204 | cfg.service(login); 205 | cfg.service(login_callback); 206 | } 207 | -------------------------------------------------------------------------------- /src/login/services.rs: -------------------------------------------------------------------------------- 1 | 2 | use actix_files as fs; 3 | use actix_web::web; 4 | use crate::login::env; 5 | use crate::login::routes; 6 | 7 | use actix_session::{SessionMiddleware, storage::CookieSessionStore}; 8 | use actix_web::cookie::Key; 9 | 10 | pub fn login_config(cfg: &mut web::ServiceConfig) { 11 | cfg.service(web::scope("/login") 12 | .wrap(SessionMiddleware::new(CookieSessionStore::default(), Key::generate())) 13 | .service(routes::home) 14 | .configure(routes::user_login_route_config) 15 | ) 16 | .configure(static_files_config); 17 | } 18 | 19 | pub fn static_files_config(cfg: &mut web::ServiceConfig) { 20 | cfg.service(fs::Files::new("/static", env::static_files_base_dir() + "static")); 21 | } -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | extern crate env_logger; 2 | extern crate log; 3 | use log::{info, error, warn}; 4 | 5 | use std::error::Error; 6 | 7 | mod app_config; 8 | mod env; 9 | mod error; 10 | use app_config::{AppConfig, MappedAppConfig}; 11 | mod storage; 12 | use storage::Storage; 13 | 14 | mod auth; 15 | mod models; 16 | mod routes; 17 | mod schema; 18 | 19 | extern crate serde_yaml; 20 | 21 | extern crate actix_web; 22 | use actix_web::{middleware, web, App, HttpServer}; 23 | 24 | #[cfg(feature = "third-party-login")] 25 | mod login; 26 | 27 | extern crate actix_web_httpauth; 28 | use actix_web_httpauth::middleware::HttpAuthentication; 29 | 30 | mod tls; 31 | 32 | #[actix_web::main] 33 | async fn main() -> Result<(), Box> { 34 | 35 | // third-party-login should only be enable by one of the features below (github-login, gitlab-login, google-login, microsoft-login) 36 | #[cfg(feature = "third-party-login")] 37 | { 38 | #[cfg(not(any(feature = "github-login", feature = "gitlab-login", feature = "google-login", feature = "microsoft-login")))] 39 | { 40 | compile_error!("You must enable at least one login provider feature to use the login feature."); 41 | } 42 | } 43 | 44 | // INITIALIZE LOGGING 45 | env_logger::Builder::from_env(env_logger::Env::default().default_filter_or( 46 | if cfg!(debug_assertions) { 47 | "debug" 48 | } else { 49 | "info" 50 | }, 51 | )) 52 | .init(); 53 | info!("Running v{}", env!("CARGO_PKG_VERSION")); 54 | 55 | // LOAD ENV VAR from .env if dotenv feature is enable 56 | env::init(); 57 | 58 | match run_app().await { 59 | Ok(_) => Ok(()), 60 | Err(err) => { 61 | error!("{}", err); 62 | Err(err) 63 | } 64 | } 65 | 66 | } 67 | 68 | async fn run_app() -> Result<(), Box> { 69 | // LOAD CONFIG FILE 70 | let config_file_name = env::var(env::ENV_CONFIG_FILE).unwrap_or(String::from("users.yml")); 71 | 72 | // Check if the config file already exist, else create one and exit 73 | app_config::create_config_file_if_not_exist(&config_file_name)?; 74 | 75 | let config: AppConfig = app_config::load_file(&config_file_name)?; 76 | let config: MappedAppConfig = config.into(); 77 | 78 | info!("{} loaded => {} users found", config_file_name, config.users.len()); 79 | 80 | // INIT DATABASE STORAGE 81 | let storage: Storage = Storage::new(); 82 | storage.init()?; 83 | 84 | // storage clean up on start 85 | if env::var(env::ENV_CLEANUP_USERS).unwrap_or(String::from("false")).to_lowercase().parse().unwrap_or(false) { 86 | warn!("Cleaning up old user configurations from storage."); 87 | storage.cleanup(&config)?; 88 | } 89 | 90 | #[cfg(feature = "third-party-login")] 91 | let providers_config: login::ProvidersConfig = login::get_provider_config(); 92 | 93 | #[cfg(feature = "third-party-login")] 94 | { 95 | info!("Third party login enabled: {} providers found.", providers_config.available_providers.len()); 96 | if providers_config.https_callback { 97 | info!("Third party login enabled: login callback will use HTTPS"); 98 | } 99 | } 100 | 101 | 102 | let pool = storage.pool()?; 103 | let mut server = HttpServer::new(move || { 104 | let app = App::new() 105 | .app_data(web::Data::new(config.clone())) // App Config Data 106 | .app_data(web::Data::new(pool.clone())) // Database Pool Data 107 | .wrap(middleware::Logger::default().log_target(env!("CARGO_PKG_NAME").to_string())) 108 | .configure(api_v1_config); 109 | 110 | #[cfg(feature = "third-party-login")] 111 | if !providers_config.available_providers.is_empty() { 112 | return app.app_data(web::Data::new(providers_config.clone())) 113 | .configure(login::services::login_config); 114 | } 115 | 116 | #[allow(clippy::let_and_return)] 117 | app 118 | 119 | }); 120 | 121 | // socket var 122 | let bind_addr = env::var(env::ENV_BIND_ADDR).unwrap_or(String::from("0.0.0.0")); 123 | let bind_port = env::var(env::ENV_BIND_PORT).unwrap_or(String::from("8080")); 124 | 125 | if env::var(env::ENV_SSL_CERTIFICATE).is_ok() || env::var(env::ENV_SSL_CERTIFICATE_KEY).is_ok() 126 | { 127 | 128 | let ssl_certificate = 129 | env::var(env::ENV_SSL_CERTIFICATE).expect("Missing SSL_CERTIFICATE env var"); 130 | let ssl_certificate_key = 131 | env::var(env::ENV_SSL_CERTIFICATE_KEY).expect("Missing SSL_CERTIFICATE_KEY env var"); 132 | 133 | let config = tls::TLSConfigBuilder::new() 134 | .load_certs(&ssl_certificate)? 135 | .load_private_key(&ssl_certificate_key)? 136 | .build()?; 137 | 138 | info!("Binding HTTPS Listener on {bind_addr}:{bind_port}"); 139 | server = server.bind_rustls_021(format!("{bind_addr}:{bind_port}"), config)?; 140 | } else { 141 | info!("Binding HTTP Listener on {bind_addr}:{bind_port}"); 142 | server = server.bind(format!("{bind_addr}:{bind_port}"))?; 143 | } 144 | 145 | info!("Starting HTTP Listener on {bind_addr}:{bind_port}"); 146 | server.run().await?; 147 | Ok(()) 148 | } 149 | 150 | // configure service & route for api v1 151 | fn api_v1_config(cfg: &mut web::ServiceConfig) { 152 | cfg.service( 153 | web::scope("/api").service( 154 | web::scope("/1") 155 | .configure(routes::user::user_route_config) // USER ROUTE 156 | .configure(routes::config::config_route_config), 157 | ) 158 | // AUTH 159 | .wrap(HttpAuthentication::bearer(auth::bearer_auth_validator)) 160 | ); 161 | } 162 | -------------------------------------------------------------------------------- /src/models/config.rs: -------------------------------------------------------------------------------- 1 | use chrono::{NaiveDateTime, Utc}; 2 | use diesel::sql_types::{Integer, VarChar}; 3 | use diesel::{ 4 | sql_query, AsChangeset, BoolExpressionMethods, ExpressionMethods, Identifiable, Insertable, 5 | NullableExpressionMethods, OptionalExtension, QueryDsl, Queryable, 6 | RunQueryDsl, 7 | }; 8 | use serde::{Deserialize, Serialize}; 9 | 10 | use super::DbError; 11 | 12 | use crate::storage::DbConnection; 13 | 14 | use crate::schema::configs; 15 | use crate::schema::configs::dsl::configs as all_configs; 16 | 17 | #[derive(Clone, Debug, Serialize, Deserialize, Identifiable, Queryable)] 18 | #[diesel(table_name = configs)] 19 | #[diesel(primary_key(id))] 20 | pub struct Config { 21 | pub id: i32, 22 | pub name: String, 23 | 24 | #[serde(default)] 25 | pub user: Option, 26 | 27 | #[serde(default)] 28 | pub content: String, 29 | 30 | pub created_at: NaiveDateTime, 31 | pub modified_at: NaiveDateTime, 32 | } 33 | 34 | impl Config { 35 | pub fn get_all_config_by_user( 36 | conn: &mut DbConnection, 37 | user_id: &str, 38 | ) -> Result, DbError> { 39 | use crate::schema::configs::dsl::*; 40 | 41 | Ok(all_configs 42 | .select((id, name, created_at, modified_at)) 43 | .filter(user.eq(user_id)) 44 | .load::(conn)?) 45 | } 46 | 47 | pub fn insert_new_user_config( 48 | conn: &mut DbConnection, 49 | new_config: NewConfigWithUser, 50 | ) -> Result<(), DbError> { 51 | 52 | match conn { 53 | #[cfg(feature = "mysql")] 54 | DbConnection::Mysql(ref mut conn) => { 55 | diesel::insert_into(all_configs) 56 | .values(&new_config) 57 | .execute(conn)?; 58 | }, 59 | #[cfg(feature = "sqlite")] 60 | DbConnection::Sqlite(ref mut conn) => { 61 | diesel::insert_into(all_configs) 62 | .values(&new_config) 63 | .execute(conn)?; 64 | } 65 | } 66 | 67 | Ok(()) 68 | } 69 | 70 | pub fn insert_new_user_config_or_update( 71 | conn: &mut DbConnection, 72 | config: ConfigWithoutDate, 73 | ) -> Result<(), DbError> { 74 | let query = 75 | sql_query("INSERT INTO configs(id, name) VALUES (?,?) ON DUPLICATE KEY UPDATE name=?;"); 76 | 77 | query 78 | .bind::(config.id) 79 | .bind::(config.name.clone()) 80 | .bind::(config.name) 81 | .execute(conn)?; 82 | 83 | Ok(()) 84 | } 85 | 86 | pub fn get_config_by_id_and_user( 87 | conn: &mut DbConnection, 88 | config_id: i32, 89 | user_id: &str, 90 | ) -> Result, DbError> { 91 | use crate::schema::configs::dsl::*; 92 | 93 | Ok(all_configs 94 | .filter(id.eq(config_id).and(user.nullable().eq(user_id))) 95 | .first::(conn) 96 | .optional()?) 97 | } 98 | 99 | pub fn update_user_config_content( 100 | conn: &mut DbConnection, 101 | config: Config, 102 | new_content: &str, 103 | ) -> Result<(), DbError> { 104 | use crate::schema::configs::dsl::*; 105 | 106 | diesel::update(&config) 107 | .set(( 108 | content.eq(new_content), 109 | modified_at.eq(Utc::now().naive_utc()), 110 | )) 111 | .execute(conn)?; 112 | 113 | Ok(()) 114 | } 115 | 116 | pub fn delete_config(conn: &mut DbConnection, config: Config) -> Result<(), DbError> { 117 | diesel::delete(&config).execute(conn)?; 118 | 119 | Ok(()) 120 | } 121 | } 122 | 123 | #[derive(Clone, Debug, Serialize, Deserialize, Identifiable, Queryable)] 124 | #[diesel(table_name = configs)] 125 | #[diesel(primary_key(id))] 126 | pub struct ConfigWithoutUser { 127 | pub id: i32, 128 | pub name: String, 129 | 130 | #[serde(default)] 131 | pub content: String, 132 | 133 | pub created_at: NaiveDateTime, 134 | pub modified_at: NaiveDateTime, 135 | } 136 | 137 | impl From for ConfigWithoutUser { 138 | fn from(config: Config) -> Self { 139 | ConfigWithoutUser { 140 | id: config.id, 141 | name: config.name, 142 | 143 | content: config.content, 144 | 145 | created_at: config.created_at, 146 | modified_at: config.modified_at, 147 | } 148 | } 149 | } 150 | 151 | #[derive(Clone, Debug, Serialize, Deserialize, Identifiable, Queryable)] 152 | #[diesel(table_name = configs)] 153 | #[diesel(primary_key(id))] 154 | pub struct ConfigWithoutUserAndContent { 155 | pub id: i32, 156 | pub name: String, 157 | 158 | pub created_at: NaiveDateTime, 159 | pub modified_at: NaiveDateTime, 160 | } 161 | 162 | impl From for ConfigWithoutUserAndContent { 163 | fn from(config: Config) -> Self { 164 | ConfigWithoutUserAndContent { 165 | id: config.id, 166 | name: config.name, 167 | 168 | created_at: config.created_at, 169 | modified_at: config.modified_at, 170 | } 171 | } 172 | } 173 | 174 | #[derive( 175 | Clone, Debug, Serialize, Deserialize, Identifiable, Queryable, Insertable, AsChangeset, 176 | )] 177 | #[diesel(table_name = configs)] 178 | #[diesel(primary_key(id))] 179 | pub struct ConfigWithoutDate { 180 | pub id: i32, 181 | pub name: String, 182 | 183 | #[serde(default)] 184 | pub user: Option, 185 | 186 | #[serde(default)] 187 | pub content: String, 188 | } 189 | 190 | #[derive(Clone, Debug, Serialize, Deserialize, Insertable)] 191 | #[diesel(table_name = configs)] 192 | pub struct NewConfig { 193 | pub name: String, 194 | } 195 | 196 | impl NewConfig { 197 | pub fn into_new_user_config_with_user(self, user: String) -> NewConfigWithUser { 198 | NewConfigWithUser { 199 | name: self.name, 200 | user, 201 | } 202 | } 203 | 204 | pub fn into_user_config_without_date(self, id: i32) -> ConfigWithoutDate { 205 | ConfigWithoutDate { 206 | id, 207 | name: self.name, 208 | user: Option::default(), 209 | content: String::default(), 210 | } 211 | } 212 | } 213 | 214 | #[derive(Clone, Debug, Serialize, Deserialize, Insertable)] 215 | #[diesel(table_name = configs)] 216 | pub struct NewConfigWithUser { 217 | name: String, 218 | #[serde(default)] 219 | pub user: String, 220 | } 221 | 222 | #[derive(Clone, Debug, Serialize, Deserialize, Insertable)] 223 | #[diesel(table_name = configs)] 224 | pub struct UpdateConfig { 225 | pub content: String, 226 | } 227 | -------------------------------------------------------------------------------- /src/models/mod.rs: -------------------------------------------------------------------------------- 1 | pub type DbError = Box; 2 | 3 | pub mod config; 4 | pub mod user; -------------------------------------------------------------------------------- /src/models/user.rs: -------------------------------------------------------------------------------- 1 | use serde::{de, Deserialize, Serialize}; 2 | use uuid::Uuid; 3 | 4 | #[derive(Clone, Debug, Deserialize)] 5 | pub struct LocalUser { 6 | pub name: String, 7 | #[serde(deserialize_with = "uuid_validator")] 8 | pub token: String, 9 | } 10 | 11 | #[derive(Clone, Debug, Deserialize, Serialize)] 12 | pub struct UserWithoutToken { 13 | pub name: String, 14 | } 15 | 16 | impl From for UserWithoutToken { 17 | fn from(user: LocalUser) -> Self { 18 | UserWithoutToken { 19 | name: user.name, 20 | } 21 | } 22 | } 23 | 24 | pub fn uuid_validator<'de, D>(d: D) -> Result 25 | where 26 | D: de::Deserializer<'de>, 27 | { 28 | let value = String::deserialize(d)?; 29 | 30 | if Uuid::parse_str(&value).is_err() { 31 | return Err(de::Error::invalid_value( 32 | de::Unexpected::Str(&value), 33 | &"a valid UUIDv4", 34 | )); 35 | } 36 | 37 | Ok(value) 38 | } 39 | -------------------------------------------------------------------------------- /src/routes/config.rs: -------------------------------------------------------------------------------- 1 | use actix_web::{delete, get, patch, post, web, Error, HttpResponse}; 2 | use actix_web_httpauth::extractors::bearer::BearerAuth; 3 | 4 | use crate::storage::DbPool; 5 | 6 | use crate::models::config::{Config, ConfigWithoutUser, ConfigWithoutUserAndContent, NewConfig, UpdateConfig}; 7 | 8 | #[get("/configs")] 9 | async fn show_configs(auth: BearerAuth, pool: web::Data) -> Result { 10 | let token = String::from(auth.token()); 11 | 12 | let mtoken = token.clone(); 13 | let mpool = pool.clone(); 14 | let configs = web::block(move || { 15 | let mut conn = mpool.get()?; 16 | Config::get_all_config_by_user(&mut conn, &mtoken) 17 | }) 18 | .await? 19 | .map_err(actix_web::error::ErrorInternalServerError)?; 20 | 21 | Ok(HttpResponse::Ok().json(configs)) 22 | } 23 | 24 | #[post("/configs")] // create a new config 25 | async fn new_config( 26 | auth: BearerAuth, 27 | pool: web::Data, 28 | json: web::Json, 29 | ) -> Result { 30 | let token = auth.token(); 31 | let new_user_config = json 32 | .into_inner() 33 | .into_new_user_config_with_user(String::from(token)); 34 | 35 | web::block(move || { 36 | let mut conn = pool.get()?; 37 | Config::insert_new_user_config(&mut conn, new_user_config) 38 | }) 39 | .await? 40 | .map_err(actix_web::error::ErrorInternalServerError)?; 41 | 42 | Ok(HttpResponse::Ok().finish()) 43 | } 44 | 45 | #[get("/configs/{id}")] 46 | async fn get_config( 47 | auth: BearerAuth, 48 | pool: web::Data, 49 | path: web::Path, 50 | ) -> Result { 51 | let token = String::from(auth.token()); 52 | let id = path.into_inner(); 53 | 54 | let result = web::block(move || { 55 | let mut conn = pool.get()?; 56 | Config::get_config_by_id_and_user(&mut conn, id, &token) 57 | }) 58 | .await? 59 | .map_err(actix_web::error::ErrorInternalServerError)?; 60 | 61 | match result { 62 | Some(config) => Ok(HttpResponse::Ok().json(Into::::into(config))), 63 | None => Ok(HttpResponse::Unauthorized().finish()), 64 | } 65 | } 66 | 67 | #[patch("/configs/{id}")] 68 | async fn update_config( 69 | auth: BearerAuth, 70 | pool: web::Data, 71 | path: web::Path, 72 | json: web::Json, 73 | ) -> Result { 74 | let token = String::from(auth.token()); 75 | let id = path.into_inner(); 76 | let updated_config = json.into_inner(); 77 | 78 | let t = token.clone(); 79 | let p = pool.clone(); 80 | let config = web::block(move || { 81 | let mut conn = p.get()?; 82 | Config::get_config_by_id_and_user(&mut conn, id, &t) 83 | }) 84 | .await? 85 | .map_err(actix_web::error::ErrorInternalServerError)?; 86 | 87 | if config.is_none() { 88 | return Ok(HttpResponse::Unauthorized().finish()); 89 | } 90 | 91 | let config = config.unwrap(); 92 | let c = config.clone(); 93 | web::block(move || { 94 | // update config content 95 | let mut conn = pool.get()?; 96 | Config::update_user_config_content(&mut conn, c, &updated_config.content) 97 | }) 98 | .await? 99 | .map_err(actix_web::error::ErrorInternalServerError)?; 100 | 101 | Ok(HttpResponse::Ok().json(Into::::into(config.clone()))) 102 | } 103 | 104 | #[delete("/configs/{id}")] 105 | async fn delete_config( 106 | auth: BearerAuth, 107 | pool: web::Data, 108 | path: web::Path, 109 | ) -> Result { 110 | let token = String::from(auth.token()); 111 | let id = path.into_inner(); 112 | 113 | let t = token.clone(); 114 | let p = pool.clone(); 115 | let config = web::block(move || { 116 | let mut conn = p.get()?; 117 | Config::get_config_by_id_and_user(&mut conn, id, &t) 118 | }) 119 | .await? 120 | .map_err(actix_web::error::ErrorInternalServerError)?; 121 | 122 | if config.is_none() { 123 | return Ok(HttpResponse::Unauthorized().finish()); 124 | } 125 | 126 | let config = config.unwrap(); 127 | web::block(move || { 128 | // delete config 129 | let mut conn = pool.get()?; 130 | Config::delete_config(&mut conn, config) 131 | }) 132 | .await? 133 | .map_err(actix_web::error::ErrorInternalServerError)?; 134 | 135 | Ok(HttpResponse::Ok().finish()) 136 | } 137 | 138 | pub fn config_route_config(cfg: &mut web::ServiceConfig) { 139 | cfg.service(show_configs) 140 | .service(new_config) 141 | .service(get_config) 142 | .service(update_config) 143 | .service(delete_config); 144 | } 145 | -------------------------------------------------------------------------------- /src/routes/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod user; 2 | pub mod config; -------------------------------------------------------------------------------- /src/routes/user.rs: -------------------------------------------------------------------------------- 1 | use actix_web::{get, web, Error, HttpResponse}; 2 | use actix_web_httpauth::extractors::bearer::BearerAuth; 3 | 4 | use crate::app_config::MappedAppConfig; 5 | 6 | #[cfg(feature = "third-party-login")] 7 | use crate::login::models::User; 8 | use crate::storage::DbPool; 9 | 10 | #[allow(unused_variables)] 11 | #[get("/user")] 12 | async fn get_user( 13 | auth: BearerAuth, 14 | app_config: web::Data, 15 | pool: web::Data, 16 | ) -> Result { 17 | let token = String::from(auth.token()); 18 | #[cfg(feature = "third-party-login")] 19 | { 20 | let clone_pool = pool.clone(); 21 | let clone_token = token.clone(); 22 | let current_user = web::block(move || { 23 | let mut conn = clone_pool.get()?; 24 | User::get_user_by_token(&mut conn, &clone_token) 25 | }).await.map_err(actix_web::error::ErrorInternalServerError)?; 26 | if let Ok(Some(current_user)) = current_user { 27 | return Ok(HttpResponse::Ok().json(current_user)) 28 | } 29 | } 30 | 31 | match app_config.users.get(&token) { 32 | Some(user) => Ok(HttpResponse::Ok().json(user)), 33 | None => Ok(HttpResponse::Unauthorized().finish()), 34 | } 35 | } 36 | 37 | pub fn user_route_config(cfg: &mut web::ServiceConfig) { 38 | cfg.service(get_user); 39 | } 40 | -------------------------------------------------------------------------------- /src/schema.rs: -------------------------------------------------------------------------------- 1 | // @generated automatically by Diesel CLI. 2 | 3 | diesel::table! { 4 | configs (id) { 5 | id -> Integer, 6 | name -> Text, 7 | user -> Nullable, 8 | content -> Text, 9 | created_at -> Timestamp, 10 | modified_at -> Timestamp, 11 | } 12 | } 13 | 14 | diesel::table! { 15 | users (id) { 16 | id -> Integer, 17 | name -> Text, 18 | user_id -> Text, 19 | platform -> Text, 20 | token -> Text, 21 | created_at -> Timestamp, 22 | modified_at -> Timestamp, 23 | } 24 | } 25 | 26 | diesel::allow_tables_to_appear_in_same_query!( 27 | configs, 28 | users, 29 | ); 30 | -------------------------------------------------------------------------------- /src/storage.rs: -------------------------------------------------------------------------------- 1 | extern crate diesel; 2 | use std::error::Error; 3 | 4 | use diesel::prelude::*; 5 | #[cfg(feature = "mysql")] 6 | use diesel::mysql::Mysql; 7 | #[cfg(feature = "sqlite")] 8 | use diesel::sqlite::Sqlite; 9 | 10 | 11 | extern crate diesel_migrations; 12 | use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness}; 13 | use log::info; 14 | use diesel::r2d2::{Pool, ConnectionManager}; 15 | 16 | use crate::app_config::MappedAppConfig; 17 | use crate::env; 18 | use crate::error; 19 | 20 | #[cfg(feature = "mysql")] 21 | const MYSQL_MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations"); 22 | #[cfg(feature = "sqlite")] 23 | const SQLITE_MIGRATIONS: EmbeddedMigrations = embed_migrations!("./migrations_sqlite"); 24 | 25 | #[derive(diesel::MultiConnection)] 26 | pub enum DbConnection { 27 | #[cfg(feature = "mysql")] 28 | Mysql(diesel::MysqlConnection), 29 | #[cfg(feature = "sqlite")] 30 | Sqlite(diesel::SqliteConnection), 31 | } 32 | 33 | pub type DbPool = Pool>; 34 | 35 | 36 | 37 | #[derive(Clone)] 38 | pub struct Storage { 39 | url: String, 40 | } 41 | 42 | impl Storage { 43 | pub fn new() -> Self { 44 | let database_url = env::var(env::ENV_DATABASE_URL).unwrap_or("mysql://tabby:tabby@db/tabby".to_string()); 45 | Storage { url: database_url } 46 | } 47 | 48 | pub fn url(&self) -> &String { 49 | &self.url 50 | } 51 | 52 | pub fn init(&self) -> Result<(), error::StorageError> { 53 | let mut conn = establish_connection(self.url().as_str())?; 54 | 55 | // RUN PENDING MIGRATIONS 56 | match conn { 57 | #[cfg(feature = "mysql")] 58 | DbConnection::Mysql(ref mut conn) => { 59 | run_mysql_migrations(conn)?; 60 | }, 61 | #[cfg(feature = "sqlite")] 62 | DbConnection::Sqlite(ref mut conn) => { 63 | run_sqlite_migrations(conn)?; 64 | } 65 | } 66 | 67 | Ok(()) 68 | } 69 | 70 | pub fn cleanup(&self, app_config: &MappedAppConfig) -> Result<(), error::StorageError> { 71 | let mut conn = establish_connection(self.url().as_str())?; 72 | 73 | use crate::schema::configs::dsl::*; 74 | 75 | diesel::delete(configs.filter(user.ne_all(app_config.users.keys()))).execute(&mut conn)?; 76 | 77 | Ok(()) 78 | } 79 | 80 | pub fn pool(&self) -> Result { 81 | let pool = Pool::new(ConnectionManager::new(self.url().clone()))?; 82 | 83 | Ok(pool) 84 | } 85 | } 86 | 87 | #[cfg(feature = "mysql")] 88 | fn run_mysql_migrations( 89 | connection: &mut impl MigrationHarness, 90 | ) -> Result<(), Box> { 91 | if connection.has_pending_migration(MYSQL_MIGRATIONS)? { 92 | info!("Running pending migrations."); 93 | connection.run_pending_migrations(MYSQL_MIGRATIONS)?; 94 | } 95 | 96 | Ok(()) 97 | } 98 | 99 | #[cfg(feature = "sqlite")] 100 | fn run_sqlite_migrations( 101 | connection: &mut impl MigrationHarness, 102 | ) -> Result<(), Box> { 103 | if connection.has_pending_migration(SQLITE_MIGRATIONS)? { 104 | info!("Running pending migrations."); 105 | connection.run_pending_migrations(SQLITE_MIGRATIONS)?; 106 | } 107 | 108 | Ok(()) 109 | } 110 | 111 | pub fn establish_connection(url: &str) -> Result { 112 | DbConnection::establish(url) 113 | } 114 | -------------------------------------------------------------------------------- /src/tls.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fs::File, 3 | io::{BufReader, Error, ErrorKind}, 4 | iter, 5 | }; 6 | 7 | extern crate rustls; 8 | use rustls::{Certificate, PrivateKey, ServerConfig}; 9 | extern crate rustls_pemfile; 10 | use rustls_pemfile::{read_one, Item}; 11 | 12 | use log::warn; 13 | 14 | use crate::error; 15 | 16 | pub struct TLSConfigBuilder { 17 | cert: Option>, 18 | key: Option, 19 | } 20 | 21 | impl TLSConfigBuilder { 22 | pub fn new() -> Self { 23 | TLSConfigBuilder { 24 | cert: None, 25 | key: None, 26 | } 27 | } 28 | 29 | pub fn load_certs(mut self, filename: &str) -> Result { 30 | let certfile = File::open(filename).map_err(|e| { 31 | Error::new( 32 | ErrorKind::Other, 33 | format!("failed to open certificate file {filename}: {e}"), 34 | ) 35 | })?; 36 | let mut reader = BufReader::new(certfile); 37 | 38 | let certs: Vec = rustls_pemfile::certs(&mut reader) 39 | .map_err(|e| { 40 | Error::new( 41 | ErrorKind::Other, 42 | format!( 43 | "rustls_pemfile failed to collect certificates from {filename}: {e}" 44 | ), 45 | ) 46 | })? 47 | .iter() 48 | .map(|v| rustls::Certificate(v.clone())) 49 | .collect(); 50 | 51 | if certs.is_empty() { 52 | return Err(error::TlsError::Io(Error::new( 53 | ErrorKind::Other, 54 | format!( 55 | "no certificates found in {filename}" 56 | ), 57 | ))); 58 | } 59 | 60 | self.cert = Some(certs); 61 | 62 | Ok(self) 63 | } 64 | 65 | pub fn load_private_key(mut self, filename: &str) -> Result { 66 | let keyfile = File::open(filename).map_err(|e| { 67 | Error::new( 68 | ErrorKind::Other, 69 | format!("failed to open certificate file {filename}: {e}"), 70 | ) 71 | })?; 72 | let mut reader = BufReader::new(keyfile); 73 | 74 | let mut keys: Vec = Vec::new(); 75 | 76 | for item in iter::from_fn(|| read_one(&mut reader).transpose()) { 77 | match item.map_err(|e| { 78 | Error::new( 79 | ErrorKind::Other, 80 | format!( 81 | "rustls_pemfile failed to collect private key from {filename}: {e}" 82 | ), 83 | ) 84 | })? { 85 | Item::RSAKey(key) => keys.push(PrivateKey(key)), 86 | Item::PKCS8Key(key) => keys.push(PrivateKey(key)), 87 | Item::ECKey(key) => keys.push(PrivateKey(key)), 88 | _ => warn!("unhandled key found in {}", filename), 89 | } 90 | } 91 | 92 | if keys.is_empty() { 93 | return Err(error::TlsError::Io(Error::new( 94 | ErrorKind::Other, 95 | format!( 96 | "no keys found in {filename} (encrypted keys not supported)" 97 | ), 98 | ))); 99 | } 100 | 101 | if keys.len() > 1 { 102 | return Err(error::TlsError::Io(Error::new( 103 | ErrorKind::Other, 104 | format!( 105 | "expected a single private key in {filename}" 106 | ), 107 | ))); 108 | } 109 | 110 | self.key = Some(keys.first().unwrap().to_owned()); 111 | 112 | Ok(self) 113 | } 114 | 115 | pub fn build(self) -> Result { 116 | ServerConfig::builder() 117 | .with_safe_defaults() 118 | .with_no_client_auth() 119 | .with_single_cert(self.cert.unwrap(), self.key.unwrap()).map_err(error::TlsError::Rustls) 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /users.exemple.yml: -------------------------------------------------------------------------------- 1 | # declare users 2 | users: 3 | - name: 'Clem-Fern' 4 | token: 'dfb3863c-4b06-4fb9-8c47-e2d2c6b5bb29' # Unique uuidv4 token (https://www.uuidgenerator.net/version4) 5 | 6 | - name: 'Eugeny' 7 | token: 'b841dbba-42c6-4161-9735-dc1303583743' # Unique uuidv4 token (https://www.uuidgenerator.net/version4) -------------------------------------------------------------------------------- /web/static/favicon.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /web/static/script.js: -------------------------------------------------------------------------------- 1 | function copyToken() { 2 | var tokenDisplay = document.getElementById('tokenDisplay'); 3 | var tempInput = document.createElement('input'); 4 | tempInput.value = tokenDisplay.innerText; 5 | document.body.appendChild(tempInput); 6 | tempInput.select(); 7 | document.execCommand('copy'); 8 | document.body.removeChild(tempInput); 9 | 10 | // Change button text to "Copied" 11 | var copyBtn = document.querySelector('.copy-btn'); 12 | copyBtn.innerText = 'Copied'; 13 | } 14 | 15 | function logout() { 16 | // Delete token from cookies (assuming you are using cookies for storing the token) 17 | document.cookie = 'token=; Max-Age=0' 18 | // Redirect to the home page or any desired URL 19 | window.location.href = "/"; 20 | } -------------------------------------------------------------------------------- /web/static/styles.css: -------------------------------------------------------------------------------- 1 | body { 2 | font-family: 'Arial', sans-serif; 3 | background-color: #f4f4f4; 4 | margin: 0; 5 | padding: 0; 6 | display: flex; 7 | align-items: center; 8 | justify-content: center; 9 | height: 100vh; 10 | } 11 | 12 | .container { 13 | text-align: center; 14 | max-width: 400px; 15 | width: 100%; 16 | padding: 20px; 17 | background-color: #fff; 18 | border-radius: 8px; 19 | box-shadow: 0 0 10px rgba(0, 0, 0, 0.1); 20 | } 21 | 22 | h1 { 23 | color: #333; 24 | } 25 | 26 | .btn { 27 | display: inline-block; 28 | padding: 10px 20px; 29 | font-size: 16px; 30 | background-color: #4CAF50; 31 | color: #fff; 32 | text-decoration: none; 33 | border-radius: 5px; 34 | cursor: pointer; 35 | margin-top: 20px; 36 | } 37 | 38 | .success-container, 39 | .error-container { 40 | text-align: center; 41 | } 42 | 43 | .token-display { 44 | background-color: #dff0d8; 45 | padding: 10px; 46 | border-radius: 5px; 47 | margin-bottom: 20px; 48 | } 49 | 50 | .copy-btn { 51 | background-color: #5bc0de; 52 | margin-left: 10px; 53 | width: 100px; 54 | } 55 | 56 | .logout-btn { 57 | margin-left: 10px; 58 | width: 100px; 59 | background-color: #e74c3c; /* 红色系,可以根据需要选择其他颜色 */ 60 | color: #fff; /* 文本颜色,白色在深色背景上通常更易读 */ 61 | } 62 | 63 | .logout-btn:hover { 64 | background-color: #c0392b; /* 鼠标悬停时的背景颜色,可以选择稍深的色调 */ 65 | } 66 | 67 | .error-container { 68 | color: #a94442; 69 | } 70 | 71 | .version { 72 | margin-top: 20px; 73 | color: #ccc; 74 | } -------------------------------------------------------------------------------- /web/templates/login.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Tabby - Login To Get Sync Token 7 | 8 | 9 | 10 | 11 | 12 |
13 |

Login to get sync token

14 | {% for platform in platforms %} 15 | Login with {{ platform.name }} 16 |
17 | {% endfor %} 18 |
19 |
20 |
{{ version }}
21 |
22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /web/templates/success.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Tabby - Login To Get Sync Token 7 | 8 | 9 | 10 | 11 | 12 |
13 |

Your token is

14 |
{{ token }}
15 | 16 | 17 | 18 |
19 |
20 |
{{ version }}
21 |
22 | 23 | 24 | 25 | 26 | 27 | --------------------------------------------------------------------------------