mirror of
https://github.com/n08i40k/schedule-parser-rusted.git
synced 2026-09-14 08:58:53 +03:00
Compare commits
1
Commits
master
..
a0a1098b8c
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a0a1098b8c |
@@ -1,5 +1,5 @@
|
|||||||
# Schedule
|
# Schedule
|
||||||
SCHEDULE_YANDEX_DISK_URL="https://disk.yandex.ru/d/xxxxxxxxxxxxxx"
|
# SCHEDULE_INIT_URL=
|
||||||
SCHEDULE_DISABLE_AUTO_UPDATE=1
|
SCHEDULE_DISABLE_AUTO_UPDATE=1
|
||||||
|
|
||||||
# Basic authorization
|
# Basic authorization
|
||||||
@@ -14,9 +14,13 @@ TELEGRAM_BOT_ID=0
|
|||||||
TELEGRAM_MINI_APP_HOST=example.com
|
TELEGRAM_MINI_APP_HOST=example.com
|
||||||
TELEGRAM_TEST_DC=false
|
TELEGRAM_TEST_DC=false
|
||||||
|
|
||||||
|
# Yandex Cloud
|
||||||
|
YANDEX_CLOUD_API_KEY=""
|
||||||
|
YANDEX_CLOUD_FUNC_ID=""
|
||||||
|
|
||||||
# Firebase
|
# Firebase
|
||||||
# GOOGLE_APPLICATION_CREDENTIALS=
|
# GOOGLE_APPLICATION_CREDENTIALS=
|
||||||
|
|
||||||
# LOGGING
|
# LOGGING
|
||||||
RUST_BACKTRACE=1
|
RUST_BACKTRACE=1
|
||||||
# RUST_LOG=debug
|
# RUST_LOG=debug
|
||||||
@@ -13,6 +13,12 @@ env:
|
|||||||
|
|
||||||
BINARY_NAME: schedule-parser-rusted
|
BINARY_NAME: schedule-parser-rusted
|
||||||
|
|
||||||
|
TEST_DB: ${{ secrets.TEST_DATABASE_URL }}
|
||||||
|
|
||||||
|
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||||
|
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
|
||||||
|
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
|
||||||
|
|
||||||
DOCKER_IMAGE_NAME: ${{ github.repository }}
|
DOCKER_IMAGE_NAME: ${{ github.repository }}
|
||||||
|
|
||||||
DOCKER_REGISTRY_HOST: registry.n08i40k.ru
|
DOCKER_REGISTRY_HOST: registry.n08i40k.ru
|
||||||
@@ -37,6 +43,7 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
cargo test
|
cargo test
|
||||||
env:
|
env:
|
||||||
|
DATABASE_URL: ${{ env.TEST_DB }}
|
||||||
SCHEDULE_DISABLE_AUTO_UPDATE: 1
|
SCHEDULE_DISABLE_AUTO_UPDATE: 1
|
||||||
JWT_SECRET: "test-secret-at-least-256-bits-used"
|
JWT_SECRET: "test-secret-at-least-256-bits-used"
|
||||||
VK_ID_CLIENT_ID: 0
|
VK_ID_CLIENT_ID: 0
|
||||||
@@ -44,6 +51,8 @@ jobs:
|
|||||||
TELEGRAM_BOT_ID: 0
|
TELEGRAM_BOT_ID: 0
|
||||||
TELEGRAM_MINI_APP_HOST: example.com
|
TELEGRAM_MINI_APP_HOST: example.com
|
||||||
TELEGRAM_TEST_DC: false
|
TELEGRAM_TEST_DC: false
|
||||||
|
YANDEX_CLOUD_API_KEY: ""
|
||||||
|
YANDEX_CLOUD_FUNC_ID: ""
|
||||||
build:
|
build:
|
||||||
name: Build
|
name: Build
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -67,6 +76,18 @@ jobs:
|
|||||||
objcopy --strip-debug --strip-unneeded target/release/${{ env.BINARY_NAME }}
|
objcopy --strip-debug --strip-unneeded target/release/${{ env.BINARY_NAME }}
|
||||||
objcopy --add-gnu-debuglink target/release/${{ env.BINARY_NAME }}{.d,}
|
objcopy --add-gnu-debuglink target/release/${{ env.BINARY_NAME }}{.d,}
|
||||||
|
|
||||||
|
- name: Setup sentry-cli
|
||||||
|
uses: matbour/setup-sentry-cli@v2.0.0
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
token: ${{ env.SENTRY_AUTH_TOKEN }}
|
||||||
|
organization: ${{ env.SENTRY_ORG }}
|
||||||
|
project: ${{ env.SENTRY_PROJECT }}
|
||||||
|
|
||||||
|
- name: Upload debug symbols to Sentry
|
||||||
|
run: |
|
||||||
|
sentry-cli debug-files upload --include-sources .
|
||||||
|
|
||||||
- name: Upload build binary artifact
|
- name: Upload build binary artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
@@ -118,7 +139,4 @@ jobs:
|
|||||||
cache-from: type=gha
|
cache-from: type=gha
|
||||||
cache-to: type=gha,mode=max
|
cache-to: type=gha,mode=max
|
||||||
build-args: |
|
build-args: |
|
||||||
"BINARY_NAME=${{ env.BINARY_NAME }}"
|
"BINARY_NAME=${{ env.BINARY_NAME }}"
|
||||||
|
|
||||||
- name: Deploy
|
|
||||||
run: curl ${{ secrets.DEPLOY_URL }}
|
|
||||||
@@ -14,6 +14,10 @@ env:
|
|||||||
|
|
||||||
TEST_DB: ${{ secrets.TEST_DATABASE_URL }}
|
TEST_DB: ${{ secrets.TEST_DATABASE_URL }}
|
||||||
|
|
||||||
|
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||||
|
SENTRY_ORG: ${{ secrets.SENTRY_ORG }}
|
||||||
|
SENTRY_PROJECT: ${{ secrets.SENTRY_PROJECT }}
|
||||||
|
|
||||||
DOCKER_IMAGE_NAME: ${{ github.repository }}
|
DOCKER_IMAGE_NAME: ${{ github.repository }}
|
||||||
|
|
||||||
DOCKER_REGISTRY_HOST: registry.n08i40k.ru
|
DOCKER_REGISTRY_HOST: registry.n08i40k.ru
|
||||||
@@ -46,6 +50,8 @@ jobs:
|
|||||||
TELEGRAM_BOT_ID: 0
|
TELEGRAM_BOT_ID: 0
|
||||||
TELEGRAM_MINI_APP_HOST: example.com
|
TELEGRAM_MINI_APP_HOST: example.com
|
||||||
TELEGRAM_TEST_DC: false
|
TELEGRAM_TEST_DC: false
|
||||||
|
YANDEX_CLOUD_API_KEY: ""
|
||||||
|
YANDEX_CLOUD_FUNC_ID: ""
|
||||||
build:
|
build:
|
||||||
name: Build
|
name: Build
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@@ -69,6 +75,18 @@ jobs:
|
|||||||
objcopy --strip-debug --strip-unneeded target/release/${{ env.BINARY_NAME }}
|
objcopy --strip-debug --strip-unneeded target/release/${{ env.BINARY_NAME }}
|
||||||
objcopy --add-gnu-debuglink target/release/${{ env.BINARY_NAME }}{.d,}
|
objcopy --add-gnu-debuglink target/release/${{ env.BINARY_NAME }}{.d,}
|
||||||
|
|
||||||
|
- name: Setup sentry-cli
|
||||||
|
uses: matbour/setup-sentry-cli@v2.0.0
|
||||||
|
with:
|
||||||
|
version: latest
|
||||||
|
token: ${{ env.SENTRY_AUTH_TOKEN }}
|
||||||
|
organization: ${{ env.SENTRY_ORG }}
|
||||||
|
project: ${{ env.SENTRY_PROJECT }}
|
||||||
|
|
||||||
|
- name: Upload debug symbols to Sentry
|
||||||
|
run: |
|
||||||
|
sentry-cli debug-files upload --include-sources .
|
||||||
|
|
||||||
- name: Upload build binary artifact
|
- name: Upload build binary artifact
|
||||||
uses: actions/upload-artifact@v4
|
uses: actions/upload-artifact@v4
|
||||||
with:
|
with:
|
||||||
@@ -152,4 +170,4 @@ jobs:
|
|||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
with:
|
with:
|
||||||
artifacts: "${{ env.BINARY_NAME }},${{ env.BINARY_NAME }}.d"
|
artifacts: "${{ env.BINARY_NAME }},${{ env.BINARY_NAME }}.d"
|
||||||
bodyFile: CHANGELOG.md
|
bodyFile: CHANGELOG.md
|
||||||
@@ -33,3 +33,5 @@ jobs:
|
|||||||
TELEGRAM_BOT_ID: 0
|
TELEGRAM_BOT_ID: 0
|
||||||
TELEGRAM_MINI_APP_HOST: example.com
|
TELEGRAM_MINI_APP_HOST: example.com
|
||||||
TELEGRAM_TEST_DC: false
|
TELEGRAM_TEST_DC: false
|
||||||
|
YANDEX_CLOUD_API_KEY: ""
|
||||||
|
YANDEX_CLOUD_FUNC_ID: ""
|
||||||
Generated
+1685
-1916
File diff suppressed because it is too large
Load Diff
+27
-38
@@ -18,75 +18,64 @@ providers = { path = "providers" }
|
|||||||
actix-macros = { path = "actix-macros" }
|
actix-macros = { path = "actix-macros" }
|
||||||
|
|
||||||
# serve api
|
# serve api
|
||||||
actix-web = "4"
|
actix-web = "4.11.0"
|
||||||
|
|
||||||
# basic
|
# basic
|
||||||
chrono = { version = "0", features = ["serde"] }
|
chrono = { version = "0.4.42", features = ["serde"] }
|
||||||
derive_more = { version = "2", features = ["full"] }
|
derive_more = { version = "2.0.1", features = ["full"] }
|
||||||
dotenvy = "0"
|
dotenvy = "0.15.7"
|
||||||
|
|
||||||
# sql
|
# sql
|
||||||
database = { path = "database" }
|
database = { path = "database" }
|
||||||
|
|
||||||
# logging
|
# logging
|
||||||
env_logger = "0"
|
env_logger = "0.11.8"
|
||||||
|
|
||||||
# async
|
# async
|
||||||
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
|
tokio = { version = "1.47.1", features = ["macros", "rt-multi-thread"] }
|
||||||
tokio-util = "0"
|
tokio-util = "0.7.16"
|
||||||
futures-util = "0"
|
futures-util = "0.3.31"
|
||||||
|
|
||||||
# authorization
|
# authorization
|
||||||
bcrypt = "0"
|
bcrypt = "0.17.1"
|
||||||
jsonwebtoken = { version = "11", features = ["use_pem", "aws_lc_rs"] }
|
jsonwebtoken = { version = "10.1.0", features = ["use_pem"] }
|
||||||
|
|
||||||
# creating users
|
# creating users
|
||||||
objectid = "0"
|
objectid = "0.2.0"
|
||||||
|
|
||||||
# schedule downloader
|
# schedule downloader
|
||||||
reqwest = { version = "0", features = ["json", "form"] }
|
reqwest = { version = "0.12.23", features = ["json"] }
|
||||||
mime = "0"
|
mime = "0.3.17"
|
||||||
|
|
||||||
# error handling
|
# error handling
|
||||||
sentry = { version = "0", default-features = false, features = [
|
sentry = "0.43.0"
|
||||||
"backtrace",
|
sentry-actix = "0.43.0"
|
||||||
"contexts",
|
|
||||||
"debug-images",
|
|
||||||
"logs",
|
|
||||||
"metrics",
|
|
||||||
"panic",
|
|
||||||
"release-health",
|
|
||||||
"reqwest",
|
|
||||||
"rustls",
|
|
||||||
] }
|
|
||||||
sentry-actix = "0"
|
|
||||||
|
|
||||||
# [de]serializing
|
# [de]serializing
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
serde_with = "3"
|
serde_with = "3.14"
|
||||||
|
|
||||||
sha1 = "0.11.0-rc.2"
|
sha1 = "0.11.0-rc.2"
|
||||||
|
|
||||||
# documentation
|
# documentation
|
||||||
utoipa = { version = "5", features = ["actix_extras", "chrono"] }
|
utoipa = { version = "5.4.0", features = ["actix_extras", "chrono"] }
|
||||||
utoipa-rapidoc = { version = "6", features = ["actix-web"] }
|
utoipa-rapidoc = { version = "6.0.0", features = ["actix-web"] }
|
||||||
utoipa-actix-web = "0"
|
utoipa-actix-web = "0.1.2"
|
||||||
|
|
||||||
uuid = { version = "1", features = ["v4"] }
|
uuid = { version = "1.18.1", features = ["v4"] }
|
||||||
hex-literal = "1"
|
hex-literal = "1"
|
||||||
log = "0"
|
log = "0.4.28"
|
||||||
|
|
||||||
# telegram webdata deciding and verify
|
# telegram webdata deciding and verify
|
||||||
base64 = "0"
|
base64 = "0.22.1"
|
||||||
percent-encoding = "2"
|
percent-encoding = "2.3.2"
|
||||||
aws-lc-rs = "1"
|
ed25519-dalek = "3.0.0-pre.1"
|
||||||
|
|
||||||
# development tracing
|
# development tracing
|
||||||
console-subscriber = { version = "0", optional = true }
|
console-subscriber = { version = "0.4.1", optional = true }
|
||||||
tracing = { version = "0", optional = true }
|
tracing = { version = "0.1.41", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
providers = { path = "providers", features = ["test"] }
|
providers = { path = "providers", features = ["test"] }
|
||||||
database = { path = "database", features = ["sqlite"] }
|
actix-test = { path = "actix-test" }
|
||||||
actix-test = { path = "actix-test" }
|
|
||||||
+1
-1
@@ -6,7 +6,7 @@ ARG BINARY_NAME
|
|||||||
WORKDIR /app/
|
WORKDIR /app/
|
||||||
|
|
||||||
RUN apt update && \
|
RUN apt update && \
|
||||||
apt install -y ca-certificates
|
apt install -y libpq5 ca-certificates openssl
|
||||||
|
|
||||||
COPY ./${BINARY_NAME} /bin/main
|
COPY ./${BINARY_NAME} /bin/main
|
||||||
RUN chmod +x /bin/main
|
RUN chmod +x /bin/main
|
||||||
|
|||||||
+2
-6
@@ -3,13 +3,9 @@ name = "database"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[features]
|
|
||||||
sqlite = ["sea-orm/sqlx-sqlite", "migration/sqlite"]
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
migration = { path = "migration" }
|
migration = { path = "migration" }
|
||||||
entity = { path = "entity" }
|
entity = { path = "entity" }
|
||||||
sea-orm = { version = "2.0.0-rc.15", features = ["sqlx-postgres", "runtime-tokio"] }
|
sea-orm = { version = "2.0.0-rc.6", features = ["sqlx-postgres", "runtime-tokio"] }
|
||||||
|
|
||||||
paste = "1"
|
paste = "1.0.15"
|
||||||
serde = { version = "1", features = ["derive"] }
|
|
||||||
@@ -3,5 +3,4 @@
|
|||||||
pub mod prelude;
|
pub mod prelude;
|
||||||
|
|
||||||
pub mod sea_orm_active_enums;
|
pub mod sea_orm_active_enums;
|
||||||
pub mod service_user;
|
|
||||||
pub mod user;
|
pub mod user;
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12
|
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12
|
||||||
|
|
||||||
pub use super::service_user::Entity as ServiceUser;
|
|
||||||
pub use super::user::Entity as User;
|
pub use super::user::Entity as User;
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12
|
|
||||||
|
|
||||||
use sea_orm::entity::prelude::*;
|
|
||||||
|
|
||||||
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
|
|
||||||
#[sea_orm(table_name = "service_user")]
|
|
||||||
pub struct Model {
|
|
||||||
#[sea_orm(primary_key, auto_increment = false)]
|
|
||||||
pub id: String,
|
|
||||||
pub name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
|
||||||
pub enum Relation {}
|
|
||||||
|
|
||||||
impl ActiveModelBehavior for ActiveModel {}
|
|
||||||
@@ -8,14 +8,11 @@ publish = false
|
|||||||
name = "migration"
|
name = "migration"
|
||||||
path = "src/lib.rs"
|
path = "src/lib.rs"
|
||||||
|
|
||||||
[features]
|
|
||||||
sqlite = ["sea-orm-migration/sqlx-sqlite"]
|
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
async-std = { version = "1", features = ["attributes", "tokio1"] }
|
async-std = { version = "1", features = ["attributes", "tokio1"] }
|
||||||
|
|
||||||
[dependencies.sea-orm-migration]
|
[dependencies.sea-orm-migration]
|
||||||
version = "2.0.0-rc.15"
|
version = "2.0.0-rc.6"
|
||||||
features = [
|
features = [
|
||||||
# Enable at least one `ASYNC_RUNTIME` and `DATABASE_DRIVER` feature if you want to run migration via CLI.
|
# Enable at least one `ASYNC_RUNTIME` and `DATABASE_DRIVER` feature if you want to run migration via CLI.
|
||||||
# View the list of supported features at https://www.sea-ql.org/SeaORM/docs/install-and-config/database-and-async-runtime.
|
# View the list of supported features at https://www.sea-ql.org/SeaORM/docs/install-and-config/database-and-async-runtime.
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ pub use sea_orm_migration::prelude::MigratorTrait;
|
|||||||
use sea_orm_migration::prelude::*;
|
use sea_orm_migration::prelude::*;
|
||||||
|
|
||||||
mod m20250904_024854_init;
|
mod m20250904_024854_init;
|
||||||
mod m20251027_230335_add_service_users;
|
|
||||||
|
|
||||||
pub struct Migrator;
|
pub struct Migrator;
|
||||||
|
|
||||||
@@ -12,7 +11,6 @@ impl MigratorTrait for Migrator {
|
|||||||
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
|
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
|
||||||
vec![
|
vec![
|
||||||
Box::new(m20250904_024854_init::Migration),
|
Box::new(m20250904_024854_init::Migration),
|
||||||
Box::new(m20251027_230335_add_service_users::Migration),
|
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use sea_orm_migration::prelude::extension::postgres::Type;
|
use sea_orm_migration::prelude::extension::postgres::Type;
|
||||||
use sea_orm_migration::sea_orm::{DatabaseBackend, EnumIter, Iterable};
|
use sea_orm_migration::sea_orm::{EnumIter, Iterable};
|
||||||
use sea_orm_migration::{prelude::*, schema::*};
|
use sea_orm_migration::{prelude::*, schema::*};
|
||||||
|
|
||||||
#[derive(DeriveMigrationName)]
|
#[derive(DeriveMigrationName)]
|
||||||
@@ -8,16 +8,14 @@ pub struct Migration;
|
|||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl MigrationTrait for Migration {
|
impl MigrationTrait for Migration {
|
||||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||||
if manager.get_database_backend() == DatabaseBackend::Postgres {
|
manager
|
||||||
manager
|
.create_type(
|
||||||
.create_type(
|
Type::create()
|
||||||
Type::create()
|
.as_enum(UserRole)
|
||||||
.as_enum(UserRole)
|
.values(UserRoleVariants::iter())
|
||||||
.values(UserRoleVariants::iter())
|
.to_owned(),
|
||||||
.to_owned(),
|
)
|
||||||
)
|
.await?;
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
manager
|
manager
|
||||||
.create_table(
|
.create_table(
|
||||||
@@ -42,13 +40,9 @@ impl MigrationTrait for Migration {
|
|||||||
.drop_table(Table::drop().table(User::Table).to_owned())
|
.drop_table(Table::drop().table(User::Table).to_owned())
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if manager.get_database_backend() == DatabaseBackend::Postgres {
|
manager
|
||||||
manager
|
.drop_type(Type::drop().name(UserRole).to_owned())
|
||||||
.drop_type(Type::drop().name(UserRole).to_owned())
|
.await
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,33 +0,0 @@
|
|||||||
use sea_orm_migration::{prelude::*, schema::*};
|
|
||||||
|
|
||||||
#[derive(DeriveMigrationName)]
|
|
||||||
pub struct Migration;
|
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
|
||||||
impl MigrationTrait for Migration {
|
|
||||||
async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
manager
|
|
||||||
.create_table(
|
|
||||||
Table::create()
|
|
||||||
.table(ServiceUser::Table)
|
|
||||||
.if_not_exists()
|
|
||||||
.col(string_uniq(ServiceUser::Id).primary_key().not_null())
|
|
||||||
.col(string(ServiceUser::Name))
|
|
||||||
.to_owned(),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
|
||||||
manager
|
|
||||||
.drop_table(Table::drop().table(ServiceUser::Table).to_owned())
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(DeriveIden)]
|
|
||||||
enum ServiceUser {
|
|
||||||
Table,
|
|
||||||
Id,
|
|
||||||
Name,
|
|
||||||
}
|
|
||||||
+1
-22
@@ -4,28 +4,7 @@ pub use migration;
|
|||||||
pub use sea_orm;
|
pub use sea_orm;
|
||||||
|
|
||||||
pub mod entity {
|
pub mod entity {
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
|
|
||||||
pub use entity::*;
|
pub use entity::*;
|
||||||
|
|
||||||
pub use entity::user::{
|
pub use entity::user::{ActiveModel as ActiveUser, Model as User, Entity as UserEntity, Column as UserColumn};
|
||||||
ActiveModel as ActiveUser, //
|
|
||||||
Column as UserColumn, //
|
|
||||||
Entity as UserEntity, //
|
|
||||||
Model as User, //
|
|
||||||
};
|
|
||||||
|
|
||||||
pub use entity::service_user::{
|
|
||||||
ActiveModel as ActiveServiceUser, //
|
|
||||||
Column as ServiceUserColumn, //
|
|
||||||
Entity as ServiceUserEntity, //
|
|
||||||
Model as ServiceUser, //
|
|
||||||
};
|
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Deserialize, PartialEq)]
|
|
||||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
|
||||||
pub enum UserType {
|
|
||||||
Default,
|
|
||||||
Service,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,8 +51,6 @@ macro_rules! define_find_by {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl Query {
|
impl Query {
|
||||||
// User
|
|
||||||
|
|
||||||
define_find_by!(user, id, str, Id);
|
define_find_by!(user, id, str, Id);
|
||||||
define_find_by!(user, telegram_id, i64, TelegramId);
|
define_find_by!(user, telegram_id, i64, TelegramId);
|
||||||
define_find_by!(user, vk_id, i32, VkId);
|
define_find_by!(user, vk_id, i32, VkId);
|
||||||
@@ -62,12 +60,4 @@ impl Query {
|
|||||||
define_is_exists!(user, username, str, Username);
|
define_is_exists!(user, username, str, Username);
|
||||||
define_is_exists!(user, telegram_id, i64, TelegramId);
|
define_is_exists!(user, telegram_id, i64, TelegramId);
|
||||||
define_is_exists!(user, vk_id, i32, VkId);
|
define_is_exists!(user, vk_id, i32, VkId);
|
||||||
|
|
||||||
// Service user
|
|
||||||
|
|
||||||
define_find_by!(service_user, id, str, Id);
|
|
||||||
define_find_by!(service_user, name, str, Name);
|
|
||||||
|
|
||||||
define_is_exists!(service_user, id, str, Id);
|
|
||||||
define_is_exists!(service_user, name, str, Name);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -103,9 +103,6 @@ pub enum LessonType {
|
|||||||
|
|
||||||
/// Практическое занятие.
|
/// Практическое занятие.
|
||||||
Practice,
|
Practice,
|
||||||
|
|
||||||
/// Дифференцированный зачёт.
|
|
||||||
DifferentiatedExam,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
|
#[derive(Clone, Hash, Debug, Serialize, Deserialize, ToSchema)]
|
||||||
|
|||||||
@@ -9,35 +9,23 @@ test = []
|
|||||||
[dependencies]
|
[dependencies]
|
||||||
base = { path = "../base" }
|
base = { path = "../base" }
|
||||||
|
|
||||||
tokio = { version = "1", features = ["sync", "macros", "time"] }
|
tokio = { version = "1.47.1", features = ["sync", "macros", "time"] }
|
||||||
tokio-util = "0"
|
tokio-util = "0.7.16"
|
||||||
|
|
||||||
chrono = { version = "0", features = ["serde"] }
|
chrono = { version = "0.4.41", features = ["serde"] }
|
||||||
|
|
||||||
derive_more = { version = "2", features = ["error", "display", "from"] }
|
derive_more = { version = "2.0.1", features = ["error", "display", "from"] }
|
||||||
|
|
||||||
utoipa = { version = "5", features = ["macros", "chrono"] }
|
utoipa = { version = "5.4.0", features = ["macros", "chrono"] }
|
||||||
|
|
||||||
calamine = "0"
|
calamine = "0.31"
|
||||||
async-trait = "0"
|
async-trait = "0.1.89"
|
||||||
|
|
||||||
reqwest = { version = "0", features = ["json"] }
|
reqwest = "0.12.23"
|
||||||
serde = { version = "1", features = ["derive"] }
|
ua_generator = "0.5.22"
|
||||||
percent-encoding = "2"
|
regex = "1.11.2"
|
||||||
ua_generator = "0"
|
strsim = "0.11.1"
|
||||||
regex = "1"
|
log = "0.4.27"
|
||||||
strsim = "0"
|
sentry = "0.43.0"
|
||||||
log = "0"
|
fancy-regex = "0.16.2"
|
||||||
sentry = { version = "0", default-features = false, features = [
|
|
||||||
"backtrace",
|
|
||||||
"contexts",
|
|
||||||
"debug-images",
|
|
||||||
"logs",
|
|
||||||
"metrics",
|
|
||||||
"panic",
|
|
||||||
"release-health",
|
|
||||||
"reqwest",
|
|
||||||
"rustls",
|
|
||||||
] }
|
|
||||||
fancy-regex = "0"
|
|
||||||
|
|
||||||
|
|||||||
@@ -63,6 +63,8 @@ impl ScheduleProvider for Wrapper {
|
|||||||
this.snapshot = Arc::new(snapshot);
|
this.snapshot = Arc::new(snapshot);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
Err(updater::Error::EmptyUri) => {},
|
||||||
|
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
sentry::capture_error(&err);
|
sentry::capture_error(&err);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
pub use self::error::{Error, Result};
|
pub use self::error::{Error, Result};
|
||||||
use crate::or_continue;
|
use crate::or_continue;
|
||||||
use crate::parser::LessonParseResult::{Lessons, Street};
|
|
||||||
use crate::parser::worksheet::{CellPos, CellRange, WorkSheet};
|
use crate::parser::worksheet::{CellPos, CellRange, WorkSheet};
|
||||||
|
use crate::parser::LessonParseResult::{Lessons, Street};
|
||||||
use base::LessonType::Break;
|
use base::LessonType::Break;
|
||||||
use base::{
|
use base::{
|
||||||
Day, Lesson, LessonBoundaries, LessonSubGroup, LessonType, ParsedSchedule, ScheduleEntry,
|
Day, Lesson, LessonBoundaries, LessonSubGroup, LessonType, ParsedSchedule, ScheduleEntry,
|
||||||
};
|
};
|
||||||
use calamine::{Reader, Xls, open_workbook_from_rs};
|
use calamine::{open_workbook_from_rs, Reader, Xls};
|
||||||
use chrono::{DateTime, Duration, NaiveDate, NaiveTime, Utc};
|
use chrono::{DateTime, Duration, NaiveDate, NaiveTime, Utc};
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
@@ -187,7 +187,6 @@ fn guess_lesson_type(text: &str) -> Option<LessonType> {
|
|||||||
("курсовой проект", LessonType::CourseProject),
|
("курсовой проект", LessonType::CourseProject),
|
||||||
("защита курсового проекта", LessonType::CourseProjectDefense),
|
("защита курсового проекта", LessonType::CourseProjectDefense),
|
||||||
("практическое занятие", LessonType::Practice),
|
("практическое занятие", LessonType::Practice),
|
||||||
("дифференцированный зачет", LessonType::DifferentiatedExam),
|
|
||||||
])
|
])
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -243,9 +242,12 @@ fn parse_lesson(
|
|||||||
.first()
|
.first()
|
||||||
.ok_or(Error::LessonTimeNotFound(CellPos::new(row, group_column)))?;
|
.ok_or(Error::LessonTimeNotFound(CellPos::new(row, group_column)))?;
|
||||||
|
|
||||||
let range: Option<[u8; 2]> = lesson_boundaries
|
let range: Option<[u8; 2]> = if lesson_boundaries.default_index.is_some() {
|
||||||
.default_index
|
let default = lesson_boundaries.default_index.unwrap() as u8;
|
||||||
.map(|default_index| [default_index as u8, end_time.default_index.unwrap() as u8]);
|
Some([default, end_time.default_index.unwrap() as u8])
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
|
||||||
let time = LessonBoundaries {
|
let time = LessonBoundaries {
|
||||||
start: lesson_boundaries.time_range.start,
|
start: lesson_boundaries.time_range.start,
|
||||||
@@ -740,8 +742,8 @@ pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParsedSchedule> {
|
|||||||
.clone();
|
.clone();
|
||||||
|
|
||||||
let worksheet_merges = workbook
|
let worksheet_merges = workbook
|
||||||
.merge_cells_by_sheet_name(&worksheet_name)
|
.worksheet_merge_cells(&worksheet_name)
|
||||||
.map_err(|_| Error::NoWorkSheets)?;
|
.ok_or(Error::NoWorkSheets)?;
|
||||||
|
|
||||||
WorkSheet {
|
WorkSheet {
|
||||||
data: worksheet,
|
data: worksheet,
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ fn format_column_index(index: u32) -> String {
|
|||||||
return format!("{}{}", format_column_index(quotient - 1), char);
|
return format!("{}{}", format_column_index(quotient - 1), char);
|
||||||
}
|
}
|
||||||
|
|
||||||
char.to_string()
|
return char.to_string();
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Display for CellPos {
|
impl Display for CellPos {
|
||||||
|
|||||||
@@ -3,16 +3,25 @@ use derive_more::{Display, Error, From};
|
|||||||
|
|
||||||
#[derive(Debug, Display, Error, From)]
|
#[derive(Debug, Display, Error, From)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
/// The remote file has not changed since the last update.
|
/// Occurs when the request to the Yandex Cloud API fails.
|
||||||
#[display("The schedule file has not changed.")]
|
///
|
||||||
NotModified,
|
/// This may be due to network issues, invalid API key, incorrect function ID, or other
|
||||||
|
/// problems with the Yandex Cloud Function invocation.
|
||||||
|
#[display("An error occurred during the request to the Yandex Cloud API: {_0}")]
|
||||||
|
Reqwest(reqwest::Error),
|
||||||
|
|
||||||
/// The lookup of the current schedule file failed, either due to network issues or an
|
#[display("Unable to get URI in 3 retries")]
|
||||||
/// unexpected response from the storage.
|
EmptyUri,
|
||||||
|
|
||||||
|
/// The ETag is the same (no update needed).
|
||||||
|
#[display("The ETag is the same.")]
|
||||||
|
SameETag,
|
||||||
|
|
||||||
|
/// The URL query for the XLS file failed to execute, either due to network issues or invalid API parameters.
|
||||||
#[display("Failed to fetch URL: {_0}")]
|
#[display("Failed to fetch URL: {_0}")]
|
||||||
ScheduleFetchFailed(FetchError),
|
ScheduleFetchFailed(FetchError),
|
||||||
|
|
||||||
/// Downloading the XLS file content failed after successfully locating the file.
|
/// Downloading the XLS file content failed after successfully obtaining the URL.
|
||||||
#[display("Download failed: {_0}")]
|
#[display("Download failed: {_0}")]
|
||||||
ScheduleDownloadFailed(FetchError),
|
ScheduleDownloadFailed(FetchError),
|
||||||
|
|
||||||
|
|||||||
@@ -1,48 +1,40 @@
|
|||||||
pub use self::error::{Error, Result};
|
pub use self::error::{Error, Result};
|
||||||
use crate::parser::parse_xls;
|
use crate::parser::parse_xls;
|
||||||
use crate::xls_downloader::{FetchError, Source};
|
use crate::xls_downloader::{FetchError, XlsDownloader};
|
||||||
use base::ScheduleSnapshot;
|
use base::ScheduleSnapshot;
|
||||||
use chrono::Utc;
|
|
||||||
mod error;
|
mod error;
|
||||||
|
|
||||||
pub enum UpdateSource {
|
pub enum UpdateSource {
|
||||||
Prepared(ScheduleSnapshot),
|
Prepared(ScheduleSnapshot),
|
||||||
|
|
||||||
/// Public Yandex Disk folder the college uploads the schedule to.
|
Url(String),
|
||||||
YandexDisk {
|
|
||||||
public_url: String,
|
GrabFromSite {
|
||||||
|
yandex_api_key: String,
|
||||||
|
yandex_func_id: String,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Updater {
|
pub struct Updater {
|
||||||
|
downloader: XlsDownloader,
|
||||||
update_source: UpdateSource,
|
update_source: UpdateSource,
|
||||||
|
|
||||||
/// Version of the file the current snapshot was built from.
|
|
||||||
version: Option<String>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Updater {
|
impl Updater {
|
||||||
/// Place the schedule is downloaded from, or [`None`] for a prepared snapshot.
|
/// Constructs a new `ScheduleSnapshot` by downloading and parsing schedule data from the specified URL.
|
||||||
fn source(&self) -> Option<Source> {
|
|
||||||
match &self.update_source {
|
|
||||||
UpdateSource::Prepared(_) => None,
|
|
||||||
UpdateSource::YandexDisk { public_url } => Some(Source::new(public_url.clone())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Constructs a new [`ScheduleSnapshot`] by downloading and parsing the current schedule file.
|
|
||||||
///
|
///
|
||||||
/// The file is looked up first, and its content is downloaded only when the version marker
|
/// This method first checks if the provided URL is the same as the one already configured in the downloader.
|
||||||
/// differs from the one the current snapshot was built from.
|
/// If different, it updates the downloader's URL, fetches the XLS content, parses it, and creates a snapshot.
|
||||||
|
/// Errors are returned for URL conflicts, network issues, download failures, or invalid data.
|
||||||
///
|
///
|
||||||
/// # Returns
|
/// # Arguments
|
||||||
///
|
///
|
||||||
/// Returns [`Error::NotModified`] when the remote file has not changed since the last update,
|
/// * `downloader`: A mutable reference to an `XLSDownloader` implementation used to fetch and parse the schedule data.
|
||||||
/// or an error describing the failed download or parsing.
|
/// * `url`: The source URL pointing to the XLS file containing schedule data.
|
||||||
async fn new_snapshot(&mut self) -> Result<ScheduleSnapshot> {
|
///
|
||||||
let source = self.source().expect("a prepared snapshot has no source");
|
/// returns: Result<ScheduleSnapshot, SnapshotCreationError>
|
||||||
|
async fn new_snapshot(downloader: &mut XlsDownloader, url: String) -> Result<ScheduleSnapshot> {
|
||||||
let file = source.probe().await.map_err(|error| {
|
let head_result = downloader.set_url(&url).await.map_err(|error| {
|
||||||
if let FetchError::Reqwest(error) = &error {
|
if let FetchError::Reqwest(error) = &error {
|
||||||
sentry::capture_error(&error);
|
sentry::capture_error(&error);
|
||||||
}
|
}
|
||||||
@@ -50,44 +42,110 @@ impl Updater {
|
|||||||
Error::ScheduleFetchFailed(error)
|
Error::ScheduleFetchFailed(error)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
if self.version.as_deref() == Some(file.version.as_str()) {
|
if downloader.etag == Some(head_result.etag) {
|
||||||
return Err(Error::NotModified);
|
return Err(Error::SameETag);
|
||||||
}
|
}
|
||||||
|
|
||||||
let xls_data = source.download(&file).await.map_err(|error| {
|
let xls_data = downloader
|
||||||
if let FetchError::Reqwest(error) = &error {
|
.fetch(false)
|
||||||
sentry::capture_error(&error);
|
.await
|
||||||
}
|
.map_err(|error| {
|
||||||
|
if let FetchError::Reqwest(error) = &error {
|
||||||
|
sentry::capture_error(&error);
|
||||||
|
}
|
||||||
|
|
||||||
Error::ScheduleDownloadFailed(error)
|
Error::ScheduleDownloadFailed(error)
|
||||||
})?;
|
})?
|
||||||
|
.data
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
let parse_result = parse_xls(&xls_data)?;
|
let parse_result = parse_xls(&xls_data)?;
|
||||||
|
|
||||||
self.version = Some(file.version);
|
|
||||||
|
|
||||||
Ok(ScheduleSnapshot {
|
Ok(ScheduleSnapshot {
|
||||||
fetched_at: Utc::now(),
|
fetched_at: head_result.requested_at,
|
||||||
updated_at: file.modified_at,
|
updated_at: head_result.uploaded_at,
|
||||||
url: file.url,
|
url,
|
||||||
data: parse_result,
|
data: parse_result,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Initializes the schedule by downloading the current file from the configured source.
|
/// Queries the Yandex Cloud Function (FaaS) to obtain a URL for the schedule file.
|
||||||
|
///
|
||||||
|
/// This sends a POST request to the specified Yandex Cloud Function endpoint,
|
||||||
|
/// using the provided API key for authentication. The returned URI is combined
|
||||||
|
/// with the "https://politehnikum-eng.ru" base domain to form the complete URL.
|
||||||
///
|
///
|
||||||
/// # Arguments
|
/// # Arguments
|
||||||
///
|
///
|
||||||
/// * `update_source`: Place the schedule is taken from.
|
/// * `api_key` - Authentication token for Yandex Cloud API
|
||||||
|
/// * `func_id` - ID of the target Yandex Cloud Function to invoke
|
||||||
///
|
///
|
||||||
/// # Returns
|
/// # Returns
|
||||||
///
|
///
|
||||||
/// Returns the updater together with the initial [`ScheduleSnapshot`], or an error if the
|
/// Result containing:
|
||||||
/// schedule could not be downloaded or parsed.
|
/// - `Ok(String)` - Complete URL constructed from the Function's response
|
||||||
|
/// - `Err(QueryUrlError)` - If the request or response processing fails
|
||||||
|
async fn query_url(api_key: &str, func_id: &str) -> Result<String> {
|
||||||
|
let client = reqwest::Client::new();
|
||||||
|
|
||||||
|
let uri = {
|
||||||
|
// вот бы добавили named-scopes как в котлине,
|
||||||
|
// чтоб мне не пришлось такой хуйнёй страдать.
|
||||||
|
#[allow(unused_assignments)]
|
||||||
|
let mut uri = String::new();
|
||||||
|
let mut counter = 0;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if counter == 3 {
|
||||||
|
return Err(Error::EmptyUri);
|
||||||
|
}
|
||||||
|
|
||||||
|
counter += 1;
|
||||||
|
|
||||||
|
uri = client
|
||||||
|
.post(format!(
|
||||||
|
"https://functions.yandexcloud.net/{}?integration=raw",
|
||||||
|
func_id
|
||||||
|
))
|
||||||
|
.header("Authorization", format!("Api-Key {}", api_key))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(Error::Reqwest)?
|
||||||
|
.text()
|
||||||
|
.await
|
||||||
|
.map_err(Error::Reqwest)?;
|
||||||
|
|
||||||
|
if uri.is_empty() {
|
||||||
|
log::warn!("[{}] Unable to get uri! Retrying in 5 seconds...", counter);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
uri
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(format!("https://politehnikum-eng.ru{}", uri.trim()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initializes the schedule by fetching the URL from the environment or Yandex Cloud Function (FaaS)
|
||||||
|
/// and creating a [`ScheduleSnapshot`] with the downloaded data.
|
||||||
|
///
|
||||||
|
/// # Arguments
|
||||||
|
///
|
||||||
|
/// * `downloader`: Mutable reference to an `XLSDownloader` implementation used to fetch and parse the schedule
|
||||||
|
/// * `app_env`: Reference to the application environment containing either a predefined URL or Yandex Cloud credentials
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
///
|
||||||
|
/// Returns `Ok(())` if the snapshot was successfully initialized, or an `Error` if:
|
||||||
|
/// - URL query to Yandex Cloud failed ([`QueryUrlError`])
|
||||||
|
/// - Schedule snapshot creation failed ([`SnapshotCreationError`])
|
||||||
pub async fn new(update_source: UpdateSource) -> Result<(Self, ScheduleSnapshot)> {
|
pub async fn new(update_source: UpdateSource) -> Result<(Self, ScheduleSnapshot)> {
|
||||||
let mut this = Updater {
|
let mut this = Updater {
|
||||||
|
downloader: XlsDownloader::new(),
|
||||||
update_source,
|
update_source,
|
||||||
version: None,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
if let UpdateSource::Prepared(snapshot) = &this.update_source {
|
if let UpdateSource::Prepared(snapshot) = &this.update_source {
|
||||||
@@ -95,24 +153,43 @@ impl Updater {
|
|||||||
return Ok((this, snapshot));
|
return Ok((this, snapshot));
|
||||||
}
|
}
|
||||||
|
|
||||||
log::info!("Creating the initial schedule snapshot...");
|
let url = match &this.update_source {
|
||||||
|
UpdateSource::Url(url) => {
|
||||||
|
log::info!("The default link {} will be used", url);
|
||||||
|
url.clone()
|
||||||
|
}
|
||||||
|
UpdateSource::GrabFromSite {
|
||||||
|
yandex_api_key,
|
||||||
|
yandex_func_id,
|
||||||
|
} => {
|
||||||
|
log::info!("Obtaining a link using FaaS...");
|
||||||
|
Self::query_url(yandex_api_key, yandex_func_id).await?
|
||||||
|
}
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
|
||||||
let snapshot = this.new_snapshot().await?;
|
log::info!("For the initial setup, a link {} will be used", url);
|
||||||
|
|
||||||
|
let snapshot = Self::new_snapshot(&mut this.downloader, url).await?;
|
||||||
log::info!("Schedule snapshot successfully created!");
|
log::info!("Schedule snapshot successfully created!");
|
||||||
|
|
||||||
Ok((this, snapshot))
|
Ok((this, snapshot))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rebuilds the schedule snapshot from the current remote file.
|
/// Updates the schedule snapshot by querying the latest URL from FaaS and checking for changes.
|
||||||
///
|
/// If the URL hasn't changed, only updates the [`fetched_at`] timestamp. If changed, downloads
|
||||||
/// When the remote file has not changed, the current snapshot is reused with a refreshed
|
/// and parses the new schedule data.
|
||||||
/// fetch timestamp.
|
|
||||||
///
|
///
|
||||||
/// # Arguments
|
/// # Arguments
|
||||||
///
|
///
|
||||||
/// * `current_snapshot`: Snapshot the provider currently serves.
|
/// * `downloader`: XLS file downloader used to fetch and parse the schedule data
|
||||||
|
/// * `app_env`: Application environment containing Yandex Cloud configuration and auto-update settings
|
||||||
///
|
///
|
||||||
/// returns: `Result<ScheduleSnapshot, Error>`
|
/// returns: `Result<(), Error>` - Returns error if URL query fails or schedule parsing encounters issues
|
||||||
|
///
|
||||||
|
/// # Safety
|
||||||
|
///
|
||||||
|
/// Use `unsafe` to access the initialized snapshot, guaranteed valid by prior `init()` call
|
||||||
pub async fn update(
|
pub async fn update(
|
||||||
&mut self,
|
&mut self,
|
||||||
current_snapshot: &ScheduleSnapshot,
|
current_snapshot: &ScheduleSnapshot,
|
||||||
@@ -123,9 +200,18 @@ impl Updater {
|
|||||||
return Ok(snapshot);
|
return Ok(snapshot);
|
||||||
}
|
}
|
||||||
|
|
||||||
let snapshot = match self.new_snapshot().await {
|
let url = match &self.update_source {
|
||||||
|
UpdateSource::Url(url) => url.clone(),
|
||||||
|
UpdateSource::GrabFromSite {
|
||||||
|
yandex_api_key,
|
||||||
|
yandex_func_id,
|
||||||
|
} => Self::query_url(yandex_api_key.as_str(), yandex_func_id.as_str()).await?,
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let snapshot = match Self::new_snapshot(&mut self.downloader, url).await {
|
||||||
Ok(snapshot) => snapshot,
|
Ok(snapshot) => snapshot,
|
||||||
Err(Error::NotModified) => {
|
Err(Error::SameETag) => {
|
||||||
let mut clone = current_snapshot.clone();
|
let mut clone = current_snapshot.clone();
|
||||||
clone.update();
|
clone.update();
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,253 @@
|
|||||||
|
use chrono::{DateTime, Utc};
|
||||||
|
use derive_more::{Display, Error};
|
||||||
|
use std::mem::discriminant;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use utoipa::ToSchema;
|
||||||
|
|
||||||
|
/// XLS data retrieval errors.
|
||||||
|
#[derive(Clone, Debug, ToSchema, Display, Error)]
|
||||||
|
pub enum FetchError {
|
||||||
|
/// File url is not set.
|
||||||
|
#[display("The link to the timetable was not provided earlier.")]
|
||||||
|
NoUrlProvided,
|
||||||
|
|
||||||
|
/// Unknown error.
|
||||||
|
#[display("An unknown error occurred while downloading the file.")]
|
||||||
|
#[schema(value_type = String)]
|
||||||
|
Reqwest(Arc<reqwest::Error>),
|
||||||
|
|
||||||
|
/// Server returned a status code different from 200.
|
||||||
|
#[display("Server returned a status code {status_code}.")]
|
||||||
|
BadStatusCode { status_code: u16 },
|
||||||
|
|
||||||
|
/// The url leads to a file of a different type.
|
||||||
|
#[display("The link leads to a file of type '{content_type}'.")]
|
||||||
|
BadContentType { content_type: String },
|
||||||
|
|
||||||
|
/// Server doesn't return expected headers.
|
||||||
|
#[display("Server doesn't return expected header(s) '{expected_header}'.")]
|
||||||
|
BadHeaders { expected_header: String },
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FetchError {
|
||||||
|
pub fn unknown(error: Arc<reqwest::Error>) -> Self {
|
||||||
|
Self::Reqwest(error)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bad_status_code(status_code: u16) -> Self {
|
||||||
|
Self::BadStatusCode { status_code }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bad_content_type(content_type: &str) -> Self {
|
||||||
|
Self::BadContentType {
|
||||||
|
content_type: content_type.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bad_headers(expected_header: &str) -> Self {
|
||||||
|
Self::BadHeaders {
|
||||||
|
expected_header: expected_header.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PartialEq for FetchError {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
discriminant(self) == discriminant(other)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Result of XLS data retrieval.
|
||||||
|
#[derive(Debug, PartialEq)]
|
||||||
|
pub struct FetchOk {
|
||||||
|
/// File upload date.
|
||||||
|
pub uploaded_at: DateTime<Utc>,
|
||||||
|
|
||||||
|
/// Date data received.
|
||||||
|
pub requested_at: DateTime<Utc>,
|
||||||
|
|
||||||
|
/// Etag.
|
||||||
|
pub etag: String,
|
||||||
|
|
||||||
|
/// File data.
|
||||||
|
pub data: Option<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl FetchOk {
|
||||||
|
/// Result without file content.
|
||||||
|
pub fn head(uploaded_at: DateTime<Utc>, etag: String) -> Self {
|
||||||
|
FetchOk {
|
||||||
|
uploaded_at,
|
||||||
|
requested_at: Utc::now(),
|
||||||
|
etag,
|
||||||
|
data: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Full result.
|
||||||
|
pub fn get(uploaded_at: DateTime<Utc>, etag: String, data: Vec<u8>) -> Self {
|
||||||
|
FetchOk {
|
||||||
|
uploaded_at,
|
||||||
|
requested_at: Utc::now(),
|
||||||
|
etag,
|
||||||
|
data: Some(data),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub type FetchResult = Result<FetchOk, FetchError>;
|
||||||
|
|
||||||
|
pub struct XlsDownloader {
|
||||||
|
pub url: Option<String>,
|
||||||
|
pub etag: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl XlsDownloader {
|
||||||
|
pub fn new() -> Self {
|
||||||
|
XlsDownloader {
|
||||||
|
url: None,
|
||||||
|
etag: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn fetch_specified(url: &str, head: bool) -> FetchResult {
|
||||||
|
let client = reqwest::Client::new();
|
||||||
|
|
||||||
|
let response = if head {
|
||||||
|
client.head(url)
|
||||||
|
} else {
|
||||||
|
client.get(url)
|
||||||
|
}
|
||||||
|
.header("User-Agent", ua_generator::ua::spoof_chrome_ua())
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.map_err(|e| FetchError::unknown(Arc::new(e)))?;
|
||||||
|
|
||||||
|
if response.status().as_u16() != 200 {
|
||||||
|
return Err(FetchError::bad_status_code(response.status().as_u16()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let headers = response.headers();
|
||||||
|
|
||||||
|
let content_type = headers
|
||||||
|
.get("Content-Type")
|
||||||
|
.ok_or(FetchError::bad_headers("Content-Type"))?;
|
||||||
|
|
||||||
|
let etag = headers
|
||||||
|
.get("etag")
|
||||||
|
.ok_or(FetchError::bad_headers("etag"))?
|
||||||
|
.to_str()
|
||||||
|
.or(Err(FetchError::bad_headers("etag")))?
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
let last_modified = headers
|
||||||
|
.get("last-modified")
|
||||||
|
.ok_or(FetchError::bad_headers("last-modified"))?;
|
||||||
|
|
||||||
|
if content_type != "application/vnd.ms-excel" {
|
||||||
|
return Err(FetchError::bad_content_type(content_type.to_str().unwrap()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let last_modified = DateTime::parse_from_rfc2822(last_modified.to_str().unwrap())
|
||||||
|
.unwrap()
|
||||||
|
.with_timezone(&Utc);
|
||||||
|
|
||||||
|
Ok(if head {
|
||||||
|
FetchOk::head(last_modified, etag)
|
||||||
|
} else {
|
||||||
|
FetchOk::get(
|
||||||
|
last_modified,
|
||||||
|
etag,
|
||||||
|
response.bytes().await.unwrap().to_vec(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn fetch(&self, head: bool) -> FetchResult {
|
||||||
|
if self.url.is_none() {
|
||||||
|
Err(FetchError::NoUrlProvided)
|
||||||
|
} else {
|
||||||
|
Self::fetch_specified(self.url.as_ref().unwrap(), head).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_url(&mut self, url: &str) -> FetchResult {
|
||||||
|
let result = Self::fetch_specified(url, true).await;
|
||||||
|
|
||||||
|
if result.is_ok() {
|
||||||
|
self.url = Some(url.to_string());
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use crate::xls_downloader::{FetchError, XlsDownloader};
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn bad_url() {
|
||||||
|
let url = "bad_url";
|
||||||
|
|
||||||
|
let mut downloader = XlsDownloader::new();
|
||||||
|
assert!(downloader.set_url(url).await.is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn bad_status_code() {
|
||||||
|
let url = "https://www.google.com/not-found";
|
||||||
|
|
||||||
|
let mut downloader = XlsDownloader::new();
|
||||||
|
assert_eq!(
|
||||||
|
downloader.set_url(url).await,
|
||||||
|
Err(FetchError::bad_status_code(404))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn bad_headers() {
|
||||||
|
let url = "https://www.google.com/favicon.ico";
|
||||||
|
|
||||||
|
let mut downloader = XlsDownloader::new();
|
||||||
|
assert_eq!(
|
||||||
|
downloader.set_url(url).await,
|
||||||
|
Err(FetchError::BadHeaders {
|
||||||
|
expected_header: "ETag".to_string(),
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn bad_content_type() {
|
||||||
|
let url = "https://s3.aero-storage.ldragol.ru/679e5d1145a6ad00843ad3f1/67ddb59fd46303008396ac96%2Fexample.txt";
|
||||||
|
|
||||||
|
let mut downloader = XlsDownloader::new();
|
||||||
|
assert!(downloader.set_url(url).await.is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn ok() {
|
||||||
|
let url = "https://s3.aero-storage.ldragol.ru/679e5d1145a6ad00843ad3f1/67ddb5fad46303008396ac97%2Fschedule.xls";
|
||||||
|
|
||||||
|
let mut downloader = XlsDownloader::new();
|
||||||
|
assert!(downloader.set_url(url).await.is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn downloader_ok() {
|
||||||
|
let url = "https://s3.aero-storage.ldragol.ru/679e5d1145a6ad00843ad3f1/67ddb5fad46303008396ac97%2Fschedule.xls";
|
||||||
|
|
||||||
|
let mut downloader = XlsDownloader::new();
|
||||||
|
assert!(downloader.set_url(url).await.is_ok());
|
||||||
|
assert!(downloader.fetch(false).await.is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn downloader_no_url_provided() {
|
||||||
|
let downloader = XlsDownloader::new();
|
||||||
|
|
||||||
|
let result = downloader.fetch(false).await;
|
||||||
|
assert_eq!(result, Err(FetchError::NoUrlProvided));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
use chrono::{DateTime, Utc};
|
|
||||||
use derive_more::{Display, Error};
|
|
||||||
use std::mem::discriminant;
|
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
mod yandex_disk;
|
|
||||||
|
|
||||||
/// XLS data retrieval errors.
|
|
||||||
#[derive(Clone, Debug, Display, Error)]
|
|
||||||
pub enum FetchError {
|
|
||||||
/// Unknown error.
|
|
||||||
#[display("An unknown error occurred while downloading the file.")]
|
|
||||||
Reqwest(Arc<reqwest::Error>),
|
|
||||||
|
|
||||||
/// Server returned a status code different from 200.
|
|
||||||
#[display("Server returned a status code {status_code}.")]
|
|
||||||
BadStatusCode { status_code: u16 },
|
|
||||||
|
|
||||||
/// The folder contains no file matching the schedule name pattern.
|
|
||||||
#[display("No schedule file was found in the shared folder.")]
|
|
||||||
NoScheduleFile,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl FetchError {
|
|
||||||
pub fn unknown(error: Arc<reqwest::Error>) -> Self {
|
|
||||||
Self::Reqwest(error)
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn bad_status_code(status_code: u16) -> Self {
|
|
||||||
Self::BadStatusCode { status_code }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl PartialEq for FetchError {
|
|
||||||
fn eq(&self, other: &Self) -> bool {
|
|
||||||
discriminant(self) == discriminant(other)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub type FetchResult<T> = Result<T, FetchError>;
|
|
||||||
|
|
||||||
/// Description of the remote schedule file, obtained without downloading its content.
|
|
||||||
#[derive(Clone, Debug, PartialEq)]
|
|
||||||
pub struct RemoteFile {
|
|
||||||
/// Permanent link to the file, shown to API clients.
|
|
||||||
pub url: String,
|
|
||||||
|
|
||||||
/// Link the content is actually downloaded from.
|
|
||||||
pub download_url: String,
|
|
||||||
|
|
||||||
/// Content hash, changing whenever the file content changes.
|
|
||||||
pub version: String,
|
|
||||||
|
|
||||||
/// Time of the last file modification reported by the remote side.
|
|
||||||
pub modified_at: DateTime<Utc>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Public Yandex Disk folder the schedule is downloaded from.
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub struct Source {
|
|
||||||
pub public_url: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Source {
|
|
||||||
pub fn new(public_url: String) -> Self {
|
|
||||||
Self { public_url }
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Looks up the current schedule file without downloading its content.
|
|
||||||
pub async fn probe(&self) -> FetchResult<RemoteFile> {
|
|
||||||
yandex_disk::probe(&self.public_url).await
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Downloads the content of a previously probed file.
|
|
||||||
pub async fn download(&self, file: &RemoteFile) -> FetchResult<Vec<u8>> {
|
|
||||||
get(&file.download_url)
|
|
||||||
.await?
|
|
||||||
.bytes()
|
|
||||||
.await
|
|
||||||
.map(|bytes| bytes.to_vec())
|
|
||||||
.map_err(|error| FetchError::unknown(Arc::new(error)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Performs a GET request with a spoofed browser User-Agent and checks the status code.
|
|
||||||
async fn get(url: &str) -> FetchResult<reqwest::Response> {
|
|
||||||
let response = reqwest::Client::new()
|
|
||||||
.get(url)
|
|
||||||
.header("User-Agent", ua_generator::ua::spoof_chrome_ua())
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.map_err(|error| FetchError::unknown(Arc::new(error)))?;
|
|
||||||
|
|
||||||
if response.status().as_u16() != 200 {
|
|
||||||
return Err(FetchError::bad_status_code(response.status().as_u16()));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(response)
|
|
||||||
}
|
|
||||||
@@ -1,135 +0,0 @@
|
|||||||
use super::{FetchError, FetchResult, RemoteFile};
|
|
||||||
use chrono::{DateTime, Utc};
|
|
||||||
use percent_encoding::{AsciiSet, CONTROLS, NON_ALPHANUMERIC, utf8_percent_encode};
|
|
||||||
use serde::Deserialize;
|
|
||||||
|
|
||||||
/// Prefix of the schedule file names in the shared folder.
|
|
||||||
const NAME_PREFIX: &str = "poltavskaja_";
|
|
||||||
|
|
||||||
/// Marker of the corrections file, which holds a separate schedule.
|
|
||||||
const NAME_EXCLUDED_MARKER: &str = "korr";
|
|
||||||
|
|
||||||
/// Extension of the schedule files.
|
|
||||||
const NAME_SUFFIX: &str = ".xls";
|
|
||||||
|
|
||||||
/// Maximum amount of entries requested from the folder listing.
|
|
||||||
const LISTING_LIMIT: u32 = 200;
|
|
||||||
|
|
||||||
/// Characters not allowed inside a single path segment of the public file link.
|
|
||||||
const PATH_SEGMENT: &AsciiSet = &CONTROLS
|
|
||||||
.add(b' ')
|
|
||||||
.add(b'"')
|
|
||||||
.add(b'#')
|
|
||||||
.add(b'%')
|
|
||||||
.add(b'/')
|
|
||||||
.add(b'<')
|
|
||||||
.add(b'>')
|
|
||||||
.add(b'?')
|
|
||||||
.add(b'`')
|
|
||||||
.add(b'{')
|
|
||||||
.add(b'}');
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Listing {
|
|
||||||
#[serde(rename = "_embedded")]
|
|
||||||
embedded: Embedded,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Embedded {
|
|
||||||
items: Vec<Item>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
|
||||||
struct Item {
|
|
||||||
#[serde(rename = "type")]
|
|
||||||
resource_type: String,
|
|
||||||
name: String,
|
|
||||||
modified: DateTime<Utc>,
|
|
||||||
md5: Option<String>,
|
|
||||||
revision: Option<u64>,
|
|
||||||
file: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Item {
|
|
||||||
/// Whether the entry is the schedule the provider is interested in.
|
|
||||||
fn is_schedule(&self) -> bool {
|
|
||||||
if self.resource_type != "file" || self.file.is_none() {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
let name = self.name.to_lowercase();
|
|
||||||
|
|
||||||
name.starts_with(NAME_PREFIX)
|
|
||||||
&& name.ends_with(NAME_SUFFIX)
|
|
||||||
&& !name.contains(NAME_EXCLUDED_MARKER)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Marker changing whenever the file content changes.
|
|
||||||
fn version(&self) -> String {
|
|
||||||
self.md5
|
|
||||||
.clone()
|
|
||||||
.or_else(|| self.revision.map(|revision| revision.to_string()))
|
|
||||||
.unwrap_or_else(|| self.modified.to_rfc3339())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Finds the freshest schedule file in the public folder.
|
|
||||||
///
|
|
||||||
/// The files inside the folder are replaced independently of the folder link,
|
|
||||||
/// so the whole listing is re-read on every probe.
|
|
||||||
pub async fn probe(public_url: &str) -> FetchResult<RemoteFile> {
|
|
||||||
let listing = super::get(&format!(
|
|
||||||
"https://cloud-api.yandex.net/v1/disk/public/resources?public_key={}&limit={}",
|
|
||||||
utf8_percent_encode(public_url, NON_ALPHANUMERIC),
|
|
||||||
LISTING_LIMIT
|
|
||||||
))
|
|
||||||
.await?
|
|
||||||
.json::<Listing>()
|
|
||||||
.await
|
|
||||||
.map_err(|error| FetchError::unknown(std::sync::Arc::new(error)))?;
|
|
||||||
|
|
||||||
let item = listing
|
|
||||||
.embedded
|
|
||||||
.items
|
|
||||||
.into_iter()
|
|
||||||
.filter(Item::is_schedule)
|
|
||||||
.max_by_key(|item| (item.modified, item.revision))
|
|
||||||
.ok_or(FetchError::NoScheduleFile)?;
|
|
||||||
|
|
||||||
Ok(RemoteFile {
|
|
||||||
url: format!(
|
|
||||||
"{}/{}",
|
|
||||||
public_url.trim_end_matches('/'),
|
|
||||||
utf8_percent_encode(&item.name, PATH_SEGMENT)
|
|
||||||
),
|
|
||||||
version: item.version(),
|
|
||||||
modified_at: item.modified,
|
|
||||||
download_url: item.file.unwrap(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::probe;
|
|
||||||
|
|
||||||
const PUBLIC_URL: &str = "https://disk.yandex.ru/d/e8HJpMgDq7msyg";
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn probe_ok() {
|
|
||||||
let file = probe(PUBLIC_URL).await.unwrap();
|
|
||||||
|
|
||||||
assert!(file.url.starts_with(PUBLIC_URL));
|
|
||||||
assert!(!file.version.is_empty());
|
|
||||||
assert!(file.download_url.starts_with("https://"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[tokio::test]
|
|
||||||
async fn probe_unknown_folder() {
|
|
||||||
assert!(
|
|
||||||
probe("https://disk.yandex.ru/d/000000000000000")
|
|
||||||
.await
|
|
||||||
.is_err()
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,12 +1,12 @@
|
|||||||
use crate::extractors::base::FromRequestAsync;
|
use crate::extractors::base::FromRequestAsync;
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
use crate::utility::req_auth;
|
use crate::utility::jwt;
|
||||||
use crate::utility::req_auth::get_claims_from_req;
|
|
||||||
use actix_macros::MiddlewareError;
|
use actix_macros::MiddlewareError;
|
||||||
use actix_web::body::BoxBody;
|
use actix_web::body::BoxBody;
|
||||||
use actix_web::dev::Payload;
|
use actix_web::dev::Payload;
|
||||||
|
use actix_web::http::header;
|
||||||
use actix_web::{web, HttpRequest};
|
use actix_web::{web, HttpRequest};
|
||||||
use database::entity::{User, UserType};
|
use database::entity::User;
|
||||||
use database::query::Query;
|
use database::query::Query;
|
||||||
use derive_more::Display;
|
use derive_more::Display;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -28,53 +28,80 @@ pub enum Error {
|
|||||||
#[display("Invalid or expired access token")]
|
#[display("Invalid or expired access token")]
|
||||||
InvalidAccessToken,
|
InvalidAccessToken,
|
||||||
|
|
||||||
/// Default user is required.
|
|
||||||
#[display("Non-default user type is owning this access token")]
|
|
||||||
#[status_code = "actix_web::http::StatusCode::FORBIDDEN"]
|
|
||||||
NonDefaultUserType,
|
|
||||||
|
|
||||||
/// The user bound to the token is not found in the database.
|
/// The user bound to the token is not found in the database.
|
||||||
#[display("No user associated with access token")]
|
#[display("No user associated with access token")]
|
||||||
NoUser,
|
NoUser,
|
||||||
|
|
||||||
/// User doesn't have required role.
|
|
||||||
#[display("You don't have sufficient rights")]
|
|
||||||
#[status_code = "actix_web::http::StatusCode::FORBIDDEN"]
|
|
||||||
InsufficientRights,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl From<req_auth::Error> for Error {
|
impl Error {
|
||||||
fn from(value: req_auth::Error) -> Self {
|
pub fn into_err(self) -> actix_web::Error {
|
||||||
match value {
|
actix_web::Error::from(self)
|
||||||
req_auth::Error::NoHeaderOrCookieFound => Error::NoHeaderOrCookieFound,
|
|
||||||
req_auth::Error::UnknownAuthorizationType => Error::UnknownAuthorizationType,
|
|
||||||
req_auth::Error::InvalidAccessToken => Error::InvalidAccessToken,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_access_token_from_header(req: &HttpRequest) -> Result<String, Error> {
|
||||||
|
let header_value = req
|
||||||
|
.headers()
|
||||||
|
.get(header::AUTHORIZATION)
|
||||||
|
.ok_or(Error::NoHeaderOrCookieFound)?
|
||||||
|
.to_str()
|
||||||
|
.map_err(|_| Error::NoHeaderOrCookieFound)?
|
||||||
|
.to_string();
|
||||||
|
|
||||||
|
let parts = header_value
|
||||||
|
.split_once(' ')
|
||||||
|
.ok_or(Error::UnknownAuthorizationType)?;
|
||||||
|
|
||||||
|
if parts.0 != "Bearer" {
|
||||||
|
Err(Error::UnknownAuthorizationType)
|
||||||
|
} else {
|
||||||
|
Ok(parts.1.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_access_token_from_cookies(req: &HttpRequest) -> Result<String, Error> {
|
||||||
|
let cookie = req
|
||||||
|
.cookie("access_token")
|
||||||
|
.ok_or(Error::NoHeaderOrCookieFound)?;
|
||||||
|
|
||||||
|
Ok(cookie.value().to_string())
|
||||||
|
}
|
||||||
|
|
||||||
/// User extractor from request with Bearer access token.
|
/// User extractor from request with Bearer access token.
|
||||||
impl FromRequestAsync for User {
|
impl FromRequestAsync for User {
|
||||||
type Error = Error;
|
type Error = actix_web::Error;
|
||||||
|
|
||||||
async fn from_request_async(
|
async fn from_request_async(
|
||||||
req: &HttpRequest,
|
req: &HttpRequest,
|
||||||
_payload: &mut Payload,
|
_payload: &mut Payload,
|
||||||
) -> Result<Self, Self::Error> {
|
) -> Result<Self, Self::Error> {
|
||||||
let claims = get_claims_from_req(req).map_err(Error::from)?;
|
let access_token = match get_access_token_from_header(req) {
|
||||||
|
Err(Error::NoHeaderOrCookieFound) => {
|
||||||
|
get_access_token_from_cookies(req).map_err(|error| error.into_err())?
|
||||||
|
}
|
||||||
|
Err(error) => {
|
||||||
|
return Err(error.into_err());
|
||||||
|
}
|
||||||
|
Ok(access_token) => access_token,
|
||||||
|
};
|
||||||
|
|
||||||
if claims.user_type.unwrap_or(UserType::Default) != UserType::Default {
|
let user_id = jwt::verify_and_decode(&access_token)
|
||||||
return Err(Error::NonDefaultUserType);
|
.map_err(|_| Error::InvalidAccessToken.into_err())?;
|
||||||
}
|
|
||||||
|
|
||||||
let db = req
|
let db = req
|
||||||
.app_data::<web::Data<AppState>>()
|
.app_data::<web::Data<AppState>>()
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.get_database();
|
.get_database();
|
||||||
|
|
||||||
match Query::find_user_by_id(db, &claims.id).await {
|
Query::find_user_by_id(db, &user_id)
|
||||||
Ok(Some(user)) => Ok(user),
|
.await
|
||||||
_ => Err(Error::NoUser),
|
.map_err(|_| Error::NoUser.into())
|
||||||
}
|
.and_then(|user| {
|
||||||
|
if let Some(user) = user {
|
||||||
|
Ok(user)
|
||||||
|
} else {
|
||||||
|
Err(actix_web::Error::from(Error::NoUser))
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+16
-70
@@ -1,14 +1,13 @@
|
|||||||
use crate::middlewares::authorization::{JWTAuthorizationBuilder, ServiceConfig};
|
use crate::middlewares::authorization::JWTAuthorization;
|
||||||
use crate::middlewares::content_type::ContentTypeBootstrap;
|
use crate::middlewares::content_type::ContentTypeBootstrap;
|
||||||
use crate::state::{AppState, new_app_state};
|
use crate::state::{new_app_state, AppState};
|
||||||
use actix_web::dev::{ServiceFactory, ServiceRequest};
|
use actix_web::dev::{ServiceFactory, ServiceRequest};
|
||||||
use actix_web::{App, Error, HttpServer};
|
use actix_web::{App, Error, HttpServer};
|
||||||
use database::entity::sea_orm_active_enums::UserRole;
|
|
||||||
use dotenvy::dotenv;
|
use dotenvy::dotenv;
|
||||||
use log::info;
|
use log::info;
|
||||||
use std::io;
|
use std::io;
|
||||||
use utoipa_actix_web::AppExt;
|
|
||||||
use utoipa_actix_web::scope::Scope;
|
use utoipa_actix_web::scope::Scope;
|
||||||
|
use utoipa_actix_web::AppExt;
|
||||||
use utoipa_rapidoc::RapiDoc;
|
use utoipa_rapidoc::RapiDoc;
|
||||||
|
|
||||||
mod state;
|
mod state;
|
||||||
@@ -27,22 +26,6 @@ pub fn get_api_scope<
|
|||||||
>(
|
>(
|
||||||
scope: I,
|
scope: I,
|
||||||
) -> Scope<T> {
|
) -> Scope<T> {
|
||||||
let admin_scope = {
|
|
||||||
let service_user_scope =
|
|
||||||
utoipa_actix_web::scope("/service-users").service(routes::admin::service_users::create);
|
|
||||||
|
|
||||||
utoipa_actix_web::scope("/admin")
|
|
||||||
.wrap(
|
|
||||||
JWTAuthorizationBuilder::new()
|
|
||||||
.with_default(Some(ServiceConfig {
|
|
||||||
allow_service: false,
|
|
||||||
user_roles: Some(&[UserRole::Admin]),
|
|
||||||
}))
|
|
||||||
.build(),
|
|
||||||
)
|
|
||||||
.service(service_user_scope)
|
|
||||||
};
|
|
||||||
|
|
||||||
let auth_scope = utoipa_actix_web::scope("/auth")
|
let auth_scope = utoipa_actix_web::scope("/auth")
|
||||||
.service(routes::auth::sign_in)
|
.service(routes::auth::sign_in)
|
||||||
.service(routes::auth::sign_in_vk)
|
.service(routes::auth::sign_in_vk)
|
||||||
@@ -50,64 +33,26 @@ pub fn get_api_scope<
|
|||||||
.service(routes::auth::sign_up_vk);
|
.service(routes::auth::sign_up_vk);
|
||||||
|
|
||||||
let users_scope = utoipa_actix_web::scope("/users")
|
let users_scope = utoipa_actix_web::scope("/users")
|
||||||
.wrap(
|
.wrap(JWTAuthorization::default())
|
||||||
JWTAuthorizationBuilder::new()
|
|
||||||
.add_paths(
|
|
||||||
["/by/id/{id}", "/by/telegram-id/{id}"],
|
|
||||||
Some(ServiceConfig {
|
|
||||||
allow_service: true,
|
|
||||||
user_roles: Some(&[UserRole::Admin]),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.build(),
|
|
||||||
)
|
|
||||||
.service(
|
|
||||||
utoipa_actix_web::scope("/by")
|
|
||||||
.service(routes::users::by::by_id)
|
|
||||||
.service(routes::users::by::by_telegram_id),
|
|
||||||
)
|
|
||||||
.service(routes::users::change_group)
|
.service(routes::users::change_group)
|
||||||
.service(routes::users::change_username)
|
.service(routes::users::change_username)
|
||||||
.service(routes::users::me);
|
.service(routes::users::me);
|
||||||
|
|
||||||
let schedule_scope = utoipa_actix_web::scope("/schedule")
|
let schedule_scope = utoipa_actix_web::scope("/schedule")
|
||||||
.wrap(
|
.wrap(JWTAuthorization {
|
||||||
JWTAuthorizationBuilder::new()
|
ignore: &["/group-names", "/teacher-names"],
|
||||||
.with_default(Some(ServiceConfig {
|
})
|
||||||
allow_service: true,
|
|
||||||
user_roles: None,
|
|
||||||
}))
|
|
||||||
.add_paths(["/group-names", "/teacher-names"], None)
|
|
||||||
.add_paths(
|
|
||||||
["/"],
|
|
||||||
Some(ServiceConfig {
|
|
||||||
allow_service: true,
|
|
||||||
user_roles: Some(&[UserRole::Admin]),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.add_paths(
|
|
||||||
["/group"],
|
|
||||||
Some(ServiceConfig {
|
|
||||||
allow_service: false,
|
|
||||||
user_roles: None,
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
.build(),
|
|
||||||
)
|
|
||||||
.service(routes::schedule::cache_status)
|
|
||||||
.service(routes::schedule::schedule)
|
.service(routes::schedule::schedule)
|
||||||
|
.service(routes::schedule::cache_status)
|
||||||
.service(routes::schedule::group)
|
.service(routes::schedule::group)
|
||||||
.service(routes::schedule::group_by_name)
|
|
||||||
.service(routes::schedule::group_names)
|
.service(routes::schedule::group_names)
|
||||||
.service(routes::schedule::teacher)
|
.service(routes::schedule::teacher)
|
||||||
.service(routes::schedule::teacher_names);
|
.service(routes::schedule::teacher_names);
|
||||||
|
|
||||||
let flow_scope = utoipa_actix_web::scope("/flow")
|
let flow_scope = utoipa_actix_web::scope("/flow")
|
||||||
.wrap(
|
.wrap(JWTAuthorization {
|
||||||
JWTAuthorizationBuilder::new()
|
ignore: &["/telegram-auth"],
|
||||||
.add_paths(["/telegram-auth"], None)
|
})
|
||||||
.build(),
|
|
||||||
)
|
|
||||||
.service(routes::flow::telegram_auth)
|
.service(routes::flow::telegram_auth)
|
||||||
.service(routes::flow::telegram_complete);
|
.service(routes::flow::telegram_complete);
|
||||||
|
|
||||||
@@ -115,7 +60,6 @@ pub fn get_api_scope<
|
|||||||
.service(routes::vk_id::oauth);
|
.service(routes::vk_id::oauth);
|
||||||
|
|
||||||
utoipa_actix_web::scope(scope)
|
utoipa_actix_web::scope(scope)
|
||||||
.service(admin_scope)
|
|
||||||
.service(auth_scope)
|
.service(auth_scope)
|
||||||
.service(users_scope)
|
.service(users_scope)
|
||||||
.service(schedule_scope)
|
.service(schedule_scope)
|
||||||
@@ -158,9 +102,11 @@ async fn async_main() -> io::Result<()> {
|
|||||||
fn main() -> io::Result<()> {
|
fn main() -> io::Result<()> {
|
||||||
let _guard = sentry::init((
|
let _guard = sentry::init((
|
||||||
"https://9c33db76e89984b3f009b28a9f4b5954@sentry.n08i40k.ru/8",
|
"https://9c33db76e89984b3f009b28a9f4b5954@sentry.n08i40k.ru/8",
|
||||||
sentry::ClientOptions::new()
|
sentry::ClientOptions {
|
||||||
.maybe_release(sentry::release_name!())
|
release: sentry::release_name!(),
|
||||||
.send_default_pii(true),
|
send_default_pii: true,
|
||||||
|
..Default::default()
|
||||||
|
},
|
||||||
));
|
));
|
||||||
|
|
||||||
let _ = dotenv();
|
let _ = dotenv();
|
||||||
|
|||||||
@@ -1,68 +1,18 @@
|
|||||||
use crate::extractors::authorized_user;
|
use crate::extractors::authorized_user;
|
||||||
use crate::state::AppState;
|
use crate::extractors::base::FromRequestAsync;
|
||||||
use crate::utility::req_auth::get_claims_from_req;
|
|
||||||
use actix_web::body::{BoxBody, EitherBody};
|
use actix_web::body::{BoxBody, EitherBody};
|
||||||
use actix_web::dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform};
|
use actix_web::dev::{forward_ready, Payload, Service, ServiceRequest, ServiceResponse, Transform};
|
||||||
use actix_web::{web, Error, HttpRequest, ResponseError};
|
use actix_web::{Error, HttpRequest, ResponseError};
|
||||||
use database::entity::sea_orm_active_enums::UserRole;
|
use database::entity::User;
|
||||||
use database::entity::UserType;
|
|
||||||
use database::query::Query;
|
|
||||||
use futures_util::future::LocalBoxFuture;
|
use futures_util::future::LocalBoxFuture;
|
||||||
use std::future::{ready, Ready};
|
use std::future::{ready, Ready};
|
||||||
use std::ops::Deref;
|
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
use std::sync::Arc;
|
|
||||||
|
|
||||||
#[derive(Default, Clone)]
|
|
||||||
pub struct ServiceConfig {
|
|
||||||
/// Allow service users to access endpoints.
|
|
||||||
pub allow_service: bool,
|
|
||||||
|
|
||||||
/// List of required roles to access endpoints.
|
|
||||||
pub user_roles: Option<&'static [UserRole]>,
|
|
||||||
}
|
|
||||||
|
|
||||||
type ServiceKV = (Arc<[&'static str]>, Option<ServiceConfig>);
|
|
||||||
|
|
||||||
pub struct JWTAuthorizationBuilder {
|
|
||||||
pub default_config: Option<ServiceConfig>,
|
|
||||||
pub path_configs: Vec<ServiceKV>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl JWTAuthorizationBuilder {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
JWTAuthorizationBuilder {
|
|
||||||
default_config: Some(ServiceConfig::default()),
|
|
||||||
path_configs: vec![],
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn with_default(mut self, default: Option<ServiceConfig>) -> Self {
|
|
||||||
self.default_config = default;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn add_paths(
|
|
||||||
mut self,
|
|
||||||
paths: impl AsRef<[&'static str]>,
|
|
||||||
config: Option<ServiceConfig>,
|
|
||||||
) -> Self {
|
|
||||||
self.path_configs.push((Arc::from(paths.as_ref()), config));
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn build(self) -> JWTAuthorization {
|
|
||||||
JWTAuthorization {
|
|
||||||
default_config: Arc::new(self.default_config),
|
|
||||||
path_configs: Arc::from(self.path_configs),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Middleware guard working with JWT tokens.
|
/// Middleware guard working with JWT tokens.
|
||||||
|
#[derive(Default)]
|
||||||
pub struct JWTAuthorization {
|
pub struct JWTAuthorization {
|
||||||
pub default_config: Arc<Option<ServiceConfig>>,
|
/// List of ignored endpoints.
|
||||||
pub path_configs: Arc<[ServiceKV]>,
|
pub ignore: &'static [&'static str],
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, B> Transform<S, ServiceRequest> for JWTAuthorization
|
impl<S, B> Transform<S, ServiceRequest> for JWTAuthorization
|
||||||
@@ -80,17 +30,15 @@ where
|
|||||||
fn new_transform(&self, service: S) -> Self::Future {
|
fn new_transform(&self, service: S) -> Self::Future {
|
||||||
ready(Ok(JWTAuthorizationMiddleware {
|
ready(Ok(JWTAuthorizationMiddleware {
|
||||||
service: Rc::new(service),
|
service: Rc::new(service),
|
||||||
default_config: self.default_config.clone(),
|
ignore: self.ignore,
|
||||||
path_configs: self.path_configs.clone(),
|
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct JWTAuthorizationMiddleware<S> {
|
pub struct JWTAuthorizationMiddleware<S> {
|
||||||
service: Rc<S>,
|
service: Rc<S>,
|
||||||
|
/// List of ignored endpoints.
|
||||||
default_config: Arc<Option<ServiceConfig>>,
|
ignore: &'static [&'static str],
|
||||||
path_configs: Arc<[ServiceKV]>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, B> JWTAuthorizationMiddleware<S>
|
impl<S, B> JWTAuthorizationMiddleware<S>
|
||||||
@@ -100,68 +48,29 @@ where
|
|||||||
B: 'static,
|
B: 'static,
|
||||||
{
|
{
|
||||||
/// Checking the validity of the token.
|
/// Checking the validity of the token.
|
||||||
async fn check_authorization(
|
async fn check_authorization(req: &HttpRequest) -> Result<(), authorized_user::Error> {
|
||||||
req: &HttpRequest,
|
let mut payload = Payload::None;
|
||||||
allow_service_user: bool,
|
|
||||||
required_user_roles: Option<&'static [UserRole]>,
|
|
||||||
) -> Result<(), authorized_user::Error> {
|
|
||||||
let claims = get_claims_from_req(req).map_err(authorized_user::Error::from)?;
|
|
||||||
|
|
||||||
let db = req
|
User::from_request_async(req, &mut payload)
|
||||||
.app_data::<web::Data<AppState>>()
|
.await
|
||||||
.unwrap()
|
.map(|_| ())
|
||||||
.get_database();
|
.map_err(|e| e.as_error::<authorized_user::Error>().unwrap().clone())
|
||||||
|
|
||||||
let user_type = claims.user_type.unwrap_or(UserType::Default);
|
|
||||||
|
|
||||||
match user_type {
|
|
||||||
UserType::Default => {
|
|
||||||
if let Some(required_user_roles) = required_user_roles {
|
|
||||||
let Ok(Some(user)) = Query::find_user_by_id(db, &claims.id).await else {
|
|
||||||
return Err(authorized_user::Error::NoUser);
|
|
||||||
};
|
|
||||||
|
|
||||||
if !required_user_roles.contains(&user.role) {
|
|
||||||
return Err(authorized_user::Error::InsufficientRights);
|
|
||||||
}
|
|
||||||
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
match Query::is_user_exists_by_id(db, &claims.id).await {
|
|
||||||
Ok(true) => Ok(()),
|
|
||||||
_ => Err(authorized_user::Error::NoUser),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
UserType::Service => {
|
|
||||||
if !allow_service_user {
|
|
||||||
return Err(authorized_user::Error::NonDefaultUserType);
|
|
||||||
}
|
|
||||||
|
|
||||||
match Query::is_service_user_exists_by_id(db, &claims.id).await {
|
|
||||||
Ok(true) => Ok(()),
|
|
||||||
_ => Err(authorized_user::Error::NoUser),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn find_config(
|
fn should_skip(&self, req: &ServiceRequest) -> bool {
|
||||||
current_path: &str,
|
let path = req.match_info().unprocessed();
|
||||||
per_route: &[ServiceKV],
|
|
||||||
default: &Option<ServiceConfig>,
|
|
||||||
) -> Option<ServiceConfig> {
|
|
||||||
for (service_paths, config) in per_route {
|
|
||||||
for service_path in service_paths.deref() {
|
|
||||||
if !service_path.eq(¤t_path) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
return config.clone();
|
self.ignore.iter().any(|ignore| {
|
||||||
|
if !path.starts_with(ignore) {
|
||||||
|
return false;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
default.clone()
|
if let Some(other) = path.as_bytes().get(ignore.len()) {
|
||||||
|
return [b'?', b'/'].contains(other);
|
||||||
|
}
|
||||||
|
|
||||||
|
true
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,33 +87,15 @@ where
|
|||||||
forward_ready!(service);
|
forward_ready!(service);
|
||||||
|
|
||||||
fn call(&self, req: ServiceRequest) -> Self::Future {
|
fn call(&self, req: ServiceRequest) -> Self::Future {
|
||||||
let service = Rc::clone(&self.service);
|
if self.should_skip(&req) {
|
||||||
|
|
||||||
let match_info = req.match_info();
|
|
||||||
let path = if let Some(pattern) = req.match_pattern() {
|
|
||||||
let scope_start_idx = match_info
|
|
||||||
.as_str()
|
|
||||||
.find(match_info.unprocessed())
|
|
||||||
.unwrap_or(0);
|
|
||||||
|
|
||||||
pattern.as_str().split_at(scope_start_idx).1.to_owned()
|
|
||||||
} else {
|
|
||||||
match_info.unprocessed().to_owned()
|
|
||||||
};
|
|
||||||
|
|
||||||
let Some(config) = Self::find_config(&path, &self.path_configs, &self.default_config)
|
|
||||||
else {
|
|
||||||
let fut = self.service.call(req);
|
let fut = self.service.call(req);
|
||||||
return Box::pin(async move { Ok(fut.await?.map_into_left_body()) });
|
return Box::pin(async move { Ok(fut.await?.map_into_left_body()) });
|
||||||
};
|
}
|
||||||
|
|
||||||
let allow_service_user = config.allow_service;
|
let service = Rc::clone(&self.service);
|
||||||
let required_user_roles = config.user_roles;
|
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
match Self::check_authorization(req.request(), allow_service_user, required_user_roles)
|
match Self::check_authorization(req.request()).await {
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
let fut = service.call(req).await?;
|
let fut = service.call(req).await?;
|
||||||
Ok(fut.map_into_left_body())
|
Ok(fut.map_into_left_body())
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
pub mod service_users;
|
|
||||||
@@ -1,75 +0,0 @@
|
|||||||
use self::schema::*;
|
|
||||||
use crate::{utility, AppState};
|
|
||||||
use actix_web::{post, web};
|
|
||||||
use database::entity::{ActiveServiceUser, UserType};
|
|
||||||
use database::query::Query;
|
|
||||||
use database::sea_orm::{ActiveModelTrait, Set};
|
|
||||||
use objectid::ObjectId;
|
|
||||||
use web::Json;
|
|
||||||
|
|
||||||
#[utoipa::path(responses(
|
|
||||||
(status = OK, body = Response),
|
|
||||||
))]
|
|
||||||
#[post("/create")]
|
|
||||||
pub async fn create(data_json: Json<Request>, app_state: web::Data<AppState>) -> ServiceResponse {
|
|
||||||
let service_user =
|
|
||||||
match Query::find_service_user_by_id(app_state.get_database(), &data_json.name)
|
|
||||||
.await
|
|
||||||
.expect("Failed to find service user by name")
|
|
||||||
{
|
|
||||||
Some(_) => return Err(ErrorCode::AlreadyExists).into(),
|
|
||||||
None => {
|
|
||||||
let new_user = ActiveServiceUser {
|
|
||||||
id: Set(ObjectId::new().unwrap().to_string()),
|
|
||||||
name: Set(data_json.name.clone()),
|
|
||||||
};
|
|
||||||
|
|
||||||
new_user
|
|
||||||
.insert(app_state.get_database())
|
|
||||||
.await
|
|
||||||
.expect("Failed to insert service user")
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
let access_token = utility::jwt::encode(UserType::Service, &service_user.id);
|
|
||||||
Ok(Response::new(access_token)).into()
|
|
||||||
}
|
|
||||||
|
|
||||||
mod schema {
|
|
||||||
use actix_macros::{ErrResponse, OkResponse};
|
|
||||||
use derive_more::Display;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use utoipa::ToSchema;
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize, ToSchema)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
#[schema(as = ServiceUser::Create::Request)]
|
|
||||||
pub struct Request {
|
|
||||||
/// Service username.
|
|
||||||
pub name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Serialize, ToSchema, OkResponse)]
|
|
||||||
#[serde(rename_all = "camelCase")]
|
|
||||||
#[schema(as = ServiceUser::Create::Response)]
|
|
||||||
pub struct Response {
|
|
||||||
access_token: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Response {
|
|
||||||
pub fn new(access_token: String) -> Self {
|
|
||||||
Self { access_token }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub type ServiceResponse = crate::routes::schema::Response<Response, ErrorCode>;
|
|
||||||
|
|
||||||
#[derive(Clone, ToSchema, Display, ErrResponse, Serialize)]
|
|
||||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
|
||||||
#[status_code = "actix_web::http::StatusCode::UNAUTHORIZED"]
|
|
||||||
#[schema(as = ServiceUser::Create::ErrorCode)]
|
|
||||||
pub enum ErrorCode {
|
|
||||||
#[display("Service user with that name already exists.")]
|
|
||||||
AlreadyExists,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
mod create;
|
|
||||||
|
|
||||||
pub use create::*;
|
|
||||||
@@ -7,7 +7,6 @@ use crate::{utility, AppState};
|
|||||||
use actix_web::{post, web};
|
use actix_web::{post, web};
|
||||||
use database::query::Query;
|
use database::query::Query;
|
||||||
use web::Json;
|
use web::Json;
|
||||||
use database::entity::UserType;
|
|
||||||
|
|
||||||
async fn sign_in_combined(
|
async fn sign_in_combined(
|
||||||
data: SignInData,
|
data: SignInData,
|
||||||
@@ -41,7 +40,7 @@ async fn sign_in_combined(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let access_token = utility::jwt::encode(UserType::Default, &user.id);
|
let access_token = utility::jwt::encode(&user.id);
|
||||||
Ok(UserResponse::from_user_with_token(user, access_token))
|
Ok(UserResponse::from_user_with_token(user, access_token))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -146,8 +145,8 @@ mod tests {
|
|||||||
use actix_web::http::StatusCode;
|
use actix_web::http::StatusCode;
|
||||||
use actix_web::test;
|
use actix_web::test;
|
||||||
use database::entity::sea_orm_active_enums::UserRole;
|
use database::entity::sea_orm_active_enums::UserRole;
|
||||||
use database::entity::{ActiveUser, UserEntity};
|
use database::entity::ActiveUser;
|
||||||
use database::sea_orm::{ActiveModelTrait, EntityTrait, Set};
|
use database::sea_orm::{ActiveModelTrait, Set};
|
||||||
use sha1::{Digest, Sha1};
|
use sha1::{Digest, Sha1};
|
||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
|
|
||||||
@@ -185,7 +184,9 @@ mod tests {
|
|||||||
let active_user = ActiveUser {
|
let active_user = ActiveUser {
|
||||||
id: Set(id.clone()),
|
id: Set(id.clone()),
|
||||||
username: Set(username),
|
username: Set(username),
|
||||||
password: Set(Some(bcrypt::hash("example", bcrypt::DEFAULT_COST).unwrap())),
|
password: Set(Some(
|
||||||
|
bcrypt::hash("example", bcrypt::DEFAULT_COST).unwrap(),
|
||||||
|
)),
|
||||||
vk_id: Set(None),
|
vk_id: Set(None),
|
||||||
telegram_id: Set(None),
|
telegram_id: Set(None),
|
||||||
group: Set(Some("ИС-214/23".to_string())),
|
group: Set(Some("ИС-214/23".to_string())),
|
||||||
@@ -193,13 +194,8 @@ mod tests {
|
|||||||
android_version: Set(None),
|
android_version: Set(None),
|
||||||
};
|
};
|
||||||
|
|
||||||
UserEntity::delete_by_id(&id)
|
|
||||||
.exec(app_state.get_database())
|
|
||||||
.await
|
|
||||||
.expect("Failed to delete user");
|
|
||||||
|
|
||||||
active_user
|
active_user
|
||||||
.insert(app_state.get_database())
|
.save(app_state.get_database())
|
||||||
.await
|
.await
|
||||||
.expect("Failed to save user");
|
.expect("Failed to save user");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use crate::routes::schema::ResponseError;
|
|||||||
use crate::{utility, AppState};
|
use crate::{utility, AppState};
|
||||||
use actix_web::{post, web};
|
use actix_web::{post, web};
|
||||||
use database::entity::sea_orm_active_enums::UserRole;
|
use database::entity::sea_orm_active_enums::UserRole;
|
||||||
use database::entity::{ActiveUser, UserType};
|
use database::entity::ActiveUser;
|
||||||
use database::query::Query;
|
use database::query::Query;
|
||||||
use database::sea_orm::ActiveModelTrait;
|
use database::sea_orm::ActiveModelTrait;
|
||||||
use web::Json;
|
use web::Json;
|
||||||
@@ -51,7 +51,7 @@ async fn sign_up_combined(
|
|||||||
|
|
||||||
let active_user: ActiveUser = data.into();
|
let active_user: ActiveUser = data.into();
|
||||||
let user = active_user.insert(db).await.unwrap();
|
let user = active_user.insert(db).await.unwrap();
|
||||||
let access_token = utility::jwt::encode(UserType::Default, &user.id);
|
let access_token = utility::jwt::encode(&user.id);
|
||||||
|
|
||||||
Ok(UserResponse::from_user_with_token(user, access_token))
|
Ok(UserResponse::from_user_with_token(user, access_token))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ use crate::{utility, AppState};
|
|||||||
use actix_web::{post, web};
|
use actix_web::{post, web};
|
||||||
use chrono::{DateTime, Duration, Utc};
|
use chrono::{DateTime, Duration, Utc};
|
||||||
use database::entity::sea_orm_active_enums::UserRole;
|
use database::entity::sea_orm_active_enums::UserRole;
|
||||||
use database::entity::{ActiveUser, UserType};
|
use database::entity::ActiveUser;
|
||||||
use database::query::Query;
|
use database::query::Query;
|
||||||
use database::sea_orm::{ActiveModelTrait, Set};
|
use database::sea_orm::{ActiveModelTrait, Set};
|
||||||
use objectid::ObjectId;
|
use objectid::ObjectId;
|
||||||
@@ -73,7 +73,7 @@ pub async fn telegram_auth(
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let access_token = utility::jwt::encode(UserType::Default, &user.id);
|
let access_token = utility::jwt::encode(&user.id);
|
||||||
Ok(Response::new(&access_token, user.group.is_some())).into()
|
Ok(Response::new(&access_token, user.group.is_some())).into()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -58,7 +58,10 @@ pub async fn telegram_complete(
|
|||||||
|
|
||||||
active_user.group = Set(Some(data.group));
|
active_user.group = Set(Some(data.group));
|
||||||
|
|
||||||
active_user.update(db).await.expect("Failed to update user");
|
active_user
|
||||||
|
.update(db)
|
||||||
|
.await
|
||||||
|
.expect("Failed to update user");
|
||||||
|
|
||||||
Ok(()).into()
|
Ok(()).into()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
pub mod admin;
|
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod flow;
|
pub mod flow;
|
||||||
pub mod schedule;
|
pub mod schedule;
|
||||||
|
|||||||
@@ -1,65 +0,0 @@
|
|||||||
use self::schema::*;
|
|
||||||
use crate::routes::schedule::schema::ScheduleEntryResponse;
|
|
||||||
use crate::routes::schema::ResponseError;
|
|
||||||
use crate::AppState;
|
|
||||||
use actix_web::{get, web};
|
|
||||||
|
|
||||||
#[utoipa::path(responses(
|
|
||||||
(status = OK, body = ScheduleEntryResponse),
|
|
||||||
(
|
|
||||||
status = SERVICE_UNAVAILABLE,
|
|
||||||
body = ResponseError<ErrorCode>,
|
|
||||||
example = json!({
|
|
||||||
"code": "NO_SCHEDULE",
|
|
||||||
"message": "Schedule not parsed yet."
|
|
||||||
})
|
|
||||||
),
|
|
||||||
(
|
|
||||||
status = NOT_FOUND,
|
|
||||||
body = ResponseError<ErrorCode>,
|
|
||||||
example = json!({
|
|
||||||
"code": "NOT_FOUND",
|
|
||||||
"message": "Required group not found."
|
|
||||||
})
|
|
||||||
),
|
|
||||||
))]
|
|
||||||
#[get("/group/{group_name}")]
|
|
||||||
pub async fn group_by_name(
|
|
||||||
path: web::Path<String>,
|
|
||||||
app_state: web::Data<AppState>,
|
|
||||||
) -> ServiceResponse {
|
|
||||||
let group_name = path.into_inner();
|
|
||||||
|
|
||||||
match app_state
|
|
||||||
.get_schedule_snapshot("eng_polytechnic")
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.data
|
|
||||||
.groups
|
|
||||||
.get(&group_name)
|
|
||||||
{
|
|
||||||
None => Err(ErrorCode::NotFound),
|
|
||||||
Some(entry) => Ok(entry.clone().into()),
|
|
||||||
}
|
|
||||||
.into()
|
|
||||||
}
|
|
||||||
|
|
||||||
mod schema {
|
|
||||||
use crate::routes::schedule::schema::ScheduleEntryResponse;
|
|
||||||
use actix_macros::ErrResponse;
|
|
||||||
use derive_more::Display;
|
|
||||||
use serde::Serialize;
|
|
||||||
use utoipa::ToSchema;
|
|
||||||
|
|
||||||
pub type ServiceResponse = crate::routes::schema::Response<ScheduleEntryResponse, ErrorCode>;
|
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Display, ToSchema, ErrResponse)]
|
|
||||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
|
||||||
#[schema(as = GroupByNameSchedule::ErrorCode)]
|
|
||||||
pub enum ErrorCode {
|
|
||||||
/// Group not found.
|
|
||||||
#[status_code = "actix_web::http::StatusCode::NOT_FOUND"]
|
|
||||||
#[display("Required group not found.")]
|
|
||||||
NotFound,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,5 @@
|
|||||||
mod cache_status;
|
mod cache_status;
|
||||||
mod group;
|
mod group;
|
||||||
mod group_by_name;
|
|
||||||
mod group_names;
|
mod group_names;
|
||||||
mod get;
|
mod get;
|
||||||
mod schema;
|
mod schema;
|
||||||
@@ -9,7 +8,6 @@ mod teacher_names;
|
|||||||
|
|
||||||
pub use cache_status::*;
|
pub use cache_status::*;
|
||||||
pub use group::*;
|
pub use group::*;
|
||||||
pub use group_by_name::*;
|
|
||||||
pub use group_names::*;
|
pub use group_names::*;
|
||||||
pub use get::*;
|
pub use get::*;
|
||||||
pub use teacher::*;
|
pub use teacher::*;
|
||||||
|
|||||||
@@ -163,7 +163,6 @@ pub mod user {
|
|||||||
#[schema(examples(
|
#[schema(examples(
|
||||||
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjY3ZGNjOWE5NTA3YjAwMDA3NzI3NDRhMiIsImlhdCI6IjE3NDMxMDgwOTkiLCJleHAiOiIxODY5MjUyMDk5In0.rMgXRb3JbT9AvLK4eiY9HMB5LxgUudkpQyoWKOypZFY"
|
"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjY3ZGNjOWE5NTA3YjAwMDA3NzI3NDRhMiIsImlhdCI6IjE3NDMxMDgwOTkiLCJleHAiOiIxODY5MjUyMDk5In0.rMgXRb3JbT9AvLK4eiY9HMB5LxgUudkpQyoWKOypZFY"
|
||||||
))]
|
))]
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
pub access_token: Option<String>,
|
pub access_token: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
use crate::routes::schema::user::UserResponse;
|
|
||||||
use crate::routes::users::by::schema::{ErrorCode, ServiceResponse};
|
|
||||||
use crate::state::AppState;
|
|
||||||
use actix_web::{get, web};
|
|
||||||
use database::query::Query;
|
|
||||||
|
|
||||||
#[utoipa::path(responses((status = OK, body = UserResponse)))]
|
|
||||||
#[get("/id/{id}")]
|
|
||||||
pub async fn by_id(app_state: web::Data<AppState>, path: web::Path<String>) -> ServiceResponse {
|
|
||||||
let user_id = path.into_inner();
|
|
||||||
|
|
||||||
let db = app_state.get_database();
|
|
||||||
|
|
||||||
match Query::find_user_by_id(db, &user_id).await {
|
|
||||||
Ok(Some(user)) => Ok(UserResponse::from(user)),
|
|
||||||
_ => Err(ErrorCode::NotFound),
|
|
||||||
}
|
|
||||||
.into()
|
|
||||||
}
|
|
||||||
|
|
||||||
#[utoipa::path(responses((status = OK, body = UserResponse)))]
|
|
||||||
#[get("/telegram-id/{id}")]
|
|
||||||
pub async fn by_telegram_id(
|
|
||||||
app_state: web::Data<AppState>,
|
|
||||||
path: web::Path<i64>,
|
|
||||||
) -> ServiceResponse {
|
|
||||||
let telegram_id = path.into_inner();
|
|
||||||
|
|
||||||
let db = app_state.get_database();
|
|
||||||
|
|
||||||
match Query::find_user_by_telegram_id(db, telegram_id).await {
|
|
||||||
Ok(Some(user)) => Ok(UserResponse::from(user)),
|
|
||||||
_ => Err(ErrorCode::NotFound),
|
|
||||||
}
|
|
||||||
.into()
|
|
||||||
}
|
|
||||||
|
|
||||||
mod schema {
|
|
||||||
use crate::routes::schema::user::UserResponse;
|
|
||||||
use actix_macros::ErrResponse;
|
|
||||||
use derive_more::Display;
|
|
||||||
use serde::Serialize;
|
|
||||||
use utoipa::ToSchema;
|
|
||||||
|
|
||||||
pub type ServiceResponse = crate::routes::schema::Response<UserResponse, ErrorCode>;
|
|
||||||
|
|
||||||
#[derive(Clone, Serialize, Display, ToSchema, ErrResponse)]
|
|
||||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
|
||||||
#[schema(as = Users::By::ErrorCode)]
|
|
||||||
pub enum ErrorCode {
|
|
||||||
/// User not found.
|
|
||||||
#[status_code = "actix_web::http::StatusCode::NOT_FOUND"]
|
|
||||||
#[display("Required user not found.")]
|
|
||||||
NotFound,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,3 @@
|
|||||||
pub mod by;
|
|
||||||
mod change_group;
|
mod change_group;
|
||||||
mod change_username;
|
mod change_username;
|
||||||
mod me;
|
mod me;
|
||||||
|
|||||||
Vendored
+9
@@ -2,13 +2,22 @@ pub mod schedule;
|
|||||||
pub mod telegram;
|
pub mod telegram;
|
||||||
pub mod vk_id;
|
pub mod vk_id;
|
||||||
|
|
||||||
|
#[cfg(not(test))]
|
||||||
|
pub mod yandex_cloud;
|
||||||
|
|
||||||
pub use self::schedule::ScheduleEnvData;
|
pub use self::schedule::ScheduleEnvData;
|
||||||
pub use self::telegram::TelegramEnvData;
|
pub use self::telegram::TelegramEnvData;
|
||||||
pub use self::vk_id::VkIdEnvData;
|
pub use self::vk_id::VkIdEnvData;
|
||||||
|
|
||||||
|
#[cfg(not(test))]
|
||||||
|
pub use self::yandex_cloud::YandexCloudEnvData;
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
pub struct AppEnv {
|
pub struct AppEnv {
|
||||||
pub schedule: ScheduleEnvData,
|
pub schedule: ScheduleEnvData,
|
||||||
pub telegram: TelegramEnvData,
|
pub telegram: TelegramEnvData,
|
||||||
pub vk_id: VkIdEnvData,
|
pub vk_id: VkIdEnvData,
|
||||||
|
|
||||||
|
#[cfg(not(test))]
|
||||||
|
pub yandex_cloud: YandexCloudEnvData,
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+2
-5
@@ -2,10 +2,8 @@ use std::env;
|
|||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ScheduleEnvData {
|
pub struct ScheduleEnvData {
|
||||||
/// Public link to the Yandex Disk folder the schedule files are uploaded to.
|
|
||||||
#[cfg(not(test))]
|
#[cfg(not(test))]
|
||||||
pub yandex_disk_url: String,
|
pub url: Option<String>,
|
||||||
|
|
||||||
pub auto_update: bool,
|
pub auto_update: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -13,8 +11,7 @@ impl Default for ScheduleEnvData {
|
|||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self {
|
Self {
|
||||||
#[cfg(not(test))]
|
#[cfg(not(test))]
|
||||||
yandex_disk_url: env::var("SCHEDULE_YANDEX_DISK_URL")
|
url: env::var("SCHEDULE_INIT_URL").ok(),
|
||||||
.expect("SCHEDULE_YANDEX_DISK_URL must be set"),
|
|
||||||
auto_update: !env::var("SCHEDULE_DISABLE_AUTO_UPDATE")
|
auto_update: !env::var("SCHEDULE_DISABLE_AUTO_UPDATE")
|
||||||
.is_ok_and(|v| v.eq("1") || v.eq("true")),
|
.is_ok_and(|v| v.eq("1") || v.eq("true")),
|
||||||
}
|
}
|
||||||
|
|||||||
Vendored
+16
@@ -0,0 +1,16 @@
|
|||||||
|
use std::env;
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct YandexCloudEnvData {
|
||||||
|
pub api_key: String,
|
||||||
|
pub func_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for YandexCloudEnvData {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
api_key: env::var("YANDEX_CLOUD_API_KEY").expect("YANDEX_CLOUD_API_KEY must be set"),
|
||||||
|
func_id: env::var("YANDEX_CLOUD_FUNC_ID").expect("YANDEX_CLOUD_FUNC_ID must be set"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+16
-41
@@ -38,8 +38,13 @@ impl AppState {
|
|||||||
|
|
||||||
#[cfg(not(test))]
|
#[cfg(not(test))]
|
||||||
{
|
{
|
||||||
providers::EngelsPolytechnicUpdateSource::YandexDisk {
|
if let Some(url) = &env.schedule.url {
|
||||||
public_url: env.schedule.yandex_disk_url.clone(),
|
providers::EngelsPolytechnicUpdateSource::Url(url.clone())
|
||||||
|
} else {
|
||||||
|
providers::EngelsPolytechnicUpdateSource::GrabFromSite {
|
||||||
|
yandex_api_key: env.yandex_cloud.api_key.clone(),
|
||||||
|
yandex_func_id: env.yandex_cloud.func_id.clone(),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
@@ -51,8 +56,15 @@ impl AppState {
|
|||||||
database: if let Some(database) = database {
|
database: if let Some(database) = database {
|
||||||
database
|
database
|
||||||
} else {
|
} else {
|
||||||
let opt = database_connect_options();
|
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
||||||
let database_url = opt.get_url().to_string();
|
|
||||||
|
let mut opt = ConnectOptions::new(database_url.clone());
|
||||||
|
|
||||||
|
opt.max_connections(4)
|
||||||
|
.min_connections(2)
|
||||||
|
.connect_timeout(Duration::from_secs(10))
|
||||||
|
.idle_timeout(Duration::from_secs(8))
|
||||||
|
.sqlx_logging(true);
|
||||||
|
|
||||||
let database = Database::connect(opt)
|
let database = Database::connect(opt)
|
||||||
.await
|
.await
|
||||||
@@ -97,43 +109,6 @@ impl AppState {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Параметры подключения к базе данных.
|
|
||||||
#[cfg(not(test))]
|
|
||||||
fn database_connect_options() -> ConnectOptions {
|
|
||||||
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
|
||||||
|
|
||||||
let mut opt = ConnectOptions::new(database_url);
|
|
||||||
|
|
||||||
opt.max_connections(4)
|
|
||||||
.min_connections(2)
|
|
||||||
.connect_timeout(Duration::from_secs(10))
|
|
||||||
.idle_timeout(Duration::from_secs(8))
|
|
||||||
.sqlx_logging(true);
|
|
||||||
|
|
||||||
opt
|
|
||||||
}
|
|
||||||
|
|
||||||
/// SQLite во временном файле: база в памяти умрёт вместе с соединением.
|
|
||||||
#[cfg(test)]
|
|
||||||
fn database_connect_options() -> ConnectOptions {
|
|
||||||
let path = std::env::temp_dir().join(format!(
|
|
||||||
"{}-test-{}.sqlite",
|
|
||||||
env!("CARGO_PKG_NAME"),
|
|
||||||
std::process::id()
|
|
||||||
));
|
|
||||||
|
|
||||||
let _ = std::fs::remove_file(&path);
|
|
||||||
|
|
||||||
let mut opt = ConnectOptions::new(format!("sqlite://{}?mode=rwc", path.display()));
|
|
||||||
|
|
||||||
opt.max_connections(1)
|
|
||||||
.min_connections(1)
|
|
||||||
.connect_timeout(Duration::from_secs(10))
|
|
||||||
.sqlx_logging(true);
|
|
||||||
|
|
||||||
opt
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Create a new object web::Data<AppState>.
|
/// Create a new object web::Data<AppState>.
|
||||||
pub async fn new_app_state(
|
pub async fn new_app_state(
|
||||||
database: Option<DatabaseConnection>,
|
database: Option<DatabaseConnection>,
|
||||||
|
|||||||
+14
-17
@@ -1,14 +1,13 @@
|
|||||||
use chrono::Duration;
|
use chrono::Duration;
|
||||||
use chrono::Utc;
|
use chrono::Utc;
|
||||||
use jsonwebtoken::errors::ErrorKind;
|
use jsonwebtoken::errors::ErrorKind;
|
||||||
use jsonwebtoken::{decode, Algorithm, DecodingKey, EncodingKey, Header, Validation};
|
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation, decode};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_with::serde_as;
|
|
||||||
use serde_with::DisplayFromStr;
|
use serde_with::DisplayFromStr;
|
||||||
|
use serde_with::serde_as;
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::mem::discriminant;
|
use std::mem::discriminant;
|
||||||
use std::sync::LazyLock;
|
use std::sync::LazyLock;
|
||||||
use database::entity::UserType;
|
|
||||||
|
|
||||||
/// Key for token verification.
|
/// Key for token verification.
|
||||||
static DECODING_KEY: LazyLock<DecodingKey> = LazyLock::new(|| {
|
static DECODING_KEY: LazyLock<DecodingKey> = LazyLock::new(|| {
|
||||||
@@ -43,31 +42,27 @@ impl PartialEq for Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/// The data the token holds.
|
/// The data the token holds.
|
||||||
#[serde_as]
|
#[serde_as]
|
||||||
#[derive(Debug, Serialize, Deserialize)]
|
#[derive(Debug, Serialize, Deserialize)]
|
||||||
pub struct Claims {
|
struct Claims {
|
||||||
/// User account UUID.
|
/// User account UUID.
|
||||||
pub id: String,
|
id: String,
|
||||||
|
|
||||||
/// User type.
|
|
||||||
pub user_type: Option<UserType>,
|
|
||||||
|
|
||||||
/// Token creation date.
|
/// Token creation date.
|
||||||
#[serde_as(as = "DisplayFromStr")]
|
#[serde_as(as = "DisplayFromStr")]
|
||||||
pub iat: u64,
|
iat: u64,
|
||||||
|
|
||||||
/// Token expiry date.
|
/// Token expiry date.
|
||||||
#[serde_as(as = "DisplayFromStr")]
|
#[serde_as(as = "DisplayFromStr")]
|
||||||
pub exp: u64,
|
exp: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Token signing algorithm.
|
/// Token signing algorithm.
|
||||||
pub(crate) const DEFAULT_ALGORITHM: Algorithm = Algorithm::HS256;
|
pub(crate) const DEFAULT_ALGORITHM: Algorithm = Algorithm::HS256;
|
||||||
|
|
||||||
/// Checking the token and extracting the UUID of the user account from it.
|
/// Checking the token and extracting the UUID of the user account from it.
|
||||||
pub fn verify_and_decode(token: &str) -> Result<Claims, Error> {
|
pub fn verify_and_decode(token: &str) -> Result<String, Error> {
|
||||||
let mut validation = Validation::new(DEFAULT_ALGORITHM);
|
let mut validation = Validation::new(DEFAULT_ALGORITHM);
|
||||||
|
|
||||||
validation.required_spec_claims.remove("exp");
|
validation.required_spec_claims.remove("exp");
|
||||||
@@ -80,7 +75,7 @@ pub fn verify_and_decode(token: &str) -> Result<Claims, Error> {
|
|||||||
if token_data.claims.exp < Utc::now().timestamp().unsigned_abs() {
|
if token_data.claims.exp < Utc::now().timestamp().unsigned_abs() {
|
||||||
Err(Error::Expired)
|
Err(Error::Expired)
|
||||||
} else {
|
} else {
|
||||||
Ok(token_data.claims)
|
Ok(token_data.claims.id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(err) => Err(match err.into_kind() {
|
Err(err) => Err(match err.into_kind() {
|
||||||
@@ -92,7 +87,7 @@ pub fn verify_and_decode(token: &str) -> Result<Claims, Error> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Creating a user token.
|
/// Creating a user token.
|
||||||
pub fn encode(user_type: UserType, id: &str) -> String {
|
pub fn encode(id: &str) -> String {
|
||||||
let header = Header {
|
let header = Header {
|
||||||
typ: Some(String::from("JWT")),
|
typ: Some(String::from("JWT")),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@@ -103,7 +98,6 @@ pub fn encode(user_type: UserType, id: &str) -> String {
|
|||||||
|
|
||||||
let claims = Claims {
|
let claims = Claims {
|
||||||
id: id.to_string(),
|
id: id.to_string(),
|
||||||
user_type: Some(user_type),
|
|
||||||
iat: iat.timestamp().unsigned_abs(),
|
iat: iat.timestamp().unsigned_abs(),
|
||||||
exp: exp.timestamp().unsigned_abs(),
|
exp: exp.timestamp().unsigned_abs(),
|
||||||
};
|
};
|
||||||
@@ -120,7 +114,7 @@ mod tests {
|
|||||||
fn test_encode() {
|
fn test_encode() {
|
||||||
test_env();
|
test_env();
|
||||||
|
|
||||||
assert!(!encode(UserType::Default, "test").is_empty());
|
assert!(!encode("test").is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -131,7 +125,10 @@ mod tests {
|
|||||||
let result = verify_and_decode(&token);
|
let result = verify_and_decode(&token);
|
||||||
|
|
||||||
assert!(result.is_err());
|
assert!(result.is_err());
|
||||||
assert_eq!(result.err().unwrap(), Error::InvalidToken);
|
assert_eq!(
|
||||||
|
result.err().unwrap(),
|
||||||
|
Error::InvalidToken
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
//noinspection SpellCheckingInspection
|
//noinspection SpellCheckingInspection
|
||||||
|
|||||||
@@ -1,3 +1,2 @@
|
|||||||
pub mod jwt;
|
pub mod jwt;
|
||||||
pub mod telegram;
|
pub mod telegram;
|
||||||
pub mod req_auth;
|
|
||||||
|
|||||||
@@ -1,56 +0,0 @@
|
|||||||
use crate::utility::jwt;
|
|
||||||
use crate::utility::jwt::Claims;
|
|
||||||
use actix_web::http::header;
|
|
||||||
use actix_web::HttpRequest;
|
|
||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
|
||||||
pub enum Error {
|
|
||||||
/// There is no Authorization header or cookie in the request.
|
|
||||||
NoHeaderOrCookieFound,
|
|
||||||
|
|
||||||
/// Unknown authorization type other than Bearer.
|
|
||||||
UnknownAuthorizationType,
|
|
||||||
|
|
||||||
/// Invalid or expired access token.
|
|
||||||
InvalidAccessToken,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_access_token_from_header(req: &HttpRequest) -> Result<String, Error> {
|
|
||||||
let header_value = req
|
|
||||||
.headers()
|
|
||||||
.get(header::AUTHORIZATION)
|
|
||||||
.ok_or(Error::NoHeaderOrCookieFound)?
|
|
||||||
.to_str()
|
|
||||||
.map_err(|_| Error::NoHeaderOrCookieFound)?
|
|
||||||
.to_string();
|
|
||||||
|
|
||||||
let parts = header_value
|
|
||||||
.split_once(' ')
|
|
||||||
.ok_or(Error::UnknownAuthorizationType)?;
|
|
||||||
|
|
||||||
if parts.0 != "Bearer" {
|
|
||||||
Err(Error::UnknownAuthorizationType)
|
|
||||||
} else {
|
|
||||||
Ok(parts.1.to_string())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_access_token_from_cookies(req: &HttpRequest) -> Result<String, Error> {
|
|
||||||
let cookie = req
|
|
||||||
.cookie("access_token")
|
|
||||||
.ok_or(Error::NoHeaderOrCookieFound)?;
|
|
||||||
|
|
||||||
Ok(cookie.value().to_string())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn get_claims_from_req(req: &HttpRequest) -> Result<Claims, Error> {
|
|
||||||
let access_token = match get_access_token_from_header(req) {
|
|
||||||
Err(Error::NoHeaderOrCookieFound) => get_access_token_from_cookies(req)?,
|
|
||||||
Err(error) => {
|
|
||||||
return Err(error);
|
|
||||||
}
|
|
||||||
Ok(access_token) => access_token,
|
|
||||||
};
|
|
||||||
|
|
||||||
jwt::verify_and_decode(&access_token).map_err(|_| Error::InvalidAccessToken)
|
|
||||||
}
|
|
||||||
+8
-14
@@ -1,13 +1,10 @@
|
|||||||
use aws_lc_rs::signature::{ED25519, UnparsedPublicKey};
|
|
||||||
use base64::Engine;
|
use base64::Engine;
|
||||||
use derive_more::{Display, Error};
|
use derive_more::{Display, Error};
|
||||||
|
use ed25519_dalek::Verifier;
|
||||||
use hex_literal::hex;
|
use hex_literal::hex;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
/// Длина подписи Ed25519 в байтах.
|
|
||||||
const ED25519_SIGNATURE_LENGTH: usize = 64;
|
|
||||||
|
|
||||||
pub struct WebAppInitDataMap {
|
pub struct WebAppInitDataMap {
|
||||||
pub data_map: HashMap<String, String>,
|
pub data_map: HashMap<String, String>,
|
||||||
}
|
}
|
||||||
@@ -57,10 +54,10 @@ impl WebAppInitDataMap {
|
|||||||
hex!("40055058a4ee38156a06562e52eece92a771bcd8346a8c4615cb7376eddf72ec"),
|
hex!("40055058a4ee38156a06562e52eece92a771bcd8346a8c4615cb7376eddf72ec"),
|
||||||
];
|
];
|
||||||
|
|
||||||
let verifying_key = UnparsedPublicKey::new(
|
let verifying_key = ed25519_dalek::VerifyingKey::from_bytes(
|
||||||
&ED25519,
|
&TELEGRAM_PUBLIC_KEY[if test_dc { 1 } else { 0 }],
|
||||||
TELEGRAM_PUBLIC_KEY[if test_dc { 1 } else { 0 }],
|
)
|
||||||
);
|
.unwrap();
|
||||||
|
|
||||||
let signature = {
|
let signature = {
|
||||||
let raw = self
|
let raw = self
|
||||||
@@ -72,11 +69,8 @@ impl WebAppInitDataMap {
|
|||||||
.decode(raw)
|
.decode(raw)
|
||||||
.map_err(|_| VerifyError::BadSignature)?;
|
.map_err(|_| VerifyError::BadSignature)?;
|
||||||
|
|
||||||
if bytes.len() != ED25519_SIGNATURE_LENGTH {
|
ed25519_dalek::Signature::from_slice(bytes.as_slice())
|
||||||
return Err(VerifyError::BadSignature);
|
.map_err(|_| VerifyError::BadSignature)?
|
||||||
}
|
|
||||||
|
|
||||||
bytes
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let data_check_string = format!("{}:WebAppData\n{}", bot_id, {
|
let data_check_string = format!("{}:WebAppData\n{}", bot_id, {
|
||||||
@@ -91,7 +85,7 @@ impl WebAppInitDataMap {
|
|||||||
});
|
});
|
||||||
|
|
||||||
verifying_key
|
verifying_key
|
||||||
.verify(data_check_string.as_bytes(), signature.as_slice())
|
.verify(data_check_string.as_bytes(), &signature)
|
||||||
.map_err(|_| VerifyError::IntegrityCheckFailed)
|
.map_err(|_| VerifyError::IntegrityCheckFailed)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user