17 Commits
Author SHA1 Message Date
phoenix 010ee6aef5 Adding license (#23)
schedtxt_auth Build / Rustfmt (push) Successful in 57s
schedtxt_auth Build / Test Suite (push) Successful in 1m23s
schedtxt_auth Build / Check (push) Successful in 1m23s
schedtxt_auth Build / build (push) Successful in 1m20s
schedtxt_auth Build / Clippy (push) Successful in 1m47s
Reviewed-on: #23
2026-07-14 15:27:37 -04:00
phoenix 039609a99c Dependency name change (#22)
schedtxt_auth Build / Rustfmt (push) Successful in 46s
schedtxt_auth Build / Check (push) Successful in 1m35s
schedtxt_auth Build / Clippy (push) Successful in 1m4s
schedtxt_auth Build / Test Suite (push) Successful in 2m6s
schedtxt_auth Build / build (push) Successful in 4m28s
Reviewed-on: #22
2026-07-13 17:24:39 -04:00
phoenix b3899c1480 Update rust (#21)
textsender_auth Build / Rustfmt (push) Successful in 44s
textsender_auth Build / Check (push) Successful in 1m42s
textsender_auth Build / Test Suite (push) Successful in 2m5s
textsender_auth Build / Clippy (push) Successful in 1m38s
textsender_auth Build / build (push) Successful in 3m5s
Reviewed-on: phoenix/textsender_auth#21
2026-07-10 17:42:38 -04:00
phoenix 3423c1eeb1 Update rust (#20)
Rust Build / Rustfmt (push) Successful in 48s
Rust Build / Check (push) Successful in 1m30s
Rust Build / Test Suite (push) Successful in 2m29s
Rust Build / Clippy (push) Successful in 1m47s
Rust Build / build (push) Successful in 2m13s
Rust Build / Check (pull_request) Successful in 3m34s
Rust Build / Rustfmt (pull_request) Successful in 36s
Rust Build / Clippy (pull_request) Successful in 38s
Reviewed-on: phoenix/textsender_auth#20
2026-07-06 22:03:16 -04:00
phoenix 21bfaf7657 Update dependencies (#19)
Rust Build / Rustfmt (push) Successful in 50s
Rust Build / Check (push) Successful in 1m7s
Rust Build / Test Suite (push) Failing after 2m2s
Rust Build / Clippy (push) Successful in 1m27s
Rust Build / build (push) Successful in 1m30s
Reviewed-on: phoenix/textsender_auth#19
2026-07-04 20:00:46 -04:00
phoenix 9dba08f179 Get User profile endpoint (#18)
Rust Build / Rustfmt (push) Successful in 38s
Rust Build / Test Suite (push) Failing after 1m43s
Rust Build / Check (push) Successful in 1m52s
Rust Build / Clippy (push) Successful in 1m10s
Rust Build / build (push) Successful in 2m4s
Rust Build / Rustfmt (pull_request) Successful in 1m9s
Rust Build / Clippy (pull_request) Successful in 1m17s
Rust Build / Check (pull_request) Successful in 1m36s
Reviewed-on: phoenix/textsender_auth#18
2026-07-01 22:37:25 -04:00
phoenix 438b19e170 Update dependencies (#17)
Rust Build / Rustfmt (push) Successful in 44s
Rust Build / Clippy (push) Successful in 1m10s
Rust Build / Test Suite (push) Failing after 2m0s
Rust Build / build (push) Successful in 2m7s
Rust Build / Check (push) Successful in 1m12s
Rust Build / Check (pull_request) Has been cancelled
Rust Build / Clippy (pull_request) Has been cancelled
Rust Build / Rustfmt (pull_request) Has been cancelled
Reviewed-on: phoenix/textsender_auth#17
2026-06-27 17:47:19 -04:00
phoenix 69d908bac3 Update (#16)
Rust Build / Rustfmt (push) Successful in 1m26s
Rust Build / build (push) Successful in 1m45s
Rust Build / Check (push) Successful in 2m14s
Rust Build / Test Suite (push) Successful in 2m18s
Rust Build / Clippy (push) Successful in 1m40s
Rust Build / Rustfmt (pull_request) Successful in 54s
Rust Build / Check (pull_request) Successful in 1m28s
Rust Build / Clippy (pull_request) Successful in 1m41s
Reviewed-on: phoenix/textsender_auth#16
2026-06-14 18:51:51 -04:00
phoenix 7d2faba4f2 Update packages (#15)
Rust Build / Rustfmt (push) Successful in 59s
Rust Build / Test Suite (push) Successful in 1m50s
Rust Build / Clippy (push) Successful in 1m12s
Rust Build / Check (push) Successful in 2m30s
Rust Build / build (push) Successful in 1m45s
Reviewed-on: phoenix/textsender_auth#15
2026-06-13 19:06:51 -04:00
phoenix e9b59fc1dd Update packages (#14)
Rust Build / Rustfmt (push) Successful in 59s
Rust Build / Test Suite (push) Successful in 1m34s
Rust Build / Check (push) Successful in 2m1s
Rust Build / Clippy (push) Successful in 1m13s
Rust Build / build (push) Successful in 2m17s
Reviewed-on: phoenix/textsender_auth#14
2026-06-13 17:01:54 -04:00
phoenix 1ab7bd4ae1 gitignore cleanup (#13)
Rust Build / Rustfmt (push) Successful in 41s
Rust Build / Check (push) Successful in 1m31s
Rust Build / Clippy (push) Successful in 1m46s
Rust Build / Test Suite (push) Successful in 2m35s
Rust Build / build (push) Successful in 1m49s
Rust Build / Rustfmt (pull_request) Successful in 40s
Rust Build / Check (pull_request) Successful in 1m44s
Rust Build / Test Suite (pull_request) Successful in 1m31s
Rust Build / Clippy (pull_request) Successful in 2m10s
Rust Build / build (pull_request) Successful in 3m26s
Reviewed-on: phoenix/textsender_auth#13
2026-06-13 12:54:17 -04:00
phoenix d83591c8a4 Updating package name (#12)
Rust Build / Rustfmt (push) Successful in 52s
Rust Build / Check (push) Successful in 1m21s
Rust Build / Test Suite (push) Successful in 1m52s
Rust Build / Clippy (push) Successful in 2m0s
Rust Build / build (push) Successful in 1m42s
Reviewed-on: phoenix/textsender-auth#12
2026-06-13 12:42:25 -04:00
phoenix 0cab4e8530 Update postgresql port (#11)
Rust Build / Test Suite (push) Successful in 1m6s
Rust Build / Check (push) Successful in 1m7s
Rust Build / Rustfmt (push) Successful in 1m59s
Rust Build / Clippy (push) Successful in 1m43s
Rust Build / build (push) Successful in 2m28s
Reviewed-on: phoenix/textsender-auth#11
2026-06-13 11:26:43 -04:00
phoenix b678c098cb Update name of user endpoint (#9)
Rust Build / Test Suite (push) Successful in 48s
Rust Build / Rustfmt (push) Successful in 1m23s
Rust Build / Check (push) Successful in 1m35s
Rust Build / Clippy (push) Successful in 1m13s
Rust Build / build (push) Successful in 2m57s
Rust Build / Rustfmt (pull_request) Successful in 1m15s
Rust Build / Test Suite (pull_request) Successful in 1m38s
Rust Build / Check (pull_request) Successful in 1m50s
Rust Build / Clippy (pull_request) Successful in 1m24s
Rust Build / build (pull_request) Successful in 2m59s
Reviewed-on: phoenix/textsender-auth#9
2026-06-12 17:27:46 -04:00
phoenix e3ee24c131 Update password endpoint (#8)
Rust Build / Rustfmt (push) Successful in 40s
Rust Build / Clippy (push) Successful in 1m12s
Rust Build / Check (push) Successful in 2m3s
Rust Build / Test Suite (push) Successful in 2m10s
Rust Build / build (push) Successful in 1m48s
Rust Build / Rustfmt (pull_request) Successful in 37s
Rust Build / Test Suite (pull_request) Successful in 1m10s
Rust Build / Check (pull_request) Successful in 1m30s
Rust Build / Clippy (pull_request) Successful in 1m36s
Rust Build / build (pull_request) Successful in 3m29s
Reviewed-on: phoenix/textsender-auth#8
2026-06-12 13:08:34 -04:00
phoenix 8e0b8b737b Refresh endpoint (#7)
Rust Build / Rustfmt (push) Successful in 1m0s
Rust Build / Clippy (pull_request) Successful in 1m48s
Rust Build / Check (push) Successful in 1m10s
Rust Build / Rustfmt (pull_request) Successful in 29s
Rust Build / Clippy (push) Successful in 1m4s
Rust Build / Test Suite (pull_request) Successful in 1m1s
Rust Build / Check (pull_request) Successful in 1m45s
Rust Build / build (pull_request) Successful in 3m11s
Rust Build / Test Suite (push) Successful in 2m25s
Rust Build / build (push) Successful in 1m41s
Reviewed-on: phoenix/textsender-auth#7
2026-06-12 10:51:40 -04:00
phoenix e5e34b4ad3 Service login (#6)
Rust Build / build (push) Successful in 1m42s
Rust Build / Clippy (push) Successful in 1m52s
Rust Build / Rustfmt (pull_request) Successful in 53s
Rust Build / Test Suite (pull_request) Successful in 1m25s
Rust Build / Clippy (pull_request) Successful in 1m40s
Rust Build / build (pull_request) Successful in 1m36s
Rust Build / Check (pull_request) Successful in 1m47s
Rust Build / Rustfmt (push) Successful in 1m24s
Rust Build / Check (push) Successful in 1m29s
Rust Build / Test Suite (push) Successful in 1m29s
Reviewed-on: phoenix/textsender-auth#6
2026-06-11 18:02:23 -04:00
22 changed files with 2291 additions and 1232 deletions
+9 -8
View File
@@ -1,10 +1,11 @@
SECRET_KEY=NULqYIzgt28bTiyziCd7IOO7b6LnWDW!
DB_NAME=textsender_auth_db
DB_USER=textsender_auth
DB_PASSWORD=password
DB_HOST=auth_db
DB_PORT=5432
DB_SSLMODE=disable
DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:5432/${DB_NAME}
DB_AUTH_NAME=schedtxt_auth_db
DB_AUTH_USER=schedtxt_auth
DB_AUTH_PASSWORD=password
DB_AUTH_HOST=auth_db
DB_AUTH_PORT=5432
DB_AUTH_SSLMODE=disable
DATABASE_URL=postgres://${DB_AUTH_USER}:${DB_AUTH_PASSWORD}@${DB_AUTH_HOST}:${DB_AUTH_PORT}/${DB_AUTH_NAME}
ENABLE_REGISTRATION=true
ALLOWED_ORIGINS="http://textsender.com"
ALLOWED_ORIGINS="http://schedtxt.com,http://localhost:5173,http://localhost:9080"
APP_ENV=production
+9 -8
View File
@@ -1,10 +1,11 @@
SECRET_KEY=NULqYIzgt28bTiyziCd7IOO7b6LnWDW!
DB_NAME=textsender_auth_db
DB_USER=textsender_auth
DB_PASSWORD=password
DB_HOST=localhost
DB_PORT=5432
DB_SSLMODE=disable
DATABASE_URL=postgres://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:5432/${DB_NAME}
DB_AUTH_NAME=schedtxt_auth_db
DB_AUTH_USER=schedtxt_auth
DB_AUTH_PASSWORD=password
DB_AUTH_HOST=localhost
DB_AUTH_PORT=5432
DB_AUTH_SSLMODE=disable
DATABASE_URL=postgres://${DB_AUTH_USER}:${DB_AUTH_PASSWORD}@${DB_AUTH_HOST}:${DB_AUTH_PORT}/${DB_AUTH_NAME}
ENABLE_REGISTRATION=true
ALLOWED_ORIGINS="http://textsender.com"
ALLOWED_ORIGINS="http://schedtxt.com,http://localhost:5173,http://localhost:9080"
APP_ENV=production
+72
View File
@@ -0,0 +1,72 @@
name: pr Build
on:
pull_request:
branches:
- main
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
name: Check
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: 1.97
- uses: Swatinem/rust-cache@v2
- run: |
mkdir -p ~/.ssh
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/schedtxt-models_deploy_key
chmod 600 ~/.ssh/schedtxt-models_deploy_key
ssh-keyscan ${{ secrets.MY_HOST }} >> ~/.ssh/known_hosts
eval $(ssh-agent -s)
ssh-add -v ~/.ssh/schedtxt-models_deploy_key
cargo check
fmt:
name: Rustfmt
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: 1.97
- uses: Swatinem/rust-cache@v2
- run: rustup component add rustfmt
- run: |
mkdir -p ~/.ssh
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/schedtxt-models_deploy_key
chmod 600 ~/.ssh/schedtxt-models_deploy_key
ssh-keyscan ${{ secrets.MY_HOST }} >> ~/.ssh/known_hosts
eval $(ssh-agent -s)
ssh-add -v ~/.ssh/schedtxt-models_deploy_key
cargo fmt --all -- --check
clippy:
name: Clippy
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: 1.97
- uses: Swatinem/rust-cache@v2
- run: rustup component add clippy
- run: |
mkdir -p ~/.ssh
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/schedtxt-models_deploy_key
chmod 600 ~/.ssh/schedtxt-models_deploy_key
ssh-keyscan ${{ secrets.MY_HOST }} >> ~/.ssh/known_hosts
eval $(ssh-agent -s)
ssh-add -v ~/.ssh/schedtxt-models_deploy_key
cargo clippy -- -D warnings
+33 -31
View File
@@ -1,31 +1,32 @@
name: Rust Build
name: schedtxt_auth Build
on:
push:
branches:
- main
pull_request:
branches:
- main
concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
check:
name: Check
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: 1.95
toolchain: 1.97
- uses: Swatinem/rust-cache@v2
- run: |
mkdir -p ~/.ssh
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/textsender-models_deploy_key
chmod 600 ~/.ssh/textsender-models_deploy_key
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/schedtxt-models_deploy_key
chmod 600 ~/.ssh/schedtxt-models_deploy_key
ssh-keyscan ${{ secrets.MY_HOST }} >> ~/.ssh/known_hosts
eval $(ssh-agent -s)
ssh-add -v ~/.ssh/textsender-models_deploy_key
ssh-add -v ~/.ssh/schedtxt-models_deploy_key
cargo check
@@ -35,12 +36,13 @@ jobs:
# --- Add database service definition ---
services:
postgres:
image: postgres:18.3-alpine
image: postgres:18.4-alpine
env:
# Use secrets for DB init, with fallbacks for flexibility
POSTGRES_USER: ${{ secrets.DB_TEST_USER || 'testuser' }}
POSTGRES_PASSWORD: ${{ secrets.DB_TEST_PASSWORD || 'testpassword' }}
POSTGRES_DB: ${{ secrets.DB_TEST_NAME || 'testdb' }}
POSTGRES_PORT: ${{ secrets.DB_PORT || 5432 }}
# Options to wait until the database is ready
options: >-
--health-cmd pg_isready
@@ -49,10 +51,10 @@ jobs:
--health-retries 5
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: 1.95
toolchain: 1.97
- uses: Swatinem/rust-cache@v2
# --- Add this step for explicit verification ---
- name: Verify Docker Environment
@@ -71,7 +73,7 @@ jobs:
- name: Run tests
env:
# Define DATABASE_URL for tests to use
DATABASE_URL: postgresql://${{ secrets.DB_TEST_USER || 'testuser' }}:${{ secrets.DB_TEST_PASSWORD || 'testpassword' }}@postgres:5432/${{ secrets.DB_TEST_NAME || 'testdb' }}
DATABASE_URL: postgresql://${{ secrets.DB_TEST_USER || 'testuser' }}:${{ secrets.DB_TEST_PASSWORD || 'testpassword' }}@postgres:${{ secrets.DB_PORT || 5432 }}/${{ secrets.DB_TEST_NAME || 'testdb' }}
RUST_LOG: info # Optional: configure test log level
SECRET_KEY: ${{ secrets.TOKEN_SECRET_KEY }}
# Make SSH agent available if tests fetch private dependencies
@@ -79,12 +81,12 @@ jobs:
ENABLE_REGISTRATION: 'TRUE'
run: |
mkdir -p ~/.ssh
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/textsender-models_deploy_key
chmod 600 ~/.ssh/textsender-models_deploy_key
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/schedtxt-models_deploy_key
chmod 600 ~/.ssh/schedtxt-models_deploy_key
ssh-keyscan ${{ secrets.MY_HOST }} >> ~/.ssh/known_hosts
eval $(ssh-agent -s)
ssh-add -v ~/.ssh/textsender-models_deploy_key
ssh-add -v ~/.ssh/schedtxt-models_deploy_key
cargo test
@@ -92,57 +94,57 @@ jobs:
name: Rustfmt
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: 1.95
toolchain: 1.97
- uses: Swatinem/rust-cache@v2
- run: rustup component add rustfmt
- run: |
mkdir -p ~/.ssh
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/textsender-models_deploy_key
chmod 600 ~/.ssh/textsender-models_deploy_key
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/schedtxt-models_deploy_key
chmod 600 ~/.ssh/schedtxt-models_deploy_key
ssh-keyscan ${{ secrets.MY_HOST }} >> ~/.ssh/known_hosts
eval $(ssh-agent -s)
ssh-add -v ~/.ssh/textsender-models_deploy_key
ssh-add -v ~/.ssh/schedtxt-models_deploy_key
cargo fmt --all -- --check
clippy:
name: Clippy
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: 1.95
toolchain: 1.97
- uses: Swatinem/rust-cache@v2
- run: rustup component add clippy
- run: |
mkdir -p ~/.ssh
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/textsender-models_deploy_key
chmod 600 ~/.ssh/textsender-models_deploy_key
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/schedtxt-models_deploy_key
chmod 600 ~/.ssh/schedtxt-models_deploy_key
ssh-keyscan ${{ secrets.MY_HOST }} >> ~/.ssh/known_hosts
eval $(ssh-agent -s)
ssh-add -v ~/.ssh/textsender-models_deploy_key
ssh-add -v ~/.ssh/schedtxt-models_deploy_key
cargo clippy -- -D warnings
build:
name: build
runs-on: ubuntu-24.04
steps:
- uses: actions/checkout@v5
- uses: actions/checkout@v6
- uses: actions-rust-lang/setup-rust-toolchain@v1
with:
toolchain: 1.95
toolchain: 1.97
- uses: Swatinem/rust-cache@v2
- run: |
mkdir -p ~/.ssh
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/textsender-models_deploy_key
chmod 600 ~/.ssh/textsender-models_deploy_key
echo "${{ secrets.MYREPO_TOKEN }}" > ~/.ssh/schedtxt-models_deploy_key
chmod 600 ~/.ssh/schedtxt-models_deploy_key
ssh-keyscan ${{ secrets.MY_HOST }} >> ~/.ssh/known_hosts
eval $(ssh-agent -s)
ssh-add -v ~/.ssh/textsender-models_deploy_key
ssh-add -v ~/.ssh/schedtxt-models_deploy_key
cargo build --release
-2
View File
@@ -1,5 +1,3 @@
/textsender-auth
.env
.env.local
.env.docker
Generated
+257 -919
View File
File diff suppressed because it is too large Load Diff
+14 -17
View File
@@ -1,30 +1,27 @@
[package]
name = "textsender_auth"
version = "0.1.16"
name = "schedtxt_auth"
version = "0.2.4"
edition = "2024"
rust-version = "1.95"
license = "MIT"
description = "Auth API for sending text messages"
rust-version = "1.97"
[dependencies]
axum = { version = "0.8.9" }
serde = { version = "1.0.228", features = ["derive"] }
serde_json = { version = "1.0.149" }
tokio = { version = "1.52.2", features = ["rt-multi-thread"] }
serde_json = { version = "1.0.150" }
tokio = { version = "1.52.3", features = ["rt-multi-thread"] }
tracing-subscriber = { version = "0.3.23" }
tower = { version = "0.5.3", features = ["full"] }
tower-http = { version = "0.6.10", features = ["cors"] }
hyper = { version = "1.9.0" }
sqlx = { version = "0.8.6", features = ["postgres", "runtime-tokio-native-tls", "time", "uuid"] }
uuid = { version = "1.23.1", features = ["v4", "serde"] }
argon2 = { version = "0.5.3", features = ["std"] } # Use the latest 0.5.x version
rand = { version = "0.10.1" }
time = { version = "0.3.47", features = ["macros", "serde"] }
tower-http = { version = "0.7.0", features = ["cors"] }
sqlx = { version = "0.9.0", features = ["runtime-tokio", "tls-native-tls", "postgres", "time", "uuid"] }
uuid = { version = "1.23.5", features = ["v4", "serde"] }
argon2 = { version = "0.5.3", features = ["std"] }
time = { version = "0.3.53", features = ["macros", "serde"] }
josekit = { version = "0.10.3" }
utoipa = { version = "5.5.0", features = ["axum_extras"] }
utoipa-swagger-ui = { version = "9.0.2", features = ["axum"] }
textsender_models = { git = "ssh://git@git.kundeng.us/phoenix/textsender-models.git", tag = "v0.3.0" }
schedtxt_models = { git = "ssh://git@git.kundeng.us/phoenix/schedtxt_models.git", tag = "v0.5.3", features = ["config", "user"] }
[dev-dependencies]
http-body-util = { version = "0.1.3" }
tower = { version = "0.5.3", features = ["full"] }
url = { version = "2.5.8" }
once_cell = { version = "1.21.4" } # Useful for lazy initialization in tests/app setup
async-std = { version = "1.13.2" }
+4 -30
View File
@@ -1,14 +1,7 @@
# Stage 1: Build the application
# Use a specific Rust version for reproducibility. Choose one that matches your development environment.
# Using slim variant for smaller base image
FROM rust:1.95 as builder
FROM rust:1.97 as builder
# Set the working directory inside the container
WORKDIR /usr/src/app
# Install build dependencies if needed (e.g., for certain crates like sqlx with native TLS)
# RUN apt-get update && apt-get install -y pkg-config libssl-dev
# Install build dependencies if needed (e.g., git for cloning)
RUN apt-get update && apt-get install -y --no-install-recommends \
pkg-config libssl3 \
@@ -16,55 +9,36 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
openssh-client git \
&& rm -rf /var/lib/apt/lists/*
# << --- ADD HOST KEY HERE --- >>
# Replace 'yourgithost.com' with the actual hostname (e.g., github.com)
RUN mkdir -p -m 0700 ~/.ssh && \
ssh-keyscan git.kundeng.us >> ~/.ssh/known_hosts
# Copy Cargo manifests
COPY Cargo.toml Cargo.lock ./
# Build *only* dependencies to leverage Docker cache
# This dummy build caches dependencies as a separate layer
RUN --mount=type=ssh mkdir src && \
echo "fn main() {println!(\"if you see this, the build broke\")}" > src/main.rs && \
cargo build --release --quiet && \
rm -rf src target/release/deps/textsender_auth* # Clean up dummy build artifacts
rm -rf src target/release/deps/schedtxt_auth*
# Copy the actual source code
COPY src ./src
# If you have other directories like `templates` or `static`, copy them too
COPY .env ./.env
COPY migrations ./migrations
# << --- SSH MOUNT ADDED HERE --- >>
# Build *only* dependencies to leverage Docker cache
# This dummy build caches dependencies as a separate layer
# Mount the SSH agent socket for this command
RUN --mount=type=ssh \
cargo build --release --quiet
# Stage 2: Create the final, smaller runtime image
# Use a minimal base image like debian-slim or even distroless for security/size
FROM debian:trixie-slim
# Install runtime dependencies if needed (e.g., SSL certificates)
RUN apt-get update && apt-get install -y ca-certificates libssl-dev libssl3 && rm -rf /var/lib/apt/lists/*
# Set the working directory
WORKDIR /usr/local/bin
# Copy the compiled binary from the builder stage
COPY --from=builder /usr/src/app/target/release/textsender_auth .
COPY --from=builder /usr/src/app/target/release/schedtxt_auth .
# Copy other necessary files like .env (if used for runtime config) or static assets
# It's generally better to configure via environment variables in Docker though
COPY --from=builder /usr/src/app/.env .
COPY --from=builder /usr/src/app/migrations ./migrations
# Expose the port your Axum app listens on (e.g., 3000 or 8000)
EXPOSE 9080
# Set the command to run your application
# Ensure this matches the binary name copied above
CMD ["./textsender_auth"]
CMD ["./schedtxt_auth"]
+22
View File
@@ -0,0 +1,22 @@
Copyright (c) 2026 Kun Deng.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
+21
View File
@@ -1 +1,22 @@
# schedtxt_auth
Auth API for `schedtxt` project.
## Getting started
Quickest way to get started is with docker, make sure that it is installed. Copy over
the `.env.docker.sample` file and name it `.env`.
For `SECRET_KEY` provide a key that is at least 32-characters. This is used for token
creation. Additionally, provide credentials for the database for the `DB_*` keys.
Make sure that `ENABLE_REGISTRATION` is set to true, otherwise registration will not work.
Build the container
```
docker compose build
```
Bring up the container
```
docker compose up
```
+14 -17
View File
@@ -1,35 +1,33 @@
version: '3.8' # Use a recent version
services:
# Your Rust Application Service
auth_api:
build: # Tells docker-compose to build the Dockerfile in the current directory
build:
context: .
ssh: ["default"] # Uses host's SSH agent
container_name: textsender_auth # Optional: Give the container a specific name
ssh: ["default"]
container_name: schedtxt_auth
ports:
# Map host port 8000 to container port 3000 (adjust as needed)
- "9080:9080"
env_file:
- .env
depends_on:
auth_db:
condition: service_healthy # Wait for the DB to be healthy before starting the app
restart: unless-stopped # Optional: Restart policy
condition: service_healthy
restart: unless-stopped
# PostgreSQL Database Service
auth_db:
image: postgres:18.4-alpine # Use an official Postgres image (Alpine variant is smaller)
container_name: textsender_auth_db # Optional: Give the container a specific name
image: postgres:18.4-alpine
container_name: schedtxt_auth_db
environment:
# These MUST match the user, password, and database name in the DATABASE_URL above
POSTGRES_USER: ${DB_USER:-textsender_op}
POSTGRES_PASSWORD: ${DB_PASSWORD:-password}
POSTGRES_DB: ${DB_NAME:-textsender_auth_db}
POSTGRES_USER: ${DB_AUTH_USER:-schedtxt_op}
POSTGRES_PASSWORD: ${DB_AUTH_PASSWORD:-password}
POSTGRES_DB: ${DB_AUTH_NAME:-schedtxt_auth_db}
volumes:
# Persist database data using a named volume
- postgres_data:/var/lib/postgresql
ports: []
ports:
- "5433:5432"
healthcheck:
# Checks if Postgres is ready to accept connections
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
@@ -37,9 +35,8 @@ services:
timeout: 5s
retries: 5
start_period: 10s
restart: always # Optional: Restart policy
restart: always
# Define the named volume for data persistence
volumes:
postgres_data:
driver: local # Use the default local driver
driver: local
-32
View File
@@ -1,32 +0,0 @@
-- CREATE EXTENSION IF NOT EXISTS pgcrypto;
-- CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
--
-- DROP TABLE IF EXISTS "user" CASCADE;
-- DROP TABLE IF EXISTS "salt" CASCADE;
-- DROP TABLE IF EXISTS "service_user" CASCADE;
--
-- CREATE TABLE IF NOT EXISTS "user" (
-- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- first_name TEXT NOT NULL,
-- last_name TEXT NOT NULL,
-- phone_number TEXT NOT NULL,
-- username TEXT NOT NULL,
-- password TEXT NOT NULL,
-- created TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-- last_login TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-- salt_id UUID NOT NULL
-- );
--
--
-- CREATE TABLE IF NOT EXISTS "salt" (
-- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- salt TEXT NOT NULL
-- );
--
-- CREATE TABLE IF NOT EXISTS "service_user" (
-- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
-- username TEXT NOT NULL,
-- passphrase TEXT NOT NULL,
-- created TIMESTAMPTZ NOT NULL DEFAULT NOW(),
-- last_login timestamptz NULL
-- );
+725 -17
View File
@@ -9,6 +9,74 @@ pub mod request {
pub username: String,
pub password: String,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub struct ServiceUserLoginRequest {
pub username: String,
pub passphrase: String,
}
impl ServiceUserLoginRequest {
pub fn is_empty(&self) -> (bool, Option<String>) {
if self.username.is_empty() && self.passphrase.is_empty() {
(
true,
Some(String::from("Username and passphrase are empty")),
)
} else if self.username.is_empty() {
(true, Some(String::from("Username is empty")))
} else if self.username.is_empty() {
(true, Some(String::from("Passphrase is empty")))
} else {
(false, None)
}
}
}
#[derive(Deserialize, utoipa::ToSchema)]
pub struct RefreshTokenRequest {
pub access_token: String,
}
#[derive(Deserialize, utoipa::ToSchema)]
pub struct UpdatePasswordRequest {
pub user_id: uuid::Uuid,
pub current_password: String,
pub updated_password: String,
pub confirmed_password: String,
}
impl UpdatePasswordRequest {
pub fn is_valid(&self) -> bool {
if self.user_id.is_nil()
|| self.current_password.is_empty()
|| self.updated_password.is_empty()
|| self.confirmed_password.is_empty()
{
false
} else {
self.updated_password == self.confirmed_password
}
}
}
#[derive(Deserialize, utoipa::ToSchema)]
pub struct UserUpdateNameRequest {
pub user_id: uuid::Uuid,
pub firstname: String,
pub lastname: String,
}
impl UserUpdateNameRequest {
pub fn is_valid(&self) -> (bool, Option<String>) {
if self.user_id.is_nil() || self.firstname.is_empty() || self.lastname.is_empty() {
let reason = String::from("Missing fields");
(false, Some(reason))
} else {
(true, None)
}
}
}
}
pub mod response {
@@ -16,17 +84,55 @@ pub mod response {
#[derive(Default, Deserialize, Serialize, utoipa::ToSchema)]
pub struct LoginResponse {
pub message: String,
pub data: Vec<textsender_models::token::LoginResult>,
pub data: Vec<schedtxt_models::token::LoginResult>,
}
#[derive(Default, Deserialize, Serialize, utoipa::ToSchema)]
pub struct ServiceUserLoginResponse {
pub message: String,
pub data: Vec<schedtxt_models::token::LoginResult>,
}
pub async fn extract(
response: axum::response::Response,
) -> Result<LoginResponse, std::io::Error> {
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
.await
.unwrap();
let _parsed_body: LoginResponse = serde_json::from_slice(&body).unwrap();
todo!("Add code to convert axum::Response to this type");
let body = match axum::body::to_bytes(response.into_body(), usize::MAX).await {
Ok(body) => body,
Err(err) => {
return Err(std::io::Error::other(err));
}
};
let parsed_body: LoginResponse = match serde_json::from_slice(&body) {
Ok(body) => body,
Err(err) => {
return Err(std::io::Error::other(err));
}
};
Ok(parsed_body)
}
#[derive(Deserialize, Serialize, utoipa::ToSchema)]
pub struct RefreshTokenResponse {
pub message: String,
pub data: Vec<schedtxt_models::token::LoginResult>,
}
#[derive(Deserialize, Serialize, utoipa::ToSchema)]
pub struct UpdatePasswordResponse {
pub message: String,
pub data: Vec<uuid::Uuid>,
}
#[derive(Deserialize, Serialize, utoipa::ToSchema)]
pub struct UserUpdateNameResponse {
pub message: String,
pub data: Vec<schedtxt_models::user::User>,
}
#[derive(Default, Deserialize, Serialize, utoipa::ToSchema)]
pub struct GetUserProfileResponse {
pub message: String,
pub data: Vec<schedtxt_models::user::UserProfile>,
}
}
@@ -94,13 +200,22 @@ pub async fn user_login(
Ok(matches) => {
if matches {
// Create token
let key = textsender_models::envy::environment::get_secret_key()
.await
.value;
let (token_literal, duration) =
token_stuff::create_token(&key, &user.id).unwrap();
let key =
schedtxt_models::envy::environment::get_secret_key().value;
let cst = match token_stuff::create_token(&key, &user.id) {
Ok(token) => token,
Err(_err) => {
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::LoginResponse {
message: String::from("Error creating token"),
data: Vec::new(),
}),
);
}
};
if token_stuff::verify_token(&key, &token_literal) {
if token_stuff::verify_token(&key, &cst.access_token) {
let current_time = time::OffsetDateTime::now_utc();
let _ =
repo::user::update_last_login(&pool, &user, &current_time)
@@ -110,14 +225,14 @@ pub async fn user_login(
axum::http::StatusCode::OK,
axum::Json(response::LoginResponse {
message: String::from("Successful"),
data: vec![textsender_models::token::LoginResult {
data: vec![schedtxt_models::token::LoginResult {
user_id: user.id,
access_token: token_literal,
access_token: cst.access_token,
token_type: String::from(
textsender_models::token::TOKEN_TYPE,
schedtxt_models::token::TOKEN_TYPE,
),
issued_at: duration,
..Default::default()
issued_at: cst.issued,
expires_in: cst.expires_in,
}],
}),
)
@@ -160,3 +275,596 @@ pub async fn user_login(
}
}
}
/// Endpoint for service user login
#[utoipa::path(
post,
path = super::endpoints::LOGIN_SERVICE_USER,
request_body(
content = request::ServiceUserLoginRequest,
description = "Data required for service user to lgoin",
content_type = "application/json"
),
responses(
(status = 201, description = "Service uuser login successful", body = response::ServiceUserLoginResponse),
(status = 400, description = "Bad data", body = response::ServiceUserLoginResponse),
(status = 500, description = "Something went wrong", body = response::ServiceUserLoginResponse)
)
)]
pub async fn service_user_login(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<request::ServiceUserLoginRequest>,
) -> (
axum::http::StatusCode,
axum::Json<response::ServiceUserLoginResponse>,
) {
if payload.username.is_empty() || payload.passphrase.is_empty() {
let reason = if payload.username.is_empty() {
String::from("Username not provided")
} else {
String::from("Passphrase not provided")
};
(
axum::http::StatusCode::BAD_REQUEST,
axum::Json(response::ServiceUserLoginResponse {
message: reason,
data: Vec::new(),
}),
)
} else {
match repo::service::exists(&pool, &payload.username).await {
Ok(exists) => {
if !exists {
println!("User does not exists");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::ServiceUserLoginResponse {
message: String::from("Unable to login"),
data: Vec::new(),
}),
)
} else {
println!("Good to create");
let service_user =
match repo::service::get_with_username(&pool, &payload.username).await {
Ok(service_user) => service_user,
Err(err) => {
eprintln!("Error: {err:?}");
return (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::ServiceUserLoginResponse {
message: String::from("Unable to login"),
data: Vec::new(),
}),
);
}
};
println!("Service user: {service_user:?}");
println!("Payload: {:?}", payload.passphrase);
let hashed_password = service_user.passphrase.clone();
println!("Hash password: {hashed_password:?}");
match hashing::verify_password(&payload.passphrase, hashed_password) {
Ok(matches) => {
if matches {
// Create token
println!("Creating token");
let key =
schedtxt_models::envy::environment::get_secret_key().value;
let cst =
token_stuff::create_token(&key, &service_user.id).unwrap();
if token_stuff::verify_token(&key, &cst.access_token) {
let current_time = time::OffsetDateTime::now_utc();
let _ = repo::service::update_last_login(
&pool,
&service_user,
&current_time,
)
.await;
(
axum::http::StatusCode::OK,
axum::Json(response::ServiceUserLoginResponse {
message: String::from(
super::messages::SUCCESSFUL_MESSAGE,
),
data: vec![schedtxt_models::token::LoginResult {
user_id: service_user.id,
access_token: cst.access_token,
token_type: String::from(
schedtxt_models::token::TOKEN_TYPE,
),
issued_at: cst.issued,
expires_in: cst.expires_in,
}],
}),
)
} else {
eprintln!("Invalid token");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::ServiceUserLoginResponse {
message: String::from("Invalid attempt"),
data: Vec::new(),
}),
)
}
} else {
eprintln!("No match");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::ServiceUserLoginResponse {
message: String::from("Invalid attempt"),
data: Vec::new(),
}),
)
}
}
Err(err) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::ServiceUserLoginResponse {
message: err.to_string(),
data: Vec::new(),
}),
),
}
}
}
Err(err) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::ServiceUserLoginResponse {
message: err.to_string(),
data: Vec::new(),
}),
),
}
}
}
/// Endpoint for service user login
#[utoipa::path(
post,
path = super::endpoints::REFRESH_TOKEN,
request_body(
content = request::RefreshTokenRequest,
description = "Data required refresh token",
content_type = "application/json"
),
responses(
(status = 200, description = "Service uuser login successful", body = response::RefreshTokenResponse),
(status = 400, description = "Bad data", body = response::RefreshTokenResponse),
(status = 500, description = "Something went wrong", body = response::RefreshTokenResponse)
)
)]
pub async fn refresh_token(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<request::RefreshTokenRequest>,
) -> (
axum::http::StatusCode,
axum::Json<response::RefreshTokenResponse>,
) {
if payload.access_token.is_empty() {
let reason = String::from("Access token not provided");
(
axum::http::StatusCode::BAD_REQUEST,
axum::Json(response::RefreshTokenResponse {
message: reason,
data: Vec::new(),
}),
)
} else {
let key = schedtxt_models::envy::environment::get_secret_key().value;
if token_stuff::verify_token(&key, &payload.access_token) {
match token_stuff::extract_id_from_token(&key, &payload.access_token) {
Ok(id) => {
let generate_service_token =
|id, key| -> Option<schedtxt_models::token::CreateTokenResult> {
token_stuff::create_service_refresh_token(key, id).ok()
};
let mut response = response::RefreshTokenResponse {
message: String::new(),
data: Vec::new(),
};
match repo::user::get_with_id(&pool, &id).await {
Ok(_user) => match generate_service_token(&id, &key) {
Some(cst) => {
response.message =
String::from(super::messages::SUCCESSFUL_MESSAGE);
let lr = schedtxt_models::token::LoginResult {
user_id: id,
access_token: cst.access_token,
issued_at: cst.issued,
expires_in: cst.expires_in,
token_type: String::from(schedtxt_models::token::TOKEN_TYPE),
};
response.data.push(lr);
(axum::http::StatusCode::OK, axum::Json(response))
}
None => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::RefreshTokenResponse {
message: String::from("Refresh token not generated"),
data: Vec::new(),
}),
),
},
Err(err) => {
println!("Unable to find user, checking service user: {err:?}");
match repo::service::get(&pool, &id).await {
Ok(_service_user) => match generate_service_token(&id, &key) {
Some(cst) => {
response.message =
String::from(super::messages::SUCCESSFUL_MESSAGE);
let lr = schedtxt_models::token::LoginResult {
user_id: id,
access_token: cst.access_token,
issued_at: cst.issued,
expires_in: cst.expires_in,
token_type: String::from(
schedtxt_models::token::TOKEN_TYPE,
),
};
response.data.push(lr);
(axum::http::StatusCode::OK, axum::Json(response))
}
None => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::RefreshTokenResponse {
message: String::from("Issued at not returned"),
data: Vec::new(),
}),
),
},
Err(err) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::RefreshTokenResponse {
message: err.to_string(),
data: Vec::new(),
}),
),
}
}
}
}
Err(err) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::RefreshTokenResponse {
message: err.to_string(),
data: Vec::new(),
}),
),
}
} else {
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::RefreshTokenResponse {
message: String::from("Unable to verify token"),
data: Vec::new(),
}),
)
}
}
}
/// Endpoint for a updating password
#[utoipa::path(
patch,
path = super::endpoints::UPDATE_PASSWORD,
request_body(
content = request::UpdatePasswordRequest,
description = "Data required to update password",
content_type = "application/json"
),
responses(
(status = 200, description = "User login successful", body = response::UpdatePasswordResponse),
(status = 400, description = "Bad data", body = response::UpdatePasswordResponse),
(status = 500, description = "Something went wrong", body = response::UpdatePasswordResponse)
)
)]
pub async fn update_password(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<request::UpdatePasswordRequest>,
) -> (
axum::http::StatusCode,
axum::Json<response::UpdatePasswordResponse>,
) {
if !payload.is_valid() {
(
axum::http::StatusCode::BAD_REQUEST,
axum::Json(response::UpdatePasswordResponse {
message: String::from("Invalid passwords"),
data: Vec::new(),
}),
)
} else {
let verify_password = |current_password, hashed_password| -> Result<bool, std::io::Error> {
match hashing::verify_password(current_password, hashed_password) {
Ok(matches) => Ok(matches),
Err(err) => Err(std::io::Error::other(err.to_string())),
}
};
match repo::user::get_with_id(&pool, &payload.user_id).await {
Ok(user) => {
let hashed_password = user.password.clone();
match verify_password(&payload.current_password, hashed_password) {
Ok(matches) => {
if matches {
let (generate_salt, mut salt) = super::register::generate_the_salt();
salt.id = repo::salt::insert(&pool, &salt).await.unwrap();
let updated_hashed_password = match hashing::hash_password(
&payload.updated_password,
&generate_salt,
) {
Ok(hashed) => hashed,
Err(err) => {
eprintln!("Error: {err:?}");
String::new()
}
};
match repo::user::update_password(
&pool,
&user,
&updated_hashed_password,
)
.await
{
Ok(()) => (
axum::http::StatusCode::OK,
axum::Json(response::UpdatePasswordResponse {
message: String::from(super::messages::SUCCESSFUL_MESSAGE),
data: vec![user.id],
}),
),
Err(err) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::UpdatePasswordResponse {
message: err.to_string(),
data: Vec::new(),
}),
),
}
} else {
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::UpdatePasswordResponse {
message: String::from("Issue updating password"),
data: Vec::new(),
}),
)
}
}
Err(err) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::UpdatePasswordResponse {
message: err.to_string(),
data: Vec::new(),
}),
),
}
}
Err(err) => {
println!("No User found, trying Service User: {err:?}");
// Try service user
match repo::service::get(&pool, &payload.user_id).await {
Ok(service_user) => {
let hashed_password = service_user.passphrase.clone();
match verify_password(&payload.current_password, hashed_password) {
Ok(matches) => {
if matches {
let (generate_salt, mut salt) =
super::register::generate_the_salt();
salt.id = repo::salt::insert(&pool, &salt).await.unwrap();
let updated_hashed_password = match hashing::hash_password(
&payload.updated_password,
&generate_salt,
) {
Ok(hashed) => hashed,
Err(err) => {
eprintln!("Error: {err:?}");
String::new()
}
};
match repo::service::update_passphrase(
&pool,
&service_user,
&updated_hashed_password,
)
.await
{
Ok(()) => (
axum::http::StatusCode::OK,
axum::Json(response::UpdatePasswordResponse {
message: String::from(
super::messages::SUCCESSFUL_MESSAGE,
),
data: vec![service_user.id],
}),
),
Err(err) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::UpdatePasswordResponse {
message: err.to_string(),
data: Vec::new(),
}),
),
}
} else {
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::UpdatePasswordResponse {
message: String::from("Issue updating password"),
data: Vec::new(),
}),
)
}
}
Err(err) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::UpdatePasswordResponse {
message: err.to_string(),
data: Vec::new(),
}),
),
}
}
Err(err) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::UpdatePasswordResponse {
message: err.to_string(),
data: Vec::new(),
}),
),
}
}
}
}
}
/// Endpoint for a updating password
#[utoipa::path(
patch,
path = super::endpoints::UPDATE_USER_NAME,
request_body(
content = request::UserUpdateNameRequest,
description = "Data required to update name of a user",
content_type = "application/json"
),
responses(
(status = 200, description = "Names were updated", body = response::UserUpdateNameResponse),
(status = 304, description = "Nothing to change", body = response::UserUpdateNameResponse),
(status = 400, description = "Bad data", body = response::UserUpdateNameResponse),
(status = 500, description = "Something went wrong", body = response::UserUpdateNameResponse)
)
)]
pub async fn update_name_of_user(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::Json(payload): axum::Json<request::UserUpdateNameRequest>,
) -> (
axum::http::StatusCode,
axum::Json<response::UserUpdateNameResponse>,
) {
let (valid_request, reason) = payload.is_valid();
if !valid_request {
(
axum::http::StatusCode::BAD_REQUEST,
axum::Json(response::UserUpdateNameResponse {
message: reason.unwrap_or_default(),
data: Vec::new(),
}),
)
} else {
match repo::user::get_with_id(&pool, &payload.user_id).await {
Ok(user) => {
if user.firstname == payload.firstname || user.lastname == payload.lastname {
(
axum::http::StatusCode::NOT_MODIFIED,
axum::Json(response::UserUpdateNameResponse {
message: String::from("No change"),
data: Vec::new(),
}),
)
} else {
match repo::user::update_name(
&pool,
&user.id,
&payload.firstname,
&payload.lastname,
)
.await
{
Ok(_) => (
axum::http::StatusCode::OK,
axum::Json(response::UserUpdateNameResponse {
message: String::from(super::messages::SUCCESSFUL_MESSAGE),
data: vec![schedtxt_models::user::User {
id: user.id,
phone_number: user.phone_number,
firstname: payload.firstname,
lastname: payload.lastname,
username: user.username,
created: user.created,
last_login: user.last_login,
..Default::default()
}],
}),
),
Err(err) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::UserUpdateNameResponse {
message: err.to_string(),
data: Vec::new(),
}),
),
}
}
}
Err(err) => (
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response::UserUpdateNameResponse {
message: err.to_string(),
data: Vec::new(),
}),
),
}
}
}
/// Endpoint to get User Profile
#[utoipa::path(
delete,
path = super::endpoints::GET_USER_PROFILE,
params(("id" = uuid::Uuid, Path, description = "User Id")),
responses(
(status = 200, description = "Deleted", body = response::GetUserProfileResponse),
(status = 400, description = "Bad request", body = response::GetUserProfileResponse),
(status = 500, description = "Error", body = response::GetUserProfileResponse)
)
)]
pub async fn get_user_profile(
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
axum::extract::Path(id): axum::extract::Path<uuid::Uuid>,
) -> (
axum::http::StatusCode,
axum::Json<response::GetUserProfileResponse>,
) {
let mut response = response::GetUserProfileResponse::default();
if id.is_nil() {
response.message = String::from("Invalid");
return (axum::http::StatusCode::BAD_REQUEST, axum::Json(response));
}
match repo::user::get_with_id(&pool, &id).await {
Ok(user) => {
let user_profile = schedtxt_models::user::UserProfile {
user_id: user.id,
phone_number: user.phone_number,
firstname: user.firstname,
lastname: user.lastname,
last_login: user.last_login,
created: user.created,
username: user.username,
};
response.message = String::from(super::messages::SUCCESSFUL_MESSAGE);
response.data.push(user_profile);
(axum::http::StatusCode::OK, axum::Json(response))
}
Err(err) => {
eprintln!("Error: {err:?}");
response.message = String::from("Bad request");
(
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
axum::Json(response),
)
}
}
}
+10
View File
@@ -11,4 +11,14 @@ pub mod endpoints {
pub const DBTEST: &str = "/api/v1/test/db";
/// Endpoint constant for service user registration
pub const REGISTER_SERVICE_USER: &str = "/api/v1/service/register";
/// Endpoint constant for service login user
pub const LOGIN_SERVICE_USER: &str = "/api/v1/service/login";
/// Endpoint constant for refresh token
pub const REFRESH_TOKEN: &str = "/api/v1/token/refresh";
/// Endpoint constant for updating password
pub const UPDATE_PASSWORD: &str = "/api/v1/user/password/update";
/// Endpoint constant for updating user's name
pub const UPDATE_USER_NAME: &str = "/api/v1/user/name/update";
/// Endpoint constant for getting user profile
pub const GET_USER_PROFILE: &str = "/api/v1/user/profile/{id}";
}
+12 -13
View File
@@ -49,22 +49,22 @@ pub mod response {
#[derive(Deserialize, Serialize, utoipa::ToSchema)]
pub struct Response {
pub message: String,
pub data: Vec<textsender_models::user::User>,
pub data: Vec<schedtxt_models::user::User>,
}
#[derive(Default, Deserialize, Serialize, utoipa::ToSchema)]
pub struct RegisterServiceUserResponse {
pub message: String,
pub data: Vec<textsender_models::user::ServiceUser>,
pub data: Vec<schedtxt_models::user::ServiceUser>,
}
}
fn generate_the_salt() -> (
pub fn generate_the_salt() -> (
argon2::password_hash::SaltString,
textsender_models::user::Salt,
schedtxt_models::user::Salt,
) {
let salt_string = hashing::generate_salt().unwrap();
let salt = textsender_models::user::Salt::default();
let salt = schedtxt_models::user::Salt::default();
(salt_string, salt)
}
@@ -80,7 +80,7 @@ fn generate_the_salt() -> (
responses(
(status = 201, description = "User created", body = response::Response),
(status = 404, description = "User already exists", body = response::Response),
(status = 400, description = "Issue creating user", body = response::Response)
(status = 500, description = "Issue creating user", body = response::Response)
)
)]
pub async fn register_user(
@@ -102,12 +102,10 @@ pub async fn register_user(
};
if registration_enabled {
let mut user = textsender_models::user::User {
let mut user = schedtxt_models::user::User {
username: payload.username.clone(),
password: payload.password.clone(),
// email: payload.email.clone(),
phone_number: payload.phone_number.clone(),
// email_verified: true,
..Default::default()
};
@@ -183,7 +181,7 @@ pub async fn register_user(
/// Checks to see if registration is enabled
async fn is_registration_enabled() -> Result<bool, std::io::Error> {
let key = String::from("ENABLE_REGISTRATION");
let var = textsender_models::envy::environment::get_env(&key).await;
let var = schedtxt_models::envy::environment::get_env(&key);
let parsed_value = var.value.to_uppercase();
if parsed_value == "TRUE" {
@@ -250,9 +248,9 @@ pub async fn register_service_user(
} else {
let (generate_salt, mut salt) = generate_the_salt();
salt.id = repo::salt::insert(&pool, &salt).await.unwrap();
let mut service_user = textsender_models::user::ServiceUser {
let mut service_user = schedtxt_models::user::ServiceUser {
username: payload.username.clone(),
passphrase: hashing::hash_password(&payload.username, &generate_salt)
passphrase: hashing::hash_password(&payload.passphrase, &generate_salt)
.unwrap(),
salt_id: salt.id,
..Default::default()
@@ -261,9 +259,10 @@ pub async fn register_service_user(
println!("Creating user");
match repo::service::insert(&pool, &service_user).await {
Ok(created) => {
Ok((service_user_id, created)) => {
resp.message = String::from(super::messages::SUCCESSFUL_MESSAGE);
service_user.created = Some(created);
service_user.id = service_user_id;
resp.data.push(service_user);
(axum::http::StatusCode::CREATED, axum::Json(resp))
}
+1 -3
View File
@@ -1,9 +1,7 @@
use sqlx::postgres::PgPoolOptions;
pub async fn create_pool() -> Result<sqlx::PgPool, sqlx::Error> {
let database_url = textsender_models::envy::environment::get_db_url()
.await
.value;
let database_url = schedtxt_models::envy::environment::get_db_url().value;
println!("Database url: {database_url}");
PgPoolOptions::new()
+37 -9
View File
@@ -8,7 +8,7 @@ pub mod token_stuff;
pub mod init {
use axum::{
Router,
routing::{get, post},
routing::{get, patch, post},
};
use utoipa::OpenApi;
@@ -24,9 +24,12 @@ pub mod init {
paths(
common_callers::endpoint::db_ping, common_callers::endpoint::root,
register_caller::register_user, login_caller::user_login,
login_caller::get_user_profile,
),
components(schemas(common_callers::response::TestResult,
register_responses::Response, login_responses::LoginResponse)),
register_responses::Response, login_responses::LoginResponse,
login_responses::GetUserProfileResponse,
)),
tags(
(name = "TextSender Auth API", description = "Auth API for TextSender API")
)
@@ -35,27 +38,27 @@ pub mod init {
mod cors {
pub async fn configure_cors() -> tower_http::cors::CorsLayer {
// Start building the CORS layer with common settings
let cors = tower_http::cors::CorsLayer::new()
.allow_methods([
axum::http::Method::GET,
axum::http::Method::PATCH,
axum::http::Method::POST,
axum::http::Method::PUT,
axum::http::Method::DELETE,
]) // Specify allowed methods:cite[2]
])
.allow_headers([
axum::http::header::CONTENT_TYPE,
axum::http::header::AUTHORIZATION,
]) // Specify allowed headers:cite[2]
])
.allow_credentials(true) // If you need to send cookies or authentication headers:cite[2]
.max_age(std::time::Duration::from_secs(3600)); // Cache the preflight response for 1 hour:cite[2]
// Dynamically set the allowed origin based on the environment
match std::env::var(textsender_models::envy::keys::APP_ENV).as_deref() {
match std::env::var(schedtxt_models::envy::keys::APP_ENV).as_deref() {
Ok("production") => {
let allowed_origins_env =
textsender_models::envy::environment::get_allowed_origins().await;
match textsender_models::envy::utility::delimitize(&allowed_origins_env) {
schedtxt_models::envy::environment::get_allowed_origins();
match schedtxt_models::envy::utility::delimitize(&allowed_origins_env) {
Ok(alwd) => {
let allowed_origins: Vec<axum::http::HeaderValue> = alwd
.into_iter()
@@ -76,6 +79,12 @@ pub mod init {
cors.allow_origin(vec![
"http://localhost:4200".parse().unwrap(),
"http://127.0.0.1:4200".parse().unwrap(),
"http://localhost:5173".parse().unwrap(),
"http://127.0.0.1:5173".parse().unwrap(),
"http://localhost:9080".parse().unwrap(),
"http://127.0.0.1:9080".parse().unwrap(),
"http://localhost:9081".parse().unwrap(),
"http://127.0.0.1:9081".parse().unwrap(),
])
}
}
@@ -83,7 +92,6 @@ pub mod init {
}
pub async fn routes() -> Router {
// build our application with a route
Router::new()
.route(
callers::endpoints::DBTEST,
@@ -102,6 +110,26 @@ pub mod init {
post(callers::register::register_service_user),
)
.route(callers::endpoints::LOGIN, post(callers::login::user_login))
.route(
callers::endpoints::LOGIN_SERVICE_USER,
post(callers::login::service_user_login),
)
.route(
callers::endpoints::REFRESH_TOKEN,
post(callers::login::refresh_token),
)
.route(
callers::endpoints::UPDATE_PASSWORD,
patch(callers::login::update_password),
)
.route(
callers::endpoints::UPDATE_USER_NAME,
patch(callers::login::update_name_of_user),
)
.route(
callers::endpoints::GET_USER_PROFILE,
get(callers::login::get_user_profile),
)
.layer(cors::configure_cors().await)
}
+2 -2
View File
@@ -3,10 +3,10 @@ async fn main() {
// initialize tracing
tracing_subscriber::fmt::init();
let app = textsender_auth::init::app().await;
let app = schedtxt_auth::init::app().await;
// run our app with hyper, listening globally on port 9080
let url = textsender_auth::config::get_full();
let url = schedtxt_auth::config::get_full();
let listener = tokio::net::TcpListener::bind(url).await.unwrap();
axum::serve(listener, app).await.unwrap();
}
+91 -7
View File
@@ -12,7 +12,7 @@ pub mod user {
pub async fn get(
pool: &sqlx::PgPool,
username: &String,
) -> Result<textsender_models::user::User, sqlx::Error> {
) -> Result<schedtxt_models::user::User, sqlx::Error> {
let result = sqlx::query(
r#"
SELECT id, username, password, phone_number, salt_id, firstname, lastname, created, last_login FROM "user" WHERE username = $1
@@ -24,7 +24,37 @@ pub mod user {
match result {
Ok(r) => match r {
Some(r) => Ok(textsender_models::user::User {
Some(r) => Ok(schedtxt_models::user::User {
id: r.try_get("id")?,
username: r.try_get("username")?,
password: r.try_get("password")?,
phone_number: r.try_get("phone_number")?,
salt_id: r.try_get("salt_id")?,
firstname: r.try_get("firstname")?,
lastname: r.try_get("lastname")?,
created: r.try_get("created")?,
last_login: r.try_get("last_login")?,
}),
None => Err(sqlx::Error::RowNotFound),
},
Err(e) => Err(e),
}
}
pub async fn get_with_id(
pool: &sqlx::PgPool,
id: &uuid::Uuid,
) -> Result<schedtxt_models::user::User, sqlx::Error> {
match sqlx::query(
r#"
SELECT id, username, password, phone_number, salt_id, firstname, lastname, created, last_login FROM "user" WHERE id = $1
"#,
)
.bind(id)
.fetch_optional(pool)
.await {
Ok(r) => match r {
Some(r) => Ok(schedtxt_models::user::User {
id: r.try_get("id")?,
username: r.try_get("username")?,
password: r.try_get("password")?,
@@ -43,7 +73,7 @@ pub mod user {
pub async fn update_last_login(
pool: &sqlx::PgPool,
user: &textsender_models::user::User,
user: &schedtxt_models::user::User,
time: &time::OffsetDateTime,
) -> Result<time::OffsetDateTime, sqlx::Error> {
let result = sqlx::query(
@@ -74,6 +104,60 @@ pub mod user {
}
}
pub async fn update_password(
pool: &sqlx::PgPool,
user: &schedtxt_models::user::User,
updated_hashed_password: &String,
) -> Result<(), sqlx::Error> {
match sqlx::query(
r#"
UPDATE "user" SET password = $1 WHERE id = $2
"#,
)
.bind(updated_hashed_password)
.bind(user.id)
.execute(pool)
.await
{
Ok(row) => {
if row.rows_affected() > 0 {
Ok(())
} else {
Err(sqlx::Error::RowNotFound)
}
}
Err(err) => Err(err),
}
}
pub async fn update_name(
pool: &sqlx::PgPool,
id: &uuid::Uuid,
firstname: &str,
lastname: &str,
) -> Result<(), sqlx::Error> {
match sqlx::query(
r#"
UPDATE "user" SET firstname = $1, lastname = $2 WHERE id = $3
"#,
)
.bind(firstname)
.bind(lastname)
.bind(id)
.execute(pool)
.await
{
Ok(row) => {
if row.rows_affected() > 0 {
Ok(())
} else {
Err(sqlx::Error::RowNotFound)
}
}
Err(err) => Err(err),
}
}
pub async fn exists(pool: &sqlx::PgPool, username: &String) -> Result<bool, sqlx::Error> {
let result = sqlx::query(
r#"
@@ -105,7 +189,7 @@ pub mod user {
pub async fn insert(
pool: &sqlx::PgPool,
user: &textsender_models::user::User,
user: &schedtxt_models::user::User,
) -> Result<(uuid::Uuid, std::option::Option<time::OffsetDateTime>), sqlx::Error> {
let row = sqlx::query(
r#"
@@ -153,7 +237,7 @@ pub mod salt {
pub async fn get(
pool: &sqlx::PgPool,
id: &uuid::Uuid,
) -> Result<textsender_models::user::Salt, sqlx::Error> {
) -> Result<schedtxt_models::user::Salt, sqlx::Error> {
let result = sqlx::query(
r#"
SELECT id, salt FROM "salt" WHERE id = $1
@@ -165,7 +249,7 @@ pub mod salt {
match result {
Ok(r) => match r {
Some(r) => Ok(textsender_models::user::Salt {
Some(r) => Ok(schedtxt_models::user::Salt {
id: r.try_get("id")?,
salt: r.try_get("salt")?,
}),
@@ -177,7 +261,7 @@ pub mod salt {
pub async fn insert(
pool: &sqlx::PgPool,
salt: &textsender_models::user::Salt,
salt: &schedtxt_models::user::Salt,
) -> Result<uuid::Uuid, sqlx::Error> {
let row = sqlx::query(
r#"
+118 -12
View File
@@ -49,22 +49,32 @@ pub async fn get_passphrase(
}
}
pub async fn get_with_username(
pub async fn get(
pool: &sqlx::PgPool,
username: &String,
) -> Result<textsender_models::user::ServiceUser, sqlx::Error> {
id: &uuid::Uuid,
) -> Result<schedtxt_models::user::ServiceUser, sqlx::Error> {
match sqlx::query(
r#"SELECT id, username, passphrase, created, last_login FROM "service_user" WHERE username = $1"#
).bind(username)
r#"SELECT id, username, passphrase, created, last_login, salt_id FROM "service_user" WHERE id = $1"#
).bind(id)
.fetch_one(pool).await {
Ok(row) => {
let service_user = textsender_models::user::ServiceUser {
let last_login: Option<time::OffsetDateTime> = match row.try_get("last_login") {
Ok(login) => {
Some(login)
}
Err(err) => {
eprintln!("Error: {err:?}");
None
}
};
let service_user = schedtxt_models::user::ServiceUser {
id: row.try_get("id")?,
username: row.try_get("username")?,
passphrase: row.try_get("passphrase")?,
created: row.try_get("created")?,
last_login: row.try_get("last_login")?,
salt_id: row.try_get("salt_id")?
last_login,
salt_id: row.try_get("salt_id")?,
};
Ok(service_user)
@@ -75,14 +85,109 @@ pub async fn get_with_username(
}
}
pub async fn get_with_username(
pool: &sqlx::PgPool,
username: &String,
) -> Result<schedtxt_models::user::ServiceUser, sqlx::Error> {
match sqlx::query(
r#"SELECT id, username, passphrase, created, last_login, salt_id FROM "service_user" WHERE username = $1"#
).bind(username)
.fetch_one(pool).await {
Ok(row) => {
let last_login: Option<time::OffsetDateTime> = match row.try_get("last_login") {
Ok(login) => {
Some(login)
}
Err(err) => {
eprintln!("Error: {err:?}");
None
}
};
let service_user = schedtxt_models::user::ServiceUser {
id: row.try_get("id")?,
username: row.try_get("username")?,
passphrase: row.try_get("passphrase")?,
created: row.try_get("created")?,
last_login,
salt_id: row.try_get("salt_id")?,
};
Ok(service_user)
}
Err(err) => {
Err(err)
}
}
}
pub async fn update_last_login(
pool: &sqlx::PgPool,
service_user: &schedtxt_models::user::ServiceUser,
time: &time::OffsetDateTime,
) -> Result<time::OffsetDateTime, sqlx::Error> {
let result = sqlx::query(
r#"
UPDATE "service_user" SET last_login = $1 WHERE id = $2 RETURNING last_login
"#,
)
.bind(time)
.bind(service_user.id)
.fetch_optional(pool)
.await
.map_err(|e| {
eprintln!("Error updating time: {e}");
e
});
match result {
Ok(row) => match row {
Some(r) => {
let last_login: time::OffsetDateTime = r
.try_get("last_login")
.map_err(|_e| sqlx::Error::RowNotFound)?;
Ok(last_login)
}
None => Err(sqlx::Error::RowNotFound),
},
Err(err) => Err(err),
}
}
pub async fn update_passphrase(
pool: &sqlx::PgPool,
user: &schedtxt_models::user::ServiceUser,
updated_hashed_passphrase: &String,
) -> Result<(), sqlx::Error> {
match sqlx::query(
r#"
UPDATE "service_user" SET passphrase = $1 WHERE id = $2
"#,
)
.bind(updated_hashed_passphrase)
.bind(user.id)
.execute(pool)
.await
{
Ok(row) => {
if row.rows_affected() > 0 {
Ok(())
} else {
Err(sqlx::Error::RowNotFound)
}
}
Err(err) => Err(err),
}
}
pub async fn insert(
pool: &sqlx::PgPool,
service_user: &textsender_models::user::ServiceUser,
) -> Result<time::OffsetDateTime, sqlx::Error> {
service_user: &schedtxt_models::user::ServiceUser,
) -> Result<(uuid::Uuid, time::OffsetDateTime), sqlx::Error> {
match sqlx::query(
r#"INSERT INTO "service_user" (username, passphrase, salt_id)
VALUES ($1, $2, $3)
RETURNING created
RETURNING id, created
"#,
)
.bind(&service_user.username)
@@ -92,8 +197,9 @@ pub async fn insert(
.await
{
Ok(row) => {
let id: uuid::Uuid = row.try_get("id")?;
let created: time::OffsetDateTime = row.try_get("created")?;
Ok(created)
Ok((id, created))
}
Err(err) => Err(err),
}
+30 -33
View File
@@ -8,8 +8,8 @@ use time;
pub const KEY_ENV: &str = "SECRET_KEY";
pub const MESSAGE: &str = "Something random";
pub const ISSUER: &str = "textsender_auth";
pub const AUDIENCE: &str = "textsender";
pub const ISSUER: &str = "schedtxt_auth";
pub const AUDIENCE: &str = "schedtxt";
pub fn get_expiration(issued: &time::OffsetDateTime) -> Result<time::OffsetDateTime, time::Error> {
let duration_expire = time::Duration::hours(4);
@@ -17,45 +17,45 @@ pub fn get_expiration(issued: &time::OffsetDateTime) -> Result<time::OffsetDateT
}
pub fn create_token(
provided_key: &String,
provided_key: &str,
id: &uuid::Uuid,
) -> Result<(String, i64), josekit::JoseError> {
let resource = textsender_models::token::TokenResource {
) -> Result<schedtxt_models::token::CreateTokenResult, josekit::JoseError> {
let resource = schedtxt_models::token::TokenResource {
message: String::from(MESSAGE),
issuer: String::from(ISSUER),
audiences: vec![String::from(AUDIENCE)],
id: *id,
user_id: *id,
};
textsender_models::token::create_token(provided_key, &resource, time::Duration::hours(4))
schedtxt_models::token::create_token(provided_key, resource, time::Duration::hours(4))
}
pub fn create_service_token(
provided: &String,
provided: &str,
id: &uuid::Uuid,
) -> Result<(String, i64), josekit::JoseError> {
let resource = textsender_models::token::TokenResource {
) -> Result<schedtxt_models::token::CreateTokenResult, josekit::JoseError> {
let resource = schedtxt_models::token::TokenResource {
message: String::from(SERVICE_SUBJECT),
issuer: String::from(ISSUER),
audiences: vec![String::from(AUDIENCE)],
id: *id,
user_id: *id,
};
textsender_models::token::create_token(provided, &resource, time::Duration::hours(1))
schedtxt_models::token::create_token(provided, resource, time::Duration::hours(1))
}
pub fn create_service_refresh_token(
key: &String,
key: &str,
id: &uuid::Uuid,
) -> Result<(String, i64), josekit::JoseError> {
let resource = textsender_models::token::TokenResource {
) -> Result<schedtxt_models::token::CreateTokenResult, josekit::JoseError> {
let resource = schedtxt_models::token::TokenResource {
message: String::from(SERVICE_SUBJECT),
issuer: String::from(ISSUER),
audiences: vec![String::from(AUDIENCE)],
id: *id,
user_id: *id,
};
textsender_models::token::create_token(key, &resource, time::Duration::hours(4))
schedtxt_models::token::create_token(key, resource, time::Duration::hours(4))
}
pub fn verify_token(key: &String, token: &String) -> bool {
pub fn verify_token(key: &str, token: &str) -> bool {
match get_payload(key, token) {
Ok((payload, _header)) => match payload.subject() {
Some(_sub) => true,
@@ -65,9 +65,9 @@ pub fn verify_token(key: &String, token: &String) -> bool {
}
}
pub fn extract_id_from_token(key: &String, token: &String) -> Result<uuid::Uuid, std::io::Error> {
pub fn extract_id_from_token(key: &str, token: &str) -> Result<uuid::Uuid, std::io::Error> {
match get_payload(key, token) {
Ok((payload, _header)) => match payload.claim("id") {
Ok((payload, _header)) => match payload.claim("user_id") {
Some(id) => match uuid::Uuid::parse_str(id.as_str().unwrap()) {
Ok(extracted) => Ok(extracted),
Err(err) => Err(std::io::Error::other(err.to_string())),
@@ -78,12 +78,12 @@ pub fn extract_id_from_token(key: &String, token: &String) -> Result<uuid::Uuid,
}
}
pub const APP_TOKEN_TYPE: &str = "Textsender_App";
pub const APP_TOKEN_TYPE: &str = "Schedtxt_App";
pub const APP_SUBJECT: &str = "Something random";
pub const SERVICE_TOKEN_TYPE: &str = "Textsender_Service";
pub const SERVICE_TOKEN_TYPE: &str = "Schedtxt_Service";
pub const SERVICE_SUBJECT: &str = "Service random";
pub fn get_token_type(key: &String, token: &String) -> Result<String, std::io::Error> {
pub fn get_token_type(key: &str, token: &str) -> Result<String, std::io::Error> {
match get_payload(key, token) {
Ok((payload, _header)) => match payload.subject() {
Some(subject) => {
@@ -101,13 +101,13 @@ pub fn get_token_type(key: &String, token: &String) -> Result<String, std::io::E
}
}
pub fn is_token_type_valid(token_type: &String) -> bool {
pub fn is_token_type_valid(token_type: &str) -> bool {
token_type == SERVICE_TOKEN_TYPE
}
fn get_payload(
key: &String,
token: &String,
key: &str,
token: &str,
) -> Result<(josekit::jwt::JwtPayload, josekit::jws::JwsHeader), josekit::JoseError> {
let ver = Hs256.verifier_from_bytes(key.as_bytes()).unwrap();
jwt::decode_with_verifier(token, &ver)
@@ -119,14 +119,11 @@ mod tests {
#[test]
fn test_tokenize() {
let rt = tokio::runtime::Runtime::new().unwrap();
let special_key = rt
.block_on(textsender_models::envy::environment::get_secret_key())
.value;
let special_key = schedtxt_models::envy::environment::get_secret_key();
let id = uuid::Uuid::new_v4();
match create_token(&special_key, &id) {
Ok((token, _duration)) => {
let result = verify_token(&special_key, &token);
match create_token(&special_key.value, &id) {
Ok(cst) => {
let result = verify_token(&special_key.value, &cst.access_token);
assert!(result, "Token not verified");
}
Err(err) => {
+810 -72
View File
@@ -1,7 +1,7 @@
use textsender_auth;
use textsender_auth::callers;
use textsender_auth::db;
use textsender_auth::init;
use schedtxt_auth;
use schedtxt_auth::callers;
use schedtxt_auth::db;
use schedtxt_auth::init;
mod db_mgr {
use std::str::FromStr;
@@ -9,9 +9,7 @@ mod db_mgr {
pub const LIMIT: usize = 6;
pub async fn get_pool() -> Result<sqlx::PgPool, sqlx::Error> {
let tm_db_url = textsender_models::envy::environment::get_db_url()
.await
.value;
let tm_db_url = schedtxt_models::envy::environment::get_db_url().value;
let tm_options = sqlx::postgres::PgConnectOptions::from_str(&tm_db_url).unwrap();
sqlx::PgPool::connect_with(tm_options).await
}
@@ -23,9 +21,7 @@ mod db_mgr {
}
pub async fn connect_to_db(db_name: &str) -> Result<sqlx::PgPool, sqlx::Error> {
let db_url = textsender_models::envy::environment::get_db_url()
.await
.value;
let db_url = schedtxt_models::envy::environment::get_db_url().value;
let options = sqlx::postgres::PgConnectOptions::from_str(&db_url)?.database(db_name);
sqlx::PgPool::connect_with(options).await
}
@@ -35,7 +31,10 @@ mod db_mgr {
db_name: &str,
) -> Result<(), sqlx::Error> {
let create_query = format!("CREATE DATABASE {}", db_name);
match sqlx::query(&create_query).execute(template_pool).await {
match sqlx::query(sqlx::AssertSqlSafe(create_query))
.execute(template_pool)
.await
{
Ok(_) => Ok(()),
Err(e) => Err(e),
}
@@ -47,14 +46,14 @@ mod db_mgr {
db_name: &str,
) -> Result<(), sqlx::Error> {
let drop_query = format!("DROP DATABASE IF EXISTS {} WITH (FORCE)", db_name);
sqlx::query(&drop_query).execute(template_pool).await?;
sqlx::query(sqlx::AssertSqlSafe(drop_query))
.execute(template_pool)
.await?;
Ok(())
}
pub async fn get_database_name() -> Result<String, Box<dyn std::error::Error>> {
let database_url = textsender_models::envy::environment::get_db_url()
.await
.value;
let database_url = schedtxt_models::envy::environment::get_db_url().value;
let parsed_url = url::Url::parse(&database_url)?;
if parsed_url.scheme() == "postgres" || parsed_url.scheme() == "postgresql" {
@@ -133,6 +132,121 @@ pub mod requests {
app.clone().oneshot(req).await
}
/// Function to call service user login endpoint
pub async fn login_service_user(
app: &axum::Router,
username: &str,
passphrase: &str,
) -> Result<axum::response::Response, std::convert::Infallible> {
let payload = serde_json::json!({
"username": username,
"passphrase": passphrase,
});
let req = axum::http::Request::builder()
.method(axum::http::Method::POST)
.uri(super::callers::endpoints::LOGIN_SERVICE_USER)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::from(payload.to_string()))
.unwrap();
app.clone().oneshot(req).await
}
/// Function to call token refresh endpoint
pub async fn refresh_token(
app: &axum::Router,
access_token: &str,
) -> Result<axum::response::Response, std::convert::Infallible> {
let payload = serde_json::json!({
"access_token": access_token,
});
let req = axum::http::Request::builder()
.method(axum::http::Method::POST)
.uri(super::callers::endpoints::REFRESH_TOKEN)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::from(payload.to_string()))
.unwrap();
app.clone().oneshot(req).await
}
/// Function to call update password endpoint
pub async fn update_password(
app: &axum::Router,
user_id: &uuid::Uuid,
current_password: &str,
updated_password: &str,
confirmed_password: &str,
) -> Result<axum::response::Response, axum::http::Error> {
let payload = serde_json::json!({
"user_id": user_id,
"current_password": current_password,
"updated_password": updated_password,
"confirmed_password": confirmed_password,
});
match axum::http::Request::builder()
.method(axum::http::Method::PATCH)
.uri(super::callers::endpoints::UPDATE_PASSWORD)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::from(payload.to_string()))
{
Ok(req) => match app.clone().oneshot(req).await {
Ok(resp) => Ok(resp),
Err(err) => Err(axum::http::Error::from(err)),
},
Err(err) => Err(err),
}
}
/// Function to call update name of user endpoint
pub async fn update_name_of_user(
app: &axum::Router,
user_id: &uuid::Uuid,
firstname: &str,
lastname: &str,
) -> Result<axum::response::Response, axum::http::Error> {
let payload = serde_json::json!({
"user_id": user_id,
"firstname": firstname,
"lastname": lastname,
});
match axum::http::Request::builder()
.method(axum::http::Method::PATCH)
.uri(super::callers::endpoints::UPDATE_USER_NAME)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::from(payload.to_string()))
{
Ok(req) => match app.clone().oneshot(req).await {
Ok(resp) => Ok(resp),
Err(err) => Err(axum::http::Error::from(err)),
},
Err(err) => Err(err),
}
}
/// Function to call get user profile endpoint
pub async fn get_user_profile(
app: &axum::Router,
user_id: &uuid::Uuid,
) -> Result<axum::response::Response, axum::http::Error> {
let url = super::util::format_url_with_value(
schedtxt_auth::callers::endpoints::GET_USER_PROFILE,
user_id,
);
match axum::http::Request::builder()
.method(axum::http::Method::GET)
.uri(url)
.header(axum::http::header::CONTENT_TYPE, "application/json")
.body(axum::body::Body::empty())
{
Ok(req) => match app.clone().oneshot(req).await {
Ok(resp) => Ok(resp),
Err(err) => Err(axum::http::Error::from(err)),
},
Err(err) => Err(err),
}
}
}
/// Test user firstname
@@ -145,74 +259,293 @@ const TEST_USERNAME: &str = "BillyBob01";
const TEST_PASSWORD: &str = "923ndcry392qryudx328qrdy328r";
/// Test user phone number
const TEST_PHONE_NUMBER: &str = "+10123456789";
/// Test updated user password
const TEST_UPDATED_PASSWORD: &str = "3cnf29ry8q27i3yrc928qi37ryndxc2198q7yd9xzq12837e";
/// Test updated user firstname
const TEST_UPDATED_FIRSTNAME: &str = "Kuoth";
/// Test updated user lastname
const TEST_UPDATED_LASTNAME: &str = "Wech";
/// Test service username
const TEST_SERVICE_USERNAME: &str = "swoon";
/// Test service passphrase
const TEST_SERVICE_PASSPHRASE: &str = "4n5cf349tfy34w857ty39wq45nfdq23";
/// Test updated service user passphrase
const TEST_SERVICE_UPDATED_PASSPHRASE: &str = "3487ncfyth934287fcrty32487fry32in7";
async fn convert_response<T>(response: axum::response::Response) -> Result<T, std::io::Error>
where
T: serde::de::DeserializeOwned,
{
match axum::body::to_bytes(response.into_body(), usize::MAX).await {
Ok(body) => {
let resp: T = serde_json::from_slice(&body).unwrap();
Ok(resp)
mod util {
pub async fn convert_response<T>(
response: axum::response::Response,
) -> Result<T, std::io::Error>
where
T: serde::de::DeserializeOwned,
{
match axum::body::to_bytes(response.into_body(), usize::MAX).await {
Ok(body) => {
let resp: T = match serde_json::from_slice(&body) {
Ok(val) => val,
Err(err) => {
return Err(std::io::Error::other(err.to_string()));
}
};
Ok(resp)
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
pub fn format_url_with_value(endpoint: &str, value: &uuid::Uuid) -> String {
let last = endpoint.len() - 5;
format!("{}/{value}", &endpoint[0..last])
}
}
async fn register_user(
app: &axum::Router,
) -> Result<textsender_models::user::User, std::io::Error> {
match requests::register_user(&app).await {
Ok(response) => {
if axum::http::StatusCode::CREATED != response.status() {
Err(std::io::Error::other(format!(
"Status code is off {:?}",
response.status()
)))
} else {
match axum::body::to_bytes(response.into_body(), usize::MAX).await {
Ok(body) => {
let parsed_body: callers::register::response::Response =
serde_json::from_slice(&body).unwrap();
Ok(parsed_body.data[0].clone())
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
}
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
}
mod flow {
use super::callers;
use super::requests;
use super::util;
async fn login_user(
app: &axum::Router,
username: &str,
password: &str,
) -> Result<textsender_models::token::LoginResult, std::io::Error> {
match requests::login_user(&app, username, password).await {
Ok(response) => {
if axum::http::StatusCode::OK != response.status() {
Err(std::io::Error::other(format!(
"Status code is off {:?}",
response.status()
)))
} else {
match axum::body::to_bytes(response.into_body(), usize::MAX).await {
Ok(body) => {
let parsed_body: callers::login::response::LoginResponse =
serde_json::from_slice(&body).unwrap();
Ok(parsed_body.data[0].clone())
pub async fn register_user(
app: &axum::Router,
) -> Result<schedtxt_models::user::User, std::io::Error> {
match requests::register_user(&app).await {
Ok(response) => {
if axum::http::StatusCode::CREATED != response.status() {
Err(std::io::Error::other(format!(
"Status code is off {:?}",
response.status()
)))
} else {
match util::convert_response::<callers::register::response::Response>(response)
.await
{
Ok(response) => {
if response.data.len() > 0 {
let user = response.data[0].clone();
Ok(user)
} else {
Err(std::io::Error::other("No data returned"))
}
}
Err(err) => Err(err),
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
}
pub async fn login_user(
app: &axum::Router,
username: &str,
password: &str,
) -> Result<schedtxt_models::token::LoginResult, std::io::Error> {
match requests::login_user(&app, username, password).await {
Ok(response) => {
if axum::http::StatusCode::OK != response.status() {
Err(std::io::Error::other(format!(
"Status code is off {:?}",
response.status()
)))
} else {
match util::convert_response::<callers::login::response::LoginResponse>(
response,
)
.await
{
Ok(response) => {
if response.data.len() > 0 {
let user = response.data[0].clone();
Ok(user)
} else {
Err(std::io::Error::other("No data returned"))
}
}
Err(err) => Err(err),
}
}
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
}
pub async fn register_service_user(
app: &axum::Router,
) -> Result<schedtxt_models::user::ServiceUser, std::io::Error> {
match requests::register_service_user(&app).await {
Ok(response) => {
if axum::http::StatusCode::CREATED != response.status() {
Err(std::io::Error::other(format!(
"Status code is off {:?}",
response.status()
)))
} else {
match util::convert_response::<
callers::register::response::RegisterServiceUserResponse,
>(response)
.await
{
Ok(response) => {
if response.data.len() > 0 {
let service_user = response.data[0].clone();
Ok(service_user)
} else {
Err(std::io::Error::other("No data returned"))
}
}
Err(err) => Err(err),
}
}
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
}
pub async fn login_service_user(
app: &axum::Router,
username: &str,
passphrase: &str,
) -> Result<schedtxt_models::token::LoginResult, std::io::Error> {
match requests::login_service_user(&app, username, passphrase).await {
Ok(response) => {
if axum::http::StatusCode::OK != response.status() {
Err(std::io::Error::other(format!(
"Status code is off {:?}",
response.status()
)))
} else {
match util::convert_response::<callers::login::response::ServiceUserLoginResponse>(
response,
)
.await
{
Ok(response) => {
if response.data.len() > 0 {
let login_result = response.data[0].clone();
Ok(login_result)
} else {
Err(std::io::Error::other("No data returned"))
}
}
Err(err) => Err(err),
}
}
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
}
pub async fn refresh_token(
app: &axum::Router,
access_token: &str,
) -> Result<schedtxt_models::token::LoginResult, std::io::Error> {
match requests::refresh_token(app, access_token).await {
Ok(response) => {
if axum::http::StatusCode::OK != response.status() {
Err(std::io::Error::other(format!(
"Status code is off {:?}",
response.status()
)))
} else {
match util::convert_response::<callers::login::response::RefreshTokenResponse>(
response,
)
.await
{
Ok(response) => {
if response.data.len() > 0 {
let login_result = response.data[0].clone();
Ok(login_result)
} else {
Err(std::io::Error::other("No data returned"))
}
}
Err(err) => Err(err),
}
}
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
}
pub async fn update_password(
app: &axum::Router,
user_id: &uuid::Uuid,
current_password: &str,
updated_password: &str,
confirmed_password: &str,
) -> Result<uuid::Uuid, std::io::Error> {
match requests::update_password(
app,
user_id,
current_password,
updated_password,
confirmed_password,
)
.await
{
Ok(response) => {
if axum::http::StatusCode::OK != response.status() {
Err(std::io::Error::other(format!(
"Status code is off {:?}",
response.status()
)))
} else {
match util::convert_response::<callers::login::response::UpdatePasswordResponse>(
response,
)
.await
{
Ok(response) => {
if response.data.len() > 0 {
let id = response.data[0].clone();
Ok(id)
} else {
Err(std::io::Error::other("No data returned"))
}
}
Err(err) => Err(err),
}
}
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
}
pub async fn update_name_of_user(
app: &axum::Router,
user_id: &uuid::Uuid,
firstname: &str,
lastname: &str,
) -> Result<schedtxt_models::user::User, std::io::Error> {
match requests::update_name_of_user(app, user_id, firstname, lastname).await {
Ok(response) => {
if axum::http::StatusCode::OK != response.status() {
Err(std::io::Error::other(format!(
"Status code is off {:?}",
response.status()
)))
} else {
match util::convert_response::<callers::login::response::UserUpdateNameResponse>(
response,
)
.await
{
Ok(response) => {
if response.data.len() > 0 {
let user = response.data[0].clone();
Ok(user)
} else {
Err(std::io::Error::other("No data returned"))
}
}
Err(err) => Err(err),
}
}
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
Err(err) => Err(std::io::Error::other(err.to_string())),
}
}
@@ -236,7 +569,7 @@ async fn test_register_user() {
let app = init::routes().await.layer(axum::Extension(pool));
match register_user(&app).await {
match flow::register_user(&app).await {
Ok(returned_user) => {
assert_eq!(
TEST_USERNAME, returned_user.username,
@@ -276,8 +609,8 @@ async fn test_login_user() {
let app = init::routes().await.layer(axum::Extension(pool));
match register_user(&app).await {
Ok(user) => match login_user(&app, &user.username, TEST_PASSWORD).await {
match flow::register_user(&app).await {
Ok(user) => match flow::login_user(&app, &user.username, TEST_PASSWORD).await {
Ok(login_result) => {
assert_eq!(
false,
@@ -324,7 +657,7 @@ async fn test_register_service_user() {
match requests::register_service_user(&app).await {
Ok(response) => {
match convert_response::<callers::register::response::RegisterServiceUserResponse>(
match util::convert_response::<callers::register::response::RegisterServiceUserResponse>(
response,
)
.await
@@ -354,3 +687,408 @@ async fn test_register_service_user() {
}
}
}
#[tokio::test]
async fn test_login_service_user() {
let tm_pool = db_mgr::get_pool().await.unwrap();
let db_name = db_mgr::generate_db_name().await;
match db_mgr::create_database(&tm_pool, &db_name).await {
Ok(_) => {
println!("Success");
}
Err(e) => {
assert!(false, "Error: {:?}", e.to_string());
}
}
let pool = db_mgr::connect_to_db(&db_name).await.unwrap();
db::init::migrations(&pool).await;
let app = init::routes().await.layer(axum::Extension(pool));
match flow::register_service_user(&app).await {
Ok(user) => {
assert_eq!(
false,
user.id.is_nil(),
"The service user id should not be nil"
);
match flow::login_service_user(&app, TEST_SERVICE_USERNAME, TEST_SERVICE_PASSPHRASE)
.await
{
Ok(login_result) => {
assert_eq!(
false,
login_result.access_token.is_empty(),
"Access token is empty when it should not be"
);
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
match db_mgr::drop_database(&tm_pool, &db_name).await {
Ok(()) => {}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
#[tokio::test]
async fn test_refresh_token() {
let tm_pool = db_mgr::get_pool().await.unwrap();
let db_name = db_mgr::generate_db_name().await;
match db_mgr::create_database(&tm_pool, &db_name).await {
Ok(_) => {
println!("Success");
}
Err(e) => {
assert!(false, "Error: {:?}", e.to_string());
}
}
let pool = db_mgr::connect_to_db(&db_name).await.unwrap();
db::init::migrations(&pool).await;
let app = init::routes().await.layer(axum::Extension(pool));
match flow::register_user(&app).await {
Ok(user) => match flow::login_user(&app, &user.username, TEST_PASSWORD).await {
Ok(login_result) => {
assert_eq!(
false,
login_result.access_token.is_empty(),
"Access token is empty when it should not be"
);
match flow::refresh_token(&app, &login_result.access_token).await {
Ok(refresh_login_result) => {
assert_eq!(
false,
refresh_login_result.access_token.is_empty(),
"Refreshed access token should not be empty"
);
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
},
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
match flow::register_service_user(&app).await {
Ok(user) => {
assert_eq!(
false,
user.id.is_nil(),
"The service user id should not be nil"
);
match flow::login_service_user(&app, TEST_SERVICE_USERNAME, TEST_SERVICE_PASSPHRASE)
.await
{
Ok(login_result) => {
assert_eq!(
false,
login_result.access_token.is_empty(),
"Access token is empty when it should not be"
);
match flow::refresh_token(&app, &login_result.access_token).await {
Ok(refresh_login_result) => {
assert_eq!(
false,
refresh_login_result.access_token.is_empty(),
"Refreshed access token should not be empty"
);
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
match db_mgr::drop_database(&tm_pool, &db_name).await {
Ok(()) => {}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
#[tokio::test]
async fn test_update_password() {
let tm_pool = db_mgr::get_pool().await.unwrap();
let db_name = db_mgr::generate_db_name().await;
match db_mgr::create_database(&tm_pool, &db_name).await {
Ok(_) => {
println!("Success");
}
Err(e) => {
assert!(false, "Error: {:?}", e.to_string());
}
}
let pool = db_mgr::connect_to_db(&db_name).await.unwrap();
db::init::migrations(&pool).await;
let app = init::routes().await.layer(axum::Extension(pool));
match flow::register_user(&app).await {
Ok(user) => match flow::login_user(&app, &user.username, TEST_PASSWORD).await {
Ok(login_result) => {
assert_eq!(
false,
login_result.access_token.is_empty(),
"Access token is empty when it should not be"
);
match flow::update_password(
&app,
&user.id,
TEST_PASSWORD,
TEST_UPDATED_PASSWORD,
TEST_UPDATED_PASSWORD,
)
.await
{
Ok(id) => {
assert_eq!(id, user.id, "Ids do not match");
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
},
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
match flow::register_service_user(&app).await {
Ok(service_user) => {
assert_eq!(
false,
service_user.id.is_nil(),
"The service user id should not be nil"
);
match flow::login_service_user(&app, TEST_SERVICE_USERNAME, TEST_SERVICE_PASSPHRASE)
.await
{
Ok(login_result) => {
assert_eq!(
false,
login_result.access_token.is_empty(),
"Access token is empty when it should not be"
);
match flow::update_password(
&app,
&service_user.id,
TEST_SERVICE_PASSPHRASE,
TEST_SERVICE_UPDATED_PASSPHRASE,
TEST_SERVICE_UPDATED_PASSPHRASE,
)
.await
{
Ok(id) => {
assert_eq!(id, service_user.id, "Ids do not match");
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
match db_mgr::drop_database(&tm_pool, &db_name).await {
Ok(()) => {}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
#[tokio::test]
async fn test_update_name_of_password() {
let tm_pool = db_mgr::get_pool().await.unwrap();
let db_name = db_mgr::generate_db_name().await;
match db_mgr::create_database(&tm_pool, &db_name).await {
Ok(_) => {
println!("Success");
}
Err(e) => {
assert!(false, "Error: {:?}", e.to_string());
}
}
let pool = db_mgr::connect_to_db(&db_name).await.unwrap();
db::init::migrations(&pool).await;
let app = init::routes().await.layer(axum::Extension(pool));
match flow::register_user(&app).await {
Ok(user) => match flow::login_user(&app, &user.username, TEST_PASSWORD).await {
Ok(login_result) => {
assert_eq!(
false,
login_result.access_token.is_empty(),
"Access token is empty when it should not be"
);
match flow::update_name_of_user(
&app,
&user.id,
TEST_UPDATED_FIRSTNAME,
TEST_UPDATED_LASTNAME,
)
.await
{
Ok(user) => {
assert_eq!(
TEST_UPDATED_FIRSTNAME, user.firstname,
"Firstname do not match"
);
assert_eq!(
TEST_UPDATED_LASTNAME, user.lastname,
"Lastname do not match"
);
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
},
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
match db_mgr::drop_database(&tm_pool, &db_name).await {
Ok(()) => {}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
#[tokio::test]
async fn test_get_user_profile() {
let tm_pool = db_mgr::get_pool().await.unwrap();
let db_name = db_mgr::generate_db_name().await;
match db_mgr::create_database(&tm_pool, &db_name).await {
Ok(_) => {
println!("Success");
}
Err(e) => {
assert!(false, "Error: {:?}", e.to_string());
}
}
let pool = db_mgr::connect_to_db(&db_name).await.unwrap();
db::init::migrations(&pool).await;
let app = init::routes().await.layer(axum::Extension(pool));
let user_id = match flow::register_user(&app).await {
Ok(user) => match flow::login_user(&app, &user.username, TEST_PASSWORD).await {
Ok(login_result) => {
assert_eq!(
false,
login_result.access_token.is_empty(),
"Access token is empty when it should not be"
);
login_result.user_id
}
Err(err) => {
assert!(false, "Error: {err:?}");
uuid::Uuid::nil()
}
},
Err(err) => {
assert!(false, "Error: {err:?}");
uuid::Uuid::nil()
}
};
assert_eq!(false, user_id.is_nil(), "User Id should not be empty");
match requests::get_user_profile(&app, &user_id).await {
Ok(response) => {
match util::convert_response::<
schedtxt_auth::callers::login::response::GetUserProfileResponse,
>(response)
.await
{
Ok(response) => {
assert_eq!(false, response.data.is_empty(), "No User Profile found");
let user_profile = &response.data[0];
assert_eq!(
TEST_USERNAME, user_profile.username,
"Username does not match"
);
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
match db_mgr::drop_database(&tm_pool, &db_name).await {
Ok(()) => {}
Err(err) => {
assert!(false, "Error: {err:?}");
}
}
}