mirror of
https://github.com/n08i40k/schedule-parser-rusted.git
synced 2025-12-06 17:57:47 +03:00
Compare commits
14 Commits
5e5cd53f46
...
release/v1
| Author | SHA1 | Date | |
|---|---|---|---|
|
6c9d3b3b31
|
|||
|
a348b1b99b
|
|||
|
ff12ee5da2
|
|||
|
35f707901f
|
|||
|
edea6c5424
|
|||
|
fdbb872fc3
|
|||
|
dbc800fef1
|
|||
|
e729d84c93
|
|||
|
cc7adf10ed
|
|||
|
57c1699c9a
|
|||
|
298c4f4dd3
|
|||
|
e3904a255b
|
|||
|
829c1cf68d
|
|||
|
6a535f8d73
|
4
.github/workflows/test.yml
vendored
4
.github/workflows/test.yml
vendored
@@ -18,10 +18,10 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Build
|
- name: Build
|
||||||
run: cargo build
|
run: cargo build
|
||||||
- name: Create .env.test
|
|
||||||
run: touch .env.test
|
|
||||||
- name: Run tests
|
- name: Run tests
|
||||||
run: cargo test
|
run: cargo test
|
||||||
env:
|
env:
|
||||||
|
|||||||
2253
Cargo.lock
generated
2253
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
48
Cargo.toml
48
Cargo.toml
@@ -3,46 +3,48 @@ members = ["actix-macros", "actix-test", "providers"]
|
|||||||
|
|
||||||
[package]
|
[package]
|
||||||
name = "schedule-parser-rusted"
|
name = "schedule-parser-rusted"
|
||||||
version = "1.0.5"
|
version = "1.2.2"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
publish = false
|
publish = false
|
||||||
|
|
||||||
[profile.release]
|
[profile.release]
|
||||||
debug = true
|
debug = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
trace = ["tracing", "console-subscriber"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
providers = { path = "providers" }
|
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.4.40", features = ["serde"] }
|
chrono = { version = "0.4.41", features = ["serde"] }
|
||||||
derive_more = { version = "2", features = ["full"] }
|
derive_more = { version = "2.0.1", features = ["full"] }
|
||||||
dotenvy = "0.15.7"
|
dotenvy = "0.15.7"
|
||||||
|
|
||||||
# sql
|
# sql
|
||||||
diesel = { version = "2.2.8", features = ["postgres"] }
|
database = { path = "database" }
|
||||||
diesel-derive-enum = { git = "https://github.com/Havunen/diesel-derive-enum.git", features = ["postgres"] }
|
|
||||||
|
|
||||||
# logging
|
# logging
|
||||||
env_logger = "0.11.7"
|
env_logger = "0.11.8"
|
||||||
|
|
||||||
# async
|
# async
|
||||||
tokio = { version = "1.44.1", features = ["macros", "rt-multi-thread"] }
|
tokio = { version = "1.47.1", features = ["macros", "rt-multi-thread"] }
|
||||||
tokio-util = "0.7.16"
|
tokio-util = "0.7.16"
|
||||||
futures-util = "0.3.31"
|
futures-util = "0.3.31"
|
||||||
|
|
||||||
# authorization
|
# authorization
|
||||||
bcrypt = "0.17.0"
|
bcrypt = "0.17.1"
|
||||||
jsonwebtoken = { version = "9.3.1", features = ["use_pem"] }
|
jsonwebtoken = { version = "9.3.1", features = ["use_pem"] }
|
||||||
|
|
||||||
# creating users
|
# creating users
|
||||||
objectid = "0.2.0"
|
objectid = "0.2.0"
|
||||||
|
|
||||||
# schedule downloader
|
# schedule downloader
|
||||||
reqwest = { version = "0.12.15", features = ["json"] }
|
reqwest = { version = "0.12.23", features = ["json"] }
|
||||||
mime = "0.3.17"
|
mime = "0.3.17"
|
||||||
|
|
||||||
# error handling
|
# error handling
|
||||||
@@ -51,24 +53,28 @@ sentry-actix = "0.42.0"
|
|||||||
|
|
||||||
# [de]serializing
|
# [de]serializing
|
||||||
serde = { version = "1.0.219", features = ["derive"] }
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
serde_json = "1.0.140"
|
serde_json = "1.0.143"
|
||||||
serde_with = "3.12.0"
|
serde_with = "3.14.0"
|
||||||
|
|
||||||
sha1 = "0.11.0-rc.0"
|
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.1"
|
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.4"
|
log = "0.4.27"
|
||||||
|
|
||||||
# telegram webdata deciding and verify
|
# telegram webdata deciding and verify
|
||||||
base64 = "0.22"
|
base64 = "0.22.1"
|
||||||
percent-encoding = "2.3"
|
percent-encoding = "2.3.2"
|
||||||
ed25519-dalek = "2"
|
ed25519-dalek = "3.0.0-pre.0"
|
||||||
|
|
||||||
|
# development tracing
|
||||||
|
console-subscriber = { version = "0.4.1", optional = true }
|
||||||
|
tracing = { version = "0.1.41", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
providers = { path = "providers", features = ["test"] }
|
providers = { path = "providers", features = ["test"] }
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
syn = "2"
|
syn = "2.0.106"
|
||||||
quote = "1"
|
quote = "1.0.40"
|
||||||
proc-macro2 = "1"
|
proc-macro2 = "1.0.101"
|
||||||
|
|
||||||
[lib]
|
[lib]
|
||||||
proc-macro = true
|
proc-macro = true
|
||||||
@@ -6,7 +6,7 @@ mod shared {
|
|||||||
use quote::{ToTokens, quote};
|
use quote::{ToTokens, quote};
|
||||||
use syn::{Attribute, DeriveInput};
|
use syn::{Attribute, DeriveInput};
|
||||||
|
|
||||||
pub fn find_status_code(attrs: &Vec<Attribute>) -> Option<proc_macro2::TokenStream> {
|
pub fn find_status_code(attrs: &[Attribute]) -> Option<proc_macro2::TokenStream> {
|
||||||
attrs
|
attrs
|
||||||
.iter()
|
.iter()
|
||||||
.find_map(|attr| -> Option<proc_macro2::TokenStream> {
|
.find_map(|attr| -> Option<proc_macro2::TokenStream> {
|
||||||
@@ -41,14 +41,12 @@ mod shared {
|
|||||||
|
|
||||||
let mut status_code_arms: Vec<proc_macro2::TokenStream> = variants
|
let mut status_code_arms: Vec<proc_macro2::TokenStream> = variants
|
||||||
.iter()
|
.iter()
|
||||||
.map(|v| -> Option<proc_macro2::TokenStream> {
|
.filter_map(|v| -> Option<proc_macro2::TokenStream> {
|
||||||
let status_code = find_status_code(&v.attrs)?;
|
let status_code = find_status_code(&v.attrs)?;
|
||||||
let variant_name = &v.ident;
|
let variant_name = &v.ident;
|
||||||
|
|
||||||
Some(quote! { #name::#variant_name => #status_code, })
|
Some(quote! { #name::#variant_name => #status_code, })
|
||||||
})
|
})
|
||||||
.filter(|v| v.is_some())
|
|
||||||
.map(|v| v.unwrap())
|
|
||||||
.collect();
|
.collect();
|
||||||
|
|
||||||
if status_code_arms.len() < variants.len() {
|
if status_code_arms.len() < variants.len() {
|
||||||
|
|||||||
@@ -4,5 +4,5 @@ version = "0.1.0"
|
|||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-http = "3"
|
actix-http = "3.11.1"
|
||||||
actix-web = "4"
|
actix-web = "4.11.0"
|
||||||
11
database/Cargo.toml
Normal file
11
database/Cargo.toml
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
[package]
|
||||||
|
name = "database"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
migration = { path = "migration" }
|
||||||
|
entity = { path = "entity" }
|
||||||
|
sea-orm = { version = "2.0.0-rc.6", features = ["sqlx-postgres", "runtime-tokio"] }
|
||||||
|
|
||||||
|
paste = "1.0.15"
|
||||||
1
database/entity/.gitignore
vendored
Normal file
1
database/entity/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
/target
|
||||||
9
database/entity/Cargo.toml
Normal file
9
database/entity/Cargo.toml
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
[package]
|
||||||
|
name = "entity"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
sea-orm = "2.0.0-rc.6"
|
||||||
|
serde = { version = "1.0.219", features = ["derive"] }
|
||||||
|
utoipa = "5.4.0"
|
||||||
6
database/entity/src/lib.rs
Normal file
6
database/entity/src/lib.rs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12
|
||||||
|
|
||||||
|
pub mod prelude;
|
||||||
|
|
||||||
|
pub mod sea_orm_active_enums;
|
||||||
|
pub mod user;
|
||||||
3
database/entity/src/prelude.rs
Normal file
3
database/entity/src/prelude.rs
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12
|
||||||
|
|
||||||
|
pub use super::user::Entity as User;
|
||||||
25
database/entity/src/sea_orm_active_enums.rs
Normal file
25
database/entity/src/sea_orm_active_enums.rs
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12
|
||||||
|
|
||||||
|
use sea_orm::entity::prelude::*;
|
||||||
|
|
||||||
|
#[derive(
|
||||||
|
Debug,
|
||||||
|
Clone,
|
||||||
|
PartialEq,
|
||||||
|
Eq,
|
||||||
|
EnumIter,
|
||||||
|
DeriveActiveEnum,
|
||||||
|
:: serde :: Serialize,
|
||||||
|
:: serde :: Deserialize,
|
||||||
|
:: utoipa :: ToSchema,
|
||||||
|
)]
|
||||||
|
#[sea_orm(rs_type = "String", db_type = "Enum", enum_name = "user_role")]
|
||||||
|
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||||
|
pub enum UserRole {
|
||||||
|
#[sea_orm(string_value = "student")]
|
||||||
|
Student,
|
||||||
|
#[sea_orm(string_value = "teacher")]
|
||||||
|
Teacher,
|
||||||
|
#[sea_orm(string_value = "admin")]
|
||||||
|
Admin,
|
||||||
|
}
|
||||||
25
database/entity/src/user.rs
Normal file
25
database/entity/src/user.rs
Normal file
@@ -0,0 +1,25 @@
|
|||||||
|
//! `SeaORM` Entity, @generated by sea-orm-codegen 1.1.12
|
||||||
|
|
||||||
|
use super::sea_orm_active_enums::UserRole;
|
||||||
|
use sea_orm::entity::prelude::*;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, PartialEq, DeriveEntityModel, Eq)]
|
||||||
|
#[sea_orm(table_name = "user")]
|
||||||
|
pub struct Model {
|
||||||
|
#[sea_orm(primary_key, auto_increment = false)]
|
||||||
|
pub id: String,
|
||||||
|
#[sea_orm(unique)]
|
||||||
|
pub username: String,
|
||||||
|
pub password: Option<String>,
|
||||||
|
pub vk_id: Option<i32>,
|
||||||
|
pub group: Option<String>,
|
||||||
|
pub role: UserRole,
|
||||||
|
pub android_version: Option<String>,
|
||||||
|
#[sea_orm(unique)]
|
||||||
|
pub telegram_id: Option<i64>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
|
||||||
|
pub enum Relation {}
|
||||||
|
|
||||||
|
impl ActiveModelBehavior for ActiveModel {}
|
||||||
1
database/migration/.gitignore
vendored
Normal file
1
database/migration/.gitignore
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
/target
|
||||||
22
database/migration/Cargo.toml
Normal file
22
database/migration/Cargo.toml
Normal file
@@ -0,0 +1,22 @@
|
|||||||
|
[package]
|
||||||
|
name = "migration"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[lib]
|
||||||
|
name = "migration"
|
||||||
|
path = "src/lib.rs"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
async-std = { version = "1", features = ["attributes", "tokio1"] }
|
||||||
|
|
||||||
|
[dependencies.sea-orm-migration]
|
||||||
|
version = "2.0.0-rc.6"
|
||||||
|
features = [
|
||||||
|
# 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.
|
||||||
|
# e.g.
|
||||||
|
"runtime-tokio", # `ASYNC_RUNTIME` feature
|
||||||
|
"sqlx-postgres", # `DATABASE_DRIVER` feature
|
||||||
|
]
|
||||||
16
database/migration/src/lib.rs
Normal file
16
database/migration/src/lib.rs
Normal file
@@ -0,0 +1,16 @@
|
|||||||
|
pub use sea_orm_migration::prelude::MigratorTrait;
|
||||||
|
|
||||||
|
use sea_orm_migration::prelude::*;
|
||||||
|
|
||||||
|
mod m20250904_024854_init;
|
||||||
|
|
||||||
|
pub struct Migrator;
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl MigratorTrait for Migrator {
|
||||||
|
fn migrations() -> Vec<Box<dyn MigrationTrait>> {
|
||||||
|
vec![
|
||||||
|
Box::new(m20250904_024854_init::Migration),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
70
database/migration/src/m20250904_024854_init.rs
Normal file
70
database/migration/src/m20250904_024854_init.rs
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
use sea_orm_migration::prelude::extension::postgres::Type;
|
||||||
|
use sea_orm_migration::sea_orm::{EnumIter, Iterable};
|
||||||
|
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_type(
|
||||||
|
Type::create()
|
||||||
|
.as_enum(UserRole)
|
||||||
|
.values(UserRoleVariants::iter())
|
||||||
|
.to_owned(),
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
manager
|
||||||
|
.create_table(
|
||||||
|
Table::create()
|
||||||
|
.table(User::Table)
|
||||||
|
.if_not_exists()
|
||||||
|
.col(string_uniq(User::Id).primary_key().not_null())
|
||||||
|
.col(string_uniq(User::Username).not_null())
|
||||||
|
.col(string_null(User::Password))
|
||||||
|
.col(integer_null(User::VkId))
|
||||||
|
.col(string_null(User::Group))
|
||||||
|
.col(enumeration(User::Role, UserRole, UserRoleVariants::iter()))
|
||||||
|
.col(string_null(User::AndroidVersion))
|
||||||
|
.col(big_integer_null(User::TelegramId).unique_key())
|
||||||
|
.to_owned(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
|
||||||
|
manager
|
||||||
|
.drop_table(Table::drop().table(User::Table).to_owned())
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
manager
|
||||||
|
.drop_type(Type::drop().name(UserRole).to_owned())
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(DeriveIden)]
|
||||||
|
struct UserRole;
|
||||||
|
|
||||||
|
#[derive(DeriveIden, EnumIter)]
|
||||||
|
enum UserRoleVariants {
|
||||||
|
Student,
|
||||||
|
Teacher,
|
||||||
|
Admin,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(DeriveIden)]
|
||||||
|
enum User {
|
||||||
|
Table,
|
||||||
|
Id,
|
||||||
|
Username,
|
||||||
|
Password,
|
||||||
|
VkId,
|
||||||
|
Group,
|
||||||
|
Role,
|
||||||
|
AndroidVersion,
|
||||||
|
TelegramId,
|
||||||
|
}
|
||||||
6
database/migration/src/main.rs
Normal file
6
database/migration/src/main.rs
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
use sea_orm_migration::prelude::*;
|
||||||
|
|
||||||
|
#[async_std::main]
|
||||||
|
async fn main() {
|
||||||
|
cli::run_cli(migration::Migrator).await;
|
||||||
|
}
|
||||||
10
database/src/lib.rs
Normal file
10
database/src/lib.rs
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
pub mod query;
|
||||||
|
|
||||||
|
pub use migration;
|
||||||
|
pub use sea_orm;
|
||||||
|
|
||||||
|
pub mod entity {
|
||||||
|
pub use entity::*;
|
||||||
|
|
||||||
|
pub use entity::user::{ActiveModel as ActiveUser, Model as User, Entity as UserEntity, Column as UserColumn};
|
||||||
|
}
|
||||||
63
database/src/query.rs
Normal file
63
database/src/query.rs
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
use paste::paste;
|
||||||
|
use sea_orm::ColumnTrait;
|
||||||
|
use sea_orm::EntityTrait;
|
||||||
|
use sea_orm::QueryFilter;
|
||||||
|
|
||||||
|
pub struct Query;
|
||||||
|
|
||||||
|
macro_rules! ref_type {
|
||||||
|
(String) => {
|
||||||
|
&String
|
||||||
|
};
|
||||||
|
(str) => {
|
||||||
|
&str
|
||||||
|
};
|
||||||
|
($other:ty) => {
|
||||||
|
$other
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! define_is_exists {
|
||||||
|
($entity: ident, $by: ident, $by_type: ident, $by_column: ident) => {
|
||||||
|
paste! {
|
||||||
|
pub async fn [<is_ $entity _exists_by_ $by>](
|
||||||
|
db: &::sea_orm::DbConn,
|
||||||
|
$by: ref_type!($by_type)
|
||||||
|
) -> Result<bool, ::sea_orm::DbErr> {
|
||||||
|
::entity::$entity::Entity::find()
|
||||||
|
.filter(::entity::$entity::Column::$by_column.eq($by))
|
||||||
|
.one(db)
|
||||||
|
.await
|
||||||
|
.map(|x| x.is_some())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! define_find_by {
|
||||||
|
($entity: ident, $by: ident, $by_type: ident, $by_column: ident) => {
|
||||||
|
paste! {
|
||||||
|
pub async fn [<find_ $entity _by_ $by>](
|
||||||
|
db: &::sea_orm::DbConn,
|
||||||
|
$by: ref_type!($by_type)
|
||||||
|
) -> Result<Option<::entity::$entity::Model>, ::sea_orm::DbErr> {
|
||||||
|
::entity::$entity::Entity::find()
|
||||||
|
.filter(::entity::$entity::Column::$by_column.eq($by))
|
||||||
|
.one(db)
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Query {
|
||||||
|
define_find_by!(user, id, str, Id);
|
||||||
|
define_find_by!(user, telegram_id, i64, TelegramId);
|
||||||
|
define_find_by!(user, vk_id, i32, VkId);
|
||||||
|
define_find_by!(user, username, str, Username);
|
||||||
|
|
||||||
|
define_is_exists!(user, id, str, Id);
|
||||||
|
define_is_exists!(user, username, str, Username);
|
||||||
|
define_is_exists!(user, telegram_id, i64, TelegramId);
|
||||||
|
define_is_exists!(user, vk_id, i32, VkId);
|
||||||
|
}
|
||||||
@@ -1,9 +0,0 @@
|
|||||||
# For documentation on how to configure this file,
|
|
||||||
# see https://diesel.rs/guides/configuring-diesel-cli
|
|
||||||
|
|
||||||
[print_schema]
|
|
||||||
file = "src/database/schema.rs"
|
|
||||||
custom_type_derives = ["diesel::query_builder::QueryId", "Clone"]
|
|
||||||
|
|
||||||
[migrations_directory]
|
|
||||||
dir = "./migrations"
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
-- This file was automatically created by Diesel to set up helper functions
|
|
||||||
-- and other internal bookkeeping. This file is safe to edit, any future
|
|
||||||
-- changes will be added to existing projects as new migrations.
|
|
||||||
|
|
||||||
DROP FUNCTION IF EXISTS diesel_manage_updated_at(_tbl regclass);
|
|
||||||
DROP FUNCTION IF EXISTS diesel_set_updated_at();
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
-- This file was automatically created by Diesel to set up helper functions
|
|
||||||
-- and other internal bookkeeping. This file is safe to edit, any future
|
|
||||||
-- changes will be added to existing projects as new migrations.
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
-- Sets up a trigger for the given table to automatically set a column called
|
|
||||||
-- `updated_at` whenever the row is modified (unless `updated_at` was included
|
|
||||||
-- in the modified columns)
|
|
||||||
--
|
|
||||||
-- # Example
|
|
||||||
--
|
|
||||||
-- ```sql
|
|
||||||
-- CREATE TABLE users (id SERIAL PRIMARY KEY, updated_at TIMESTAMP NOT NULL DEFAULT NOW());
|
|
||||||
--
|
|
||||||
-- SELECT diesel_manage_updated_at('users');
|
|
||||||
-- ```
|
|
||||||
CREATE OR REPLACE FUNCTION diesel_manage_updated_at(_tbl regclass) RETURNS VOID AS $$
|
|
||||||
BEGIN
|
|
||||||
EXECUTE format('CREATE TRIGGER set_updated_at BEFORE UPDATE ON %s
|
|
||||||
FOR EACH ROW EXECUTE PROCEDURE diesel_set_updated_at()', _tbl);
|
|
||||||
END;
|
|
||||||
$$ LANGUAGE plpgsql;
|
|
||||||
|
|
||||||
CREATE OR REPLACE FUNCTION diesel_set_updated_at() RETURNS trigger AS $$
|
|
||||||
BEGIN
|
|
||||||
IF (
|
|
||||||
NEW IS DISTINCT FROM OLD AND
|
|
||||||
NEW.updated_at IS NOT DISTINCT FROM OLD.updated_at
|
|
||||||
) THEN
|
|
||||||
NEW.updated_at := current_timestamp;
|
|
||||||
END IF;
|
|
||||||
RETURN NEW;
|
|
||||||
END;
|
|
||||||
$$ LANGUAGE plpgsql;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TYPE user_role;
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
CREATE TYPE user_role AS ENUM (
|
|
||||||
'STUDENT',
|
|
||||||
'TEACHER',
|
|
||||||
'ADMIN');
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE users;
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
CREATE TABLE users
|
|
||||||
(
|
|
||||||
id text PRIMARY KEY NOT NULL,
|
|
||||||
username text UNIQUE NOT NULL,
|
|
||||||
password text NOT NULL,
|
|
||||||
vk_id int4 NULL,
|
|
||||||
access_token text UNIQUE NOT NULL,
|
|
||||||
"group" text NOT NULL,
|
|
||||||
role user_role NOT NULL,
|
|
||||||
version text NOT NULL
|
|
||||||
);
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
DROP TABLE fcm;
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
CREATE TABLE fcm
|
|
||||||
(
|
|
||||||
user_id text PRIMARY KEY NOT NULL REFERENCES users (id),
|
|
||||||
token text NOT NULL,
|
|
||||||
topics text[] NOT NULL CHECK ( array_position(topics, null) is null )
|
|
||||||
);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
ALTER TABLE users DROP CONSTRAINT users_telegram_id_key;
|
|
||||||
ALTER TABLE users DROP COLUMN telegram_id;
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
ALTER TABLE users ADD telegram_id int8 NULL;
|
|
||||||
ALTER TABLE users ADD CONSTRAINT users_telegram_id_key UNIQUE (telegram_id);
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
UPDATE users SET "password" = '' WHERE "password" IS NULL;
|
|
||||||
ALTER TABLE users ALTER COLUMN "password" SET NOT NULL;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ALTER TABLE users ALTER COLUMN "password" DROP NOT NULL;
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
UPDATE users SET "android_version" = '' WHERE "android_version" IS NULL;
|
|
||||||
ALTER TABLE users ALTER COLUMN "android_version" SET NOT NULL;
|
|
||||||
ALTER TABLE users RENAME COLUMN android_version TO "version";
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
ALTER TABLE users RENAME COLUMN "version" TO android_version;
|
|
||||||
ALTER TABLE users ALTER COLUMN android_version DROP NOT NULL;
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
UPDATE users SET "group" = '' WHERE "group" IS NULL;
|
|
||||||
ALTER TABLE users ALTER COLUMN "group" SET NOT NULL;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ALTER TABLE users ALTER COLUMN "group" DROP NOT NULL;
|
|
||||||
@@ -1,2 +0,0 @@
|
|||||||
UPDATE users SET "access_token" = '' WHERE "access_token" IS NULL;
|
|
||||||
ALTER TABLE users ALTER COLUMN "access_token" SET NOT NULL;
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
ALTER TABLE users ALTER COLUMN "access_token" DROP NOT NULL;
|
|
||||||
@@ -14,4 +14,4 @@ serde_repr = "0.1.20"
|
|||||||
|
|
||||||
utoipa = { version = "5.4.0", features = ["macros", "chrono"] }
|
utoipa = { version = "5.4.0", features = ["macros", "chrono"] }
|
||||||
|
|
||||||
sha1 = "0.11.0-rc.0"
|
sha1 = "0.11.0-rc.2"
|
||||||
|
|||||||
@@ -20,12 +20,12 @@ derive_more = { version = "2.0.1", features = ["error", "display"] }
|
|||||||
|
|
||||||
utoipa = { version = "5.4.0", features = ["macros", "chrono"] }
|
utoipa = { version = "5.4.0", features = ["macros", "chrono"] }
|
||||||
|
|
||||||
calamine = { git = "https://github.com/prophittcorey/calamine.git", branch = "fix/zip-3.0" }
|
calamine = "0.30.0"
|
||||||
async-trait = "0.1.89"
|
async-trait = "0.1.89"
|
||||||
|
|
||||||
reqwest = "0.12.23"
|
reqwest = "0.12.23"
|
||||||
ua_generator = "0.5.22"
|
ua_generator = "0.5.22"
|
||||||
regex = "1.11.1"
|
regex = "1.11.2"
|
||||||
strsim = "0.11.1"
|
strsim = "0.11.1"
|
||||||
log = "0.4.27"
|
log = "0.4.27"
|
||||||
sentry = "0.42.0"
|
sentry = "0.42.0"
|
||||||
|
|||||||
@@ -25,7 +25,7 @@ pub struct EngelsPolytechnicProvider {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl EngelsPolytechnicProvider {
|
impl EngelsPolytechnicProvider {
|
||||||
pub async fn new(
|
pub async fn get(
|
||||||
update_source: UpdateSource,
|
update_source: UpdateSource,
|
||||||
) -> Result<Arc<dyn ScheduleProvider>, crate::updater::error::Error> {
|
) -> Result<Arc<dyn ScheduleProvider>, crate::updater::error::Error> {
|
||||||
let (updater, snapshot) = Updater::new(update_source).await?;
|
let (updater, snapshot) = Updater::new(update_source).await?;
|
||||||
@@ -60,7 +60,7 @@ impl ScheduleProvider for Wrapper {
|
|||||||
|
|
||||||
log::info!("Updating schedule...");
|
log::info!("Updating schedule...");
|
||||||
|
|
||||||
match this.updater.update(&mut this.snapshot).await {
|
match this.updater.update(&this.snapshot).await {
|
||||||
Ok(snapshot) => {
|
Ok(snapshot) => {
|
||||||
this.snapshot = Arc::new(snapshot);
|
this.snapshot = Arc::new(snapshot);
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use crate::or_continue;
|
use crate::or_continue;
|
||||||
use crate::parser::error::{ErrorCell, ErrorCellPos};
|
use crate::parser::error::{Error, ErrorCell, ErrorCellPos};
|
||||||
use crate::parser::worksheet::WorkSheet;
|
use crate::parser::worksheet::WorkSheet;
|
||||||
use crate::parser::LessonParseResult::{Lessons, Street};
|
use crate::parser::LessonParseResult::{Lessons, Street};
|
||||||
use base::LessonType::Break;
|
use base::LessonType::Break;
|
||||||
@@ -230,7 +230,7 @@ enum LessonParseResult {
|
|||||||
|
|
||||||
// noinspection GrazieInspection
|
// noinspection GrazieInspection
|
||||||
/// Obtaining a non-standard type of lesson by name.
|
/// Obtaining a non-standard type of lesson by name.
|
||||||
fn guess_lesson_type(text: &String) -> Option<LessonType> {
|
fn guess_lesson_type(text: &str) -> Option<LessonType> {
|
||||||
static MAP: LazyLock<HashMap<&str, LessonType>> = LazyLock::new(|| {
|
static MAP: LazyLock<HashMap<&str, LessonType>> = LazyLock::new(|| {
|
||||||
HashMap::from([
|
HashMap::from([
|
||||||
("консультация", LessonType::Consultation),
|
("консультация", LessonType::Consultation),
|
||||||
@@ -245,22 +245,18 @@ fn guess_lesson_type(text: &String) -> Option<LessonType> {
|
|||||||
|
|
||||||
let name_lower = text.to_lowercase();
|
let name_lower = text.to_lowercase();
|
||||||
|
|
||||||
match MAP
|
MAP.iter()
|
||||||
.iter()
|
.map(|(text, lesson_type)| (lesson_type, strsim::levenshtein(text, &name_lower)))
|
||||||
.map(|(text, lesson_type)| (lesson_type, strsim::levenshtein(text, &*name_lower)))
|
|
||||||
.filter(|x| x.1 <= 4)
|
.filter(|x| x.1 <= 4)
|
||||||
.min_by_key(|(_, score)| *score)
|
.min_by_key(|(_, score)| *score)
|
||||||
{
|
.map(|v| v.0.clone())
|
||||||
None => None,
|
|
||||||
Some(v) => Some(v.0.clone()),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Getting a pair or street from a cell.
|
/// Getting a pair or street from a cell.
|
||||||
fn parse_lesson(
|
fn parse_lesson(
|
||||||
worksheet: &WorkSheet,
|
worksheet: &WorkSheet,
|
||||||
day: &Day,
|
day: &Day,
|
||||||
day_boundaries: &Vec<BoundariesCellInfo>,
|
day_boundaries: &[BoundariesCellInfo],
|
||||||
lesson_boundaries: &BoundariesCellInfo,
|
lesson_boundaries: &BoundariesCellInfo,
|
||||||
group_column: u32,
|
group_column: u32,
|
||||||
) -> Result<LessonParseResult, crate::parser::error::Error> {
|
) -> Result<LessonParseResult, crate::parser::error::Error> {
|
||||||
@@ -297,7 +293,7 @@ fn parse_lesson(
|
|||||||
column: group_column,
|
column: group_column,
|
||||||
}))?;
|
}))?;
|
||||||
|
|
||||||
let range: Option<[u8; 2]> = if lesson_boundaries.default_index != None {
|
let range: Option<[u8; 2]> = if lesson_boundaries.default_index.is_some() {
|
||||||
let default = lesson_boundaries.default_index.unwrap() as u8;
|
let default = lesson_boundaries.default_index.unwrap() as u8;
|
||||||
Some([default, end_time.default_index.unwrap() as u8])
|
Some([default, end_time.default_index.unwrap() as u8])
|
||||||
} else {
|
} else {
|
||||||
@@ -312,7 +308,11 @@ fn parse_lesson(
|
|||||||
Ok((range, time))
|
Ok((range, time))
|
||||||
}?;
|
}?;
|
||||||
|
|
||||||
let (name, mut subgroups, lesson_type) = parse_name_and_subgroups(&name)?;
|
let ParsedLessonName {
|
||||||
|
name,
|
||||||
|
mut subgroups,
|
||||||
|
r#type: lesson_type,
|
||||||
|
} = parse_name_and_subgroups(&name)?;
|
||||||
|
|
||||||
{
|
{
|
||||||
let cabinets: Vec<String> = parse_cabinets(
|
let cabinets: Vec<String> = parse_cabinets(
|
||||||
@@ -325,12 +325,10 @@ fn parse_lesson(
|
|||||||
|
|
||||||
if cab_count == 1 {
|
if cab_count == 1 {
|
||||||
// Назначаем этот кабинет всем подгруппам
|
// Назначаем этот кабинет всем подгруппам
|
||||||
let cab = Some(cabinets.get(0).unwrap().clone());
|
let cab = Some(cabinets.first().unwrap().clone());
|
||||||
|
|
||||||
for subgroup in &mut subgroups {
|
for subgroup in subgroups.iter_mut().flatten() {
|
||||||
if let Some(subgroup) = subgroup {
|
subgroup.cabinet = cab.clone()
|
||||||
subgroup.cabinet = cab.clone()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
} else if cab_count == 2 {
|
} else if cab_count == 2 {
|
||||||
while subgroups.len() < cab_count {
|
while subgroups.len() < cab_count {
|
||||||
@@ -361,10 +359,7 @@ fn parse_lesson(
|
|||||||
range: default_range,
|
range: default_range,
|
||||||
name: Some(name),
|
name: Some(name),
|
||||||
time: lesson_time,
|
time: lesson_time,
|
||||||
subgroups: if subgroups.len() == 2
|
subgroups: if subgroups.len() == 2 && subgroups.iter().all(|x| x.is_none()) {
|
||||||
&& subgroups.get(0).unwrap().is_none()
|
|
||||||
&& subgroups.get(1).unwrap().is_none()
|
|
||||||
{
|
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
Some(subgroups)
|
Some(subgroups)
|
||||||
@@ -416,12 +411,15 @@ fn parse_cabinets(worksheet: &WorkSheet, row_range: (u32, u32), column: u32) ->
|
|||||||
cabinets
|
cabinets
|
||||||
}
|
}
|
||||||
|
|
||||||
|
struct ParsedLessonName {
|
||||||
|
name: String,
|
||||||
|
subgroups: Vec<Option<LessonSubGroup>>,
|
||||||
|
r#type: Option<LessonType>,
|
||||||
|
}
|
||||||
|
|
||||||
//noinspection GrazieInspection
|
//noinspection GrazieInspection
|
||||||
/// Getting the "pure" name of the lesson and list of teachers from the text of the lesson cell.
|
/// Getting the "pure" name of the lesson and list of teachers from the text of the lesson cell.
|
||||||
fn parse_name_and_subgroups(
|
fn parse_name_and_subgroups(text: &str) -> Result<ParsedLessonName, Error> {
|
||||||
text: &String,
|
|
||||||
) -> Result<(String, Vec<Option<LessonSubGroup>>, Option<LessonType>), crate::parser::error::Error>
|
|
||||||
{
|
|
||||||
// Части названия пары:
|
// Части названия пары:
|
||||||
// 1. Само название.
|
// 1. Само название.
|
||||||
// 2. Список преподавателей и подгрупп.
|
// 2. Список преподавателей и подгрупп.
|
||||||
@@ -458,7 +456,7 @@ fn parse_name_and_subgroups(
|
|||||||
static CLEAN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\s\n\t]+").unwrap());
|
static CLEAN_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\s\n\t]+").unwrap());
|
||||||
|
|
||||||
let text = CLEAN_RE
|
let text = CLEAN_RE
|
||||||
.replace(&text.replace(&[' ', '\t', '\n'], " "), " ")
|
.replace(&text.replace([' ', '\t', '\n'], " "), " ")
|
||||||
.to_string();
|
.to_string();
|
||||||
|
|
||||||
let (lesson_name, subgroups, lesson_type) = match NAMES_REGEX.captures(&text) {
|
let (lesson_name, subgroups, lesson_type) = match NAMES_REGEX.captures(&text) {
|
||||||
@@ -466,7 +464,7 @@ fn parse_name_and_subgroups(
|
|||||||
let capture = captures.get(0).unwrap();
|
let capture = captures.get(0).unwrap();
|
||||||
|
|
||||||
let subgroups: Vec<Option<LessonSubGroup>> = {
|
let subgroups: Vec<Option<LessonSubGroup>> = {
|
||||||
let src = capture.as_str().replace(&[' ', '.'], "");
|
let src = capture.as_str().replace([' ', '.'], "");
|
||||||
|
|
||||||
let mut shared_subgroup = false;
|
let mut shared_subgroup = false;
|
||||||
let mut subgroups: [Option<LessonSubGroup>; 2] = [None, None];
|
let mut subgroups: [Option<LessonSubGroup>; 2] = [None, None];
|
||||||
@@ -478,7 +476,7 @@ fn parse_name_and_subgroups(
|
|||||||
.map_or(0, |index| name[(index + 1)..(index + 2)].parse().unwrap());
|
.map_or(0, |index| name[(index + 1)..(index + 2)].parse().unwrap());
|
||||||
|
|
||||||
let teacher_name = {
|
let teacher_name = {
|
||||||
let name_end = open_bracket_index.unwrap_or_else(|| name.len());
|
let name_end = open_bracket_index.unwrap_or(name.len());
|
||||||
|
|
||||||
// Я ебал. Как же я долго до этого доходил.
|
// Я ебал. Как же я долго до этого доходил.
|
||||||
format!(
|
format!(
|
||||||
@@ -545,7 +543,11 @@ fn parse_name_and_subgroups(
|
|||||||
None => (text, Vec::new(), None),
|
None => (text, Vec::new(), None),
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok((lesson_name, subgroups, lesson_type))
|
Ok(ParsedLessonName {
|
||||||
|
name: lesson_name,
|
||||||
|
subgroups,
|
||||||
|
r#type: lesson_type,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Getting the start and end of a pair from a cell in the first column of a document.
|
/// Getting the start and end of a pair from a cell in the first column of a document.
|
||||||
@@ -554,18 +556,11 @@ fn parse_name_and_subgroups(
|
|||||||
///
|
///
|
||||||
/// * `cell_data`: text in cell.
|
/// * `cell_data`: text in cell.
|
||||||
/// * `date`: date of the current day.
|
/// * `date`: date of the current day.
|
||||||
fn parse_lesson_boundaries_cell(
|
fn parse_lesson_boundaries_cell(cell_data: &str, date: DateTime<Utc>) -> Option<LessonBoundaries> {
|
||||||
cell_data: &String,
|
|
||||||
date: DateTime<Utc>,
|
|
||||||
) -> Option<LessonBoundaries> {
|
|
||||||
static TIME_RE: LazyLock<Regex> =
|
static TIME_RE: LazyLock<Regex> =
|
||||||
LazyLock::new(|| Regex::new(r"(\d+\.\d+)-(\d+\.\d+)").unwrap());
|
LazyLock::new(|| Regex::new(r"(\d+\.\d+)-(\d+\.\d+)").unwrap());
|
||||||
|
|
||||||
let parse_res = if let Some(captures) = TIME_RE.captures(cell_data) {
|
let parse_res = TIME_RE.captures(cell_data)?;
|
||||||
captures
|
|
||||||
} else {
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
|
|
||||||
let start_match = parse_res.get(1).unwrap().as_str();
|
let start_match = parse_res.get(1).unwrap().as_str();
|
||||||
let start_parts: Vec<&str> = start_match.split(".").collect();
|
let start_parts: Vec<&str> = start_match.split(".").collect();
|
||||||
@@ -579,7 +574,7 @@ fn parse_lesson_boundaries_cell(
|
|||||||
};
|
};
|
||||||
|
|
||||||
Some(LessonBoundaries {
|
Some(LessonBoundaries {
|
||||||
start: GET_TIME(date.clone(), &start_parts),
|
start: GET_TIME(date, &start_parts),
|
||||||
end: GET_TIME(date, &end_parts),
|
end: GET_TIME(date, &end_parts),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -607,7 +602,7 @@ fn parse_day_boundaries(
|
|||||||
continue;
|
continue;
|
||||||
};
|
};
|
||||||
|
|
||||||
let lesson_time = parse_lesson_boundaries_cell(&time_cell, date.clone()).ok_or(
|
let lesson_time = parse_lesson_boundaries_cell(&time_cell, date).ok_or(
|
||||||
error::Error::LessonBoundaries(ErrorCell::new(row, column, time_cell.clone())),
|
error::Error::LessonBoundaries(ErrorCell::new(row, column, time_cell.clone())),
|
||||||
)?;
|
)?;
|
||||||
|
|
||||||
@@ -652,7 +647,7 @@ fn parse_day_boundaries(
|
|||||||
/// * `week_markup`: markup of the current week.
|
/// * `week_markup`: markup of the current week.
|
||||||
fn parse_week_boundaries(
|
fn parse_week_boundaries(
|
||||||
worksheet: &WorkSheet,
|
worksheet: &WorkSheet,
|
||||||
week_markup: &Vec<DayCellInfo>,
|
week_markup: &[DayCellInfo],
|
||||||
) -> Result<Vec<Vec<BoundariesCellInfo>>, crate::parser::error::Error> {
|
) -> Result<Vec<Vec<BoundariesCellInfo>>, crate::parser::error::Error> {
|
||||||
let mut result: Vec<Vec<BoundariesCellInfo>> = Vec::new();
|
let mut result: Vec<Vec<BoundariesCellInfo>> = Vec::new();
|
||||||
|
|
||||||
@@ -671,8 +666,8 @@ fn parse_week_boundaries(
|
|||||||
};
|
};
|
||||||
|
|
||||||
let day_boundaries = parse_day_boundaries(
|
let day_boundaries = parse_day_boundaries(
|
||||||
&worksheet,
|
worksheet,
|
||||||
day_markup.date.clone(),
|
day_markup.date,
|
||||||
(day_markup.row, end_row),
|
(day_markup.row, end_row),
|
||||||
lesson_time_column,
|
lesson_time_column,
|
||||||
)?;
|
)?;
|
||||||
@@ -698,7 +693,7 @@ fn convert_groups_to_teachers(
|
|||||||
.map(|day| Day {
|
.map(|day| Day {
|
||||||
name: day.name.clone(),
|
name: day.name.clone(),
|
||||||
street: day.street.clone(),
|
street: day.street.clone(),
|
||||||
date: day.date.clone(),
|
date: day.date,
|
||||||
lessons: vec![],
|
lessons: vec![],
|
||||||
})
|
})
|
||||||
.collect();
|
.collect();
|
||||||
@@ -774,19 +769,6 @@ fn convert_groups_to_teachers(
|
|||||||
/// * `buffer`: XLS data containing schedule.
|
/// * `buffer`: XLS data containing schedule.
|
||||||
///
|
///
|
||||||
/// returns: Result<ParseResult, crate::parser::error::Error>
|
/// returns: Result<ParseResult, crate::parser::error::Error>
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use schedule_parser::parse_xls;
|
|
||||||
///
|
|
||||||
/// let result = parse_xls(&include_bytes!("../../schedule.xls").to_vec());
|
|
||||||
///
|
|
||||||
/// assert!(result.is_ok(), "{}", result.err().unwrap());
|
|
||||||
///
|
|
||||||
/// assert_ne!(result.as_ref().unwrap().groups.len(), 0);
|
|
||||||
/// assert_ne!(result.as_ref().unwrap().teachers.len(), 0);
|
|
||||||
/// ```
|
|
||||||
pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParsedSchedule, crate::parser::error::Error> {
|
pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParsedSchedule, crate::parser::error::Error> {
|
||||||
let cursor = Cursor::new(&buffer);
|
let cursor = Cursor::new(&buffer);
|
||||||
let mut workbook: Xls<_> =
|
let mut workbook: Xls<_> =
|
||||||
@@ -800,7 +782,7 @@ pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParsedSchedule, crate::parser::erro
|
|||||||
.clone();
|
.clone();
|
||||||
|
|
||||||
let worksheet_merges = workbook
|
let worksheet_merges = workbook
|
||||||
.worksheet_merge_cells(&*worksheet_name)
|
.worksheet_merge_cells(&worksheet_name)
|
||||||
.ok_or(error::Error::NoWorkSheets)?;
|
.ok_or(error::Error::NoWorkSheets)?;
|
||||||
|
|
||||||
WorkSheet {
|
WorkSheet {
|
||||||
@@ -820,7 +802,7 @@ pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParsedSchedule, crate::parser::erro
|
|||||||
days: Vec::new(),
|
days: Vec::new(),
|
||||||
};
|
};
|
||||||
|
|
||||||
for day_index in 0..(&week_markup).len() {
|
for day_index in 0..week_markup.len() {
|
||||||
let day_markup = &week_markup[day_index];
|
let day_markup = &week_markup[day_index];
|
||||||
|
|
||||||
let mut day = Day {
|
let mut day = Day {
|
||||||
@@ -836,8 +818,8 @@ pub fn parse_xls(buffer: &Vec<u8>) -> Result<ParsedSchedule, crate::parser::erro
|
|||||||
match &mut parse_lesson(
|
match &mut parse_lesson(
|
||||||
&worksheet,
|
&worksheet,
|
||||||
&day,
|
&day,
|
||||||
&day_boundaries,
|
day_boundaries,
|
||||||
&lesson_boundaries,
|
lesson_boundaries,
|
||||||
group_markup.column,
|
group_markup.column,
|
||||||
)? {
|
)? {
|
||||||
Lessons(lesson) => day.lessons.append(lesson),
|
Lessons(lesson) => day.lessons.append(lesson),
|
||||||
|
|||||||
@@ -90,7 +90,7 @@ impl Updater {
|
|||||||
return Err(SnapshotCreationError::SameUrl);
|
return Err(SnapshotCreationError::SameUrl);
|
||||||
}
|
}
|
||||||
|
|
||||||
let head_result = downloader.set_url(&*url).await.map_err(|error| {
|
let head_result = downloader.set_url(&url).await.map_err(|error| {
|
||||||
if let FetchError::Unknown(error) = &error {
|
if let FetchError::Unknown(error) = &error {
|
||||||
sentry::capture_error(&error);
|
sentry::capture_error(&error);
|
||||||
}
|
}
|
||||||
@@ -152,10 +152,10 @@ impl Updater {
|
|||||||
.header("Authorization", format!("Api-Key {}", api_key))
|
.header("Authorization", format!("Api-Key {}", api_key))
|
||||||
.send()
|
.send()
|
||||||
.await
|
.await
|
||||||
.map_err(|error| QueryUrlError::RequestFailed(error))?
|
.map_err(QueryUrlError::RequestFailed)?
|
||||||
.text()
|
.text()
|
||||||
.await
|
.await
|
||||||
.map_err(|error| QueryUrlError::RequestFailed(error))?;
|
.map_err(QueryUrlError::RequestFailed)?;
|
||||||
|
|
||||||
Ok(format!("https://politehnikum-eng.ru{}", uri.trim()))
|
Ok(format!("https://politehnikum-eng.ru{}", uri.trim()))
|
||||||
}
|
}
|
||||||
@@ -196,7 +196,7 @@ impl Updater {
|
|||||||
log::info!("Obtaining a link using FaaS...");
|
log::info!("Obtaining a link using FaaS...");
|
||||||
Self::query_url(yandex_api_key, yandex_func_id)
|
Self::query_url(yandex_api_key, yandex_func_id)
|
||||||
.await
|
.await
|
||||||
.map_err(|error| Error::QueryUrlFailed(error))?
|
.map_err(Error::QueryUrlFailed)?
|
||||||
}
|
}
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
};
|
};
|
||||||
@@ -205,7 +205,7 @@ impl Updater {
|
|||||||
|
|
||||||
let snapshot = Self::new_snapshot(&mut this.downloader, url)
|
let snapshot = Self::new_snapshot(&mut this.downloader, url)
|
||||||
.await
|
.await
|
||||||
.map_err(|error| Error::SnapshotCreationFailed(error))?;
|
.map_err(Error::SnapshotCreationFailed)?;
|
||||||
|
|
||||||
log::info!("Schedule snapshot successfully created!");
|
log::info!("Schedule snapshot successfully created!");
|
||||||
|
|
||||||
@@ -243,7 +243,7 @@ impl Updater {
|
|||||||
yandex_func_id,
|
yandex_func_id,
|
||||||
} => Self::query_url(yandex_api_key.as_str(), yandex_func_id.as_str())
|
} => Self::query_url(yandex_api_key.as_str(), yandex_func_id.as_str())
|
||||||
.await
|
.await
|
||||||
.map_err(|error| Error::QueryUrlFailed(error))?,
|
.map_err(Error::QueryUrlFailed)?,
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -136,7 +136,7 @@ impl XlsDownloader {
|
|||||||
return Err(FetchError::bad_content_type(content_type.to_str().unwrap()));
|
return Err(FetchError::bad_content_type(content_type.to_str().unwrap()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let last_modified = DateTime::parse_from_rfc2822(&last_modified.to_str().unwrap())
|
let last_modified = DateTime::parse_from_rfc2822(last_modified.to_str().unwrap())
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.with_timezone(&Utc);
|
.with_timezone(&Utc);
|
||||||
|
|
||||||
@@ -151,14 +151,14 @@ impl XlsDownloader {
|
|||||||
if self.url.is_none() {
|
if self.url.is_none() {
|
||||||
Err(FetchError::NoUrlProvided)
|
Err(FetchError::NoUrlProvided)
|
||||||
} else {
|
} else {
|
||||||
Self::fetch_specified(&*self.url.as_ref().unwrap(), head).await
|
Self::fetch_specified(self.url.as_ref().unwrap(), head).await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn set_url(&mut self, url: &str) -> FetchResult {
|
pub async fn set_url(&mut self, url: &str) -> FetchResult {
|
||||||
let result = Self::fetch_specified(url, true).await;
|
let result = Self::fetch_specified(url, true).await;
|
||||||
|
|
||||||
if let Ok(_) = result {
|
if result.is_ok() {
|
||||||
self.url = Some(url.to_string());
|
self.url = Some(url.to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,148 +0,0 @@
|
|||||||
pub mod users {
|
|
||||||
use crate::database::models::User;
|
|
||||||
use crate::database::schema::users::dsl::users;
|
|
||||||
use crate::database::schema::users::dsl::*;
|
|
||||||
use crate::state::AppState;
|
|
||||||
use actix_web::web;
|
|
||||||
use diesel::{insert_into, ExpressionMethods, QueryResult};
|
|
||||||
use diesel::{QueryDsl, RunQueryDsl};
|
|
||||||
use diesel::{SaveChangesDsl, SelectableHelper};
|
|
||||||
use std::ops::DerefMut;
|
|
||||||
|
|
||||||
pub async fn get(state: &web::Data<AppState>, _id: &String) -> QueryResult<User> {
|
|
||||||
users
|
|
||||||
.filter(id.eq(_id))
|
|
||||||
.select(User::as_select())
|
|
||||||
.first(state.get_database().await.deref_mut())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn get_by_username(
|
|
||||||
state: &web::Data<AppState>,
|
|
||||||
_username: &String,
|
|
||||||
) -> QueryResult<User> {
|
|
||||||
users
|
|
||||||
.filter(username.eq(_username))
|
|
||||||
.select(User::as_select())
|
|
||||||
.first(state.get_database().await.deref_mut())
|
|
||||||
}
|
|
||||||
|
|
||||||
//noinspection RsTraitObligations
|
|
||||||
pub async fn get_by_vk_id(state: &web::Data<AppState>, _vk_id: i32) -> QueryResult<User> {
|
|
||||||
users
|
|
||||||
.filter(vk_id.eq(_vk_id))
|
|
||||||
.select(User::as_select())
|
|
||||||
.first(state.get_database().await.deref_mut())
|
|
||||||
}
|
|
||||||
|
|
||||||
//noinspection RsTraitObligations
|
|
||||||
pub async fn get_by_telegram_id(
|
|
||||||
state: &web::Data<AppState>,
|
|
||||||
_telegram_id: i64,
|
|
||||||
) -> QueryResult<User> {
|
|
||||||
users
|
|
||||||
.filter(telegram_id.eq(_telegram_id))
|
|
||||||
.select(User::as_select())
|
|
||||||
.first(state.get_database().await.deref_mut())
|
|
||||||
}
|
|
||||||
|
|
||||||
//noinspection DuplicatedCode
|
|
||||||
pub async fn contains_by_username(state: &web::Data<AppState>, _username: &String) -> bool {
|
|
||||||
// и как это нахуй сократить блять примеров нихуя нет, нихуя не работает
|
|
||||||
// как меня этот раст заебал уже
|
|
||||||
|
|
||||||
match users
|
|
||||||
.filter(username.eq(_username))
|
|
||||||
.count()
|
|
||||||
.get_result::<i64>(state.get_database().await.deref_mut())
|
|
||||||
{
|
|
||||||
Ok(count) => count > 0,
|
|
||||||
Err(_) => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
//noinspection DuplicatedCode
|
|
||||||
//noinspection RsTraitObligations
|
|
||||||
pub async fn contains_by_vk_id(state: &web::Data<AppState>, _vk_id: i32) -> bool {
|
|
||||||
match users
|
|
||||||
.filter(vk_id.eq(_vk_id))
|
|
||||||
.count()
|
|
||||||
.get_result::<i64>(state.get_database().await.deref_mut())
|
|
||||||
{
|
|
||||||
Ok(count) => count > 0,
|
|
||||||
Err(_) => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn insert(state: &web::Data<AppState>, user: &User) -> QueryResult<usize> {
|
|
||||||
insert_into(users)
|
|
||||||
.values(user)
|
|
||||||
.execute(state.get_database().await.deref_mut())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Function declaration [User::save][UserSave::save].
|
|
||||||
pub trait UserSave {
|
|
||||||
/// Saves the user's changes to the database.
|
|
||||||
///
|
|
||||||
/// # Arguments
|
|
||||||
///
|
|
||||||
/// * `state`: The state of the actix-web application that stores the mutex of the [connection][diesel::PgConnection].
|
|
||||||
///
|
|
||||||
/// returns: `QueryResult<User>`
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
///
|
|
||||||
/// ```
|
|
||||||
/// use crate::database::driver::users;
|
|
||||||
///
|
|
||||||
/// #[derive(Deserialize)]
|
|
||||||
/// struct Params {
|
|
||||||
/// pub username: String,
|
|
||||||
/// }
|
|
||||||
///
|
|
||||||
/// #[patch("/")]
|
|
||||||
/// async fn patch_user(
|
|
||||||
/// app_state: web::Data<AppState>,
|
|
||||||
/// user: SyncExtractor<User>,
|
|
||||||
/// web::Query(params): web::Query<Params>,
|
|
||||||
/// ) -> web::Json<User> {
|
|
||||||
/// let mut user = user.into_inner();
|
|
||||||
///
|
|
||||||
/// user.username = params.username;
|
|
||||||
///
|
|
||||||
/// match user.save(&app_state) {
|
|
||||||
/// Ok(user) => web::Json(user),
|
|
||||||
/// Err(e) => {
|
|
||||||
/// eprintln!("Failed to save user: {e}");
|
|
||||||
/// panic!();
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// }
|
|
||||||
/// ```
|
|
||||||
async fn save(&self, state: &web::Data<AppState>) -> QueryResult<User>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Implementation of [UserSave][UserSave] trait.
|
|
||||||
impl UserSave for User {
|
|
||||||
async fn save(&self, state: &web::Data<AppState>) -> QueryResult<User> {
|
|
||||||
self.save_changes::<Self>(state.get_database().await.deref_mut())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
pub async fn delete_by_username(state: &web::Data<AppState>, _username: &String) -> bool {
|
|
||||||
match diesel::delete(users.filter(username.eq(_username)))
|
|
||||||
.execute(state.get_database().await.deref_mut())
|
|
||||||
{
|
|
||||||
Ok(count) => count > 0,
|
|
||||||
Err(_) => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
pub async fn insert_or_ignore(state: &web::Data<AppState>, user: &User) -> QueryResult<usize> {
|
|
||||||
insert_into(users)
|
|
||||||
.values(user)
|
|
||||||
.on_conflict_do_nothing()
|
|
||||||
.execute(state.get_database().await.deref_mut())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,3 +0,0 @@
|
|||||||
pub mod driver;
|
|
||||||
pub mod models;
|
|
||||||
pub mod schema;
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
use actix_macros::ResponderJson;
|
|
||||||
use diesel::QueryId;
|
|
||||||
use diesel::prelude::*;
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use utoipa::ToSchema;
|
|
||||||
|
|
||||||
#[derive(
|
|
||||||
Copy, Clone, PartialEq, Debug, Serialize, Deserialize, diesel_derive_enum::DbEnum, ToSchema,
|
|
||||||
)]
|
|
||||||
#[ExistingTypePath = "crate::database::schema::sql_types::UserRole"]
|
|
||||||
#[DbValueStyle = "UPPERCASE"]
|
|
||||||
#[serde(rename_all = "UPPERCASE")]
|
|
||||||
pub enum UserRole {
|
|
||||||
Student,
|
|
||||||
Teacher,
|
|
||||||
Admin,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(
|
|
||||||
Identifiable,
|
|
||||||
AsChangeset,
|
|
||||||
Queryable,
|
|
||||||
QueryId,
|
|
||||||
Selectable,
|
|
||||||
Serialize,
|
|
||||||
Insertable,
|
|
||||||
Debug,
|
|
||||||
ToSchema,
|
|
||||||
ResponderJson,
|
|
||||||
)]
|
|
||||||
#[diesel(table_name = crate::database::schema::users)]
|
|
||||||
#[diesel(treat_none_as_null = true)]
|
|
||||||
pub struct User {
|
|
||||||
/// Account UUID.
|
|
||||||
pub id: String,
|
|
||||||
|
|
||||||
/// User name.
|
|
||||||
pub username: String,
|
|
||||||
|
|
||||||
/// BCrypt password hash.
|
|
||||||
pub password: Option<String>,
|
|
||||||
|
|
||||||
/// ID of the linked VK account.
|
|
||||||
pub vk_id: Option<i32>,
|
|
||||||
|
|
||||||
/// JWT access token.
|
|
||||||
pub access_token: Option<String>,
|
|
||||||
|
|
||||||
/// Group.
|
|
||||||
pub group: Option<String>,
|
|
||||||
|
|
||||||
/// Role.
|
|
||||||
pub role: UserRole,
|
|
||||||
|
|
||||||
/// Version of the installed Polytechnic+ application.
|
|
||||||
pub android_version: Option<String>,
|
|
||||||
|
|
||||||
/// ID of the linked Telegram account.
|
|
||||||
pub telegram_id: Option<i64>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(
|
|
||||||
Debug,
|
|
||||||
Clone,
|
|
||||||
Serialize,
|
|
||||||
Identifiable,
|
|
||||||
Queryable,
|
|
||||||
Selectable,
|
|
||||||
Insertable,
|
|
||||||
AsChangeset,
|
|
||||||
Associations,
|
|
||||||
ToSchema,
|
|
||||||
ResponderJson,
|
|
||||||
)]
|
|
||||||
#[diesel(belongs_to(User))]
|
|
||||||
#[diesel(table_name = crate::database::schema::fcm)]
|
|
||||||
#[diesel(primary_key(user_id))]
|
|
||||||
pub struct FCM {
|
|
||||||
/// Account UUID.
|
|
||||||
pub user_id: String,
|
|
||||||
|
|
||||||
/// FCM token.
|
|
||||||
pub token: String,
|
|
||||||
|
|
||||||
/// List of topics subscribed to by the user.
|
|
||||||
pub topics: Vec<Option<String>>,
|
|
||||||
}
|
|
||||||
@@ -1,39 +0,0 @@
|
|||||||
// @generated automatically by Diesel CLI.
|
|
||||||
|
|
||||||
pub mod sql_types {
|
|
||||||
#[derive(diesel::query_builder::QueryId, Clone, diesel::sql_types::SqlType)]
|
|
||||||
#[diesel(postgres_type(name = "user_role"))]
|
|
||||||
pub struct UserRole;
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
fcm (user_id) {
|
|
||||||
user_id -> Text,
|
|
||||||
token -> Text,
|
|
||||||
topics -> Array<Nullable<Text>>,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::table! {
|
|
||||||
use diesel::sql_types::*;
|
|
||||||
use super::sql_types::UserRole;
|
|
||||||
|
|
||||||
users (id) {
|
|
||||||
id -> Text,
|
|
||||||
username -> Text,
|
|
||||||
password -> Nullable<Text>,
|
|
||||||
vk_id -> Nullable<Int4>,
|
|
||||||
access_token -> Nullable<Text>,
|
|
||||||
group -> Nullable<Text>,
|
|
||||||
role -> UserRole,
|
|
||||||
android_version -> Nullable<Text>,
|
|
||||||
telegram_id -> Nullable<Int8>,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
diesel::joinable!(fcm -> users (user_id));
|
|
||||||
|
|
||||||
diesel::allow_tables_to_appear_in_same_query!(
|
|
||||||
fcm,
|
|
||||||
users,
|
|
||||||
);
|
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
use crate::database::driver;
|
|
||||||
use crate::database::models::User;
|
|
||||||
use crate::extractors::base::FromRequestAsync;
|
use crate::extractors::base::FromRequestAsync;
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
use crate::utility::jwt;
|
use crate::utility::jwt;
|
||||||
@@ -8,6 +6,8 @@ use actix_web::body::BoxBody;
|
|||||||
use actix_web::dev::Payload;
|
use actix_web::dev::Payload;
|
||||||
use actix_web::http::header;
|
use actix_web::http::header;
|
||||||
use actix_web::{web, HttpRequest};
|
use actix_web::{web, HttpRequest};
|
||||||
|
use database::entity::User;
|
||||||
|
use database::query::Query;
|
||||||
use derive_more::Display;
|
use derive_more::Display;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use std::fmt::Debug;
|
use std::fmt::Debug;
|
||||||
@@ -88,10 +88,20 @@ impl FromRequestAsync for User {
|
|||||||
let user_id = jwt::verify_and_decode(&access_token)
|
let user_id = jwt::verify_and_decode(&access_token)
|
||||||
.map_err(|_| Error::InvalidAccessToken.into_err())?;
|
.map_err(|_| Error::InvalidAccessToken.into_err())?;
|
||||||
|
|
||||||
let app_state = req.app_data::<web::Data<AppState>>().unwrap();
|
let db = req
|
||||||
|
.app_data::<web::Data<AppState>>()
|
||||||
|
.unwrap()
|
||||||
|
.get_database();
|
||||||
|
|
||||||
driver::users::get(app_state, &user_id)
|
Query::find_user_by_id(db, &user_id)
|
||||||
.await
|
.await
|
||||||
.map_err(|_| Error::NoUser.into())
|
.map_err(|_| Error::NoUser.into())
|
||||||
|
.and_then(|user| {
|
||||||
|
if let Some(user) = user {
|
||||||
|
Ok(user)
|
||||||
|
} else {
|
||||||
|
Err(actix_web::Error::from(Error::NoUser))
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ use std::future::{Ready, ready};
|
|||||||
use std::ops;
|
use std::ops;
|
||||||
|
|
||||||
/// # Async extractor.
|
/// # Async extractor.
|
||||||
|
|
||||||
/// Asynchronous object extractor from a query.
|
/// Asynchronous object extractor from a query.
|
||||||
pub struct AsyncExtractor<T>(T);
|
pub struct AsyncExtractor<T>(T);
|
||||||
|
|
||||||
@@ -80,7 +79,6 @@ impl<T: FromRequestAsync> FromRequest for AsyncExtractor<T> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// # Sync extractor.
|
/// # Sync extractor.
|
||||||
|
|
||||||
/// Synchronous object extractor from a query.
|
/// Synchronous object extractor from a query.
|
||||||
pub struct SyncExtractor<T>(T);
|
pub struct SyncExtractor<T>(T);
|
||||||
|
|
||||||
|
|||||||
@@ -12,8 +12,6 @@ use utoipa_rapidoc::RapiDoc;
|
|||||||
|
|
||||||
mod state;
|
mod state;
|
||||||
|
|
||||||
mod database;
|
|
||||||
|
|
||||||
mod extractors;
|
mod extractors;
|
||||||
mod middlewares;
|
mod middlewares;
|
||||||
mod routes;
|
mod routes;
|
||||||
@@ -72,7 +70,7 @@ pub fn get_api_scope<
|
|||||||
async fn async_main() -> io::Result<()> {
|
async fn async_main() -> io::Result<()> {
|
||||||
info!("Запуск сервера...");
|
info!("Запуск сервера...");
|
||||||
|
|
||||||
let app_state = new_app_state().await.unwrap();
|
let app_state = new_app_state(None).await.unwrap();
|
||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
let (app, api) = App::new()
|
let (app, api) = App::new()
|
||||||
@@ -111,7 +109,7 @@ fn main() -> io::Result<()> {
|
|||||||
},
|
},
|
||||||
));
|
));
|
||||||
|
|
||||||
dotenv().unwrap();
|
let _ = dotenv();
|
||||||
|
|
||||||
env_logger::init();
|
env_logger::init();
|
||||||
|
|
||||||
|
|||||||
@@ -1,25 +1,20 @@
|
|||||||
use crate::database::models::User;
|
|
||||||
use crate::extractors::authorized_user;
|
use crate::extractors::authorized_user;
|
||||||
use crate::extractors::base::FromRequestAsync;
|
use crate::extractors::base::FromRequestAsync;
|
||||||
use actix_web::body::{BoxBody, EitherBody};
|
use actix_web::body::{BoxBody, EitherBody};
|
||||||
use actix_web::dev::{Payload, Service, ServiceRequest, ServiceResponse, Transform, forward_ready};
|
use actix_web::dev::{forward_ready, Payload, Service, ServiceRequest, ServiceResponse, Transform};
|
||||||
use actix_web::{Error, HttpRequest, ResponseError};
|
use actix_web::{Error, HttpRequest, ResponseError};
|
||||||
|
use database::entity::User;
|
||||||
use futures_util::future::LocalBoxFuture;
|
use futures_util::future::LocalBoxFuture;
|
||||||
use std::future::{Ready, ready};
|
use std::future::{ready, Ready};
|
||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
/// Middleware guard working with JWT tokens.
|
/// Middleware guard working with JWT tokens.
|
||||||
|
#[derive(Default)]
|
||||||
pub struct JWTAuthorization {
|
pub struct JWTAuthorization {
|
||||||
/// List of ignored endpoints.
|
/// List of ignored endpoints.
|
||||||
pub ignore: &'static [&'static str],
|
pub ignore: &'static [&'static str],
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for JWTAuthorization {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self { ignore: &[] }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<S, B> Transform<S, ServiceRequest> for JWTAuthorization
|
impl<S, B> Transform<S, ServiceRequest> for JWTAuthorization
|
||||||
where
|
where
|
||||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
|
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
|
||||||
@@ -70,8 +65,8 @@ where
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(other) = path.as_bytes().iter().nth(ignore.len()) {
|
if let Some(other) = path.as_bytes().get(ignore.len()) {
|
||||||
return ['?' as u8, '/' as u8].contains(other);
|
return [b'?', b'/'].contains(other);
|
||||||
}
|
}
|
||||||
|
|
||||||
true
|
true
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
use actix_web::Error;
|
|
||||||
use actix_web::body::{BoxBody, EitherBody};
|
use actix_web::body::{BoxBody, EitherBody};
|
||||||
use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready};
|
use actix_web::dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform};
|
||||||
use actix_web::http::header;
|
use actix_web::http::header;
|
||||||
use actix_web::http::header::HeaderValue;
|
use actix_web::http::header::HeaderValue;
|
||||||
|
use actix_web::Error;
|
||||||
use futures_util::future::LocalBoxFuture;
|
use futures_util::future::LocalBoxFuture;
|
||||||
use std::future::{Ready, ready};
|
use std::future::{ready, Ready};
|
||||||
|
|
||||||
/// Middleware to specify the encoding in the Content-Type header.
|
/// Middleware to specify the encoding in the Content-Type header.
|
||||||
pub struct ContentTypeBootstrap;
|
pub struct ContentTypeBootstrap;
|
||||||
@@ -30,7 +30,7 @@ pub struct ContentTypeMiddleware<S> {
|
|||||||
service: S,
|
service: S,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a, S, B> Service<ServiceRequest> for ContentTypeMiddleware<S>
|
impl<S, B> Service<ServiceRequest> for ContentTypeMiddleware<S>
|
||||||
where
|
where
|
||||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
@@ -49,13 +49,14 @@ where
|
|||||||
let mut response = fut.await?;
|
let mut response = fut.await?;
|
||||||
|
|
||||||
let headers = response.response_mut().headers_mut();
|
let headers = response.response_mut().headers_mut();
|
||||||
if let Some(content_type) = headers.get("Content-Type") {
|
|
||||||
if content_type == "application/json" {
|
if let Some(content_type) = headers.get("Content-Type")
|
||||||
headers.insert(
|
&& content_type == "application/json"
|
||||||
header::CONTENT_TYPE,
|
{
|
||||||
HeaderValue::from_static("application/json; charset=utf8"),
|
headers.insert(
|
||||||
);
|
header::CONTENT_TYPE,
|
||||||
}
|
HeaderValue::from_static("application/json; charset=utf8"),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(response.map_into_left_body())
|
Ok(response.map_into_left_body())
|
||||||
|
|||||||
@@ -22,7 +22,7 @@ struct Claims {
|
|||||||
|
|
||||||
#[derive(Debug, PartialEq)]
|
#[derive(Debug, PartialEq)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
JwtError(ErrorKind),
|
Jwt(ErrorKind),
|
||||||
InvalidSignature,
|
InvalidSignature,
|
||||||
InvalidToken,
|
InvalidToken,
|
||||||
Expired,
|
Expired,
|
||||||
@@ -49,10 +49,10 @@ const VK_PUBLIC_KEY: &str = concat!(
|
|||||||
"-----END PUBLIC KEY-----"
|
"-----END PUBLIC KEY-----"
|
||||||
);
|
);
|
||||||
|
|
||||||
pub fn parse_vk_id(token_str: &String, client_id: i32) -> Result<i32, Error> {
|
pub fn parse_vk_id(token_str: &str, client_id: i32) -> Result<i32, Error> {
|
||||||
let dkey = DecodingKey::from_rsa_pem(VK_PUBLIC_KEY.as_bytes()).unwrap();
|
let dkey = DecodingKey::from_rsa_pem(VK_PUBLIC_KEY.as_bytes()).unwrap();
|
||||||
|
|
||||||
match decode::<Claims>(&token_str, &dkey, &Validation::new(Algorithm::RS256)) {
|
match decode::<Claims>(token_str, &dkey, &Validation::new(Algorithm::RS256)) {
|
||||||
Ok(token_data) => {
|
Ok(token_data) => {
|
||||||
let claims = token_data.claims;
|
let claims = token_data.claims;
|
||||||
|
|
||||||
@@ -77,7 +77,7 @@ pub fn parse_vk_id(token_str: &String, client_id: i32) -> Result<i32, Error> {
|
|||||||
ErrorKind::Base64(_) => Error::InvalidToken,
|
ErrorKind::Base64(_) => Error::InvalidToken,
|
||||||
ErrorKind::Json(_) => Error::InvalidToken,
|
ErrorKind::Json(_) => Error::InvalidToken,
|
||||||
ErrorKind::Utf8(_) => Error::InvalidToken,
|
ErrorKind::Utf8(_) => Error::InvalidToken,
|
||||||
kind => Error::JwtError(kind),
|
kind => Error::Jwt(kind),
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,34 @@
|
|||||||
use self::schema::*;
|
use self::schema::*;
|
||||||
use crate::database::driver;
|
|
||||||
use crate::database::driver::users::UserSave;
|
|
||||||
use crate::routes::auth::shared::parse_vk_id;
|
use crate::routes::auth::shared::parse_vk_id;
|
||||||
use crate::routes::auth::sign_in::schema::SignInData::{Default, VkOAuth};
|
use crate::routes::auth::sign_in::schema::SignInData::{Default, VkOAuth};
|
||||||
use crate::routes::schema::ResponseError;
|
|
||||||
use crate::routes::schema::user::UserResponse;
|
use crate::routes::schema::user::UserResponse;
|
||||||
use crate::{AppState, utility};
|
use crate::routes::schema::ResponseError;
|
||||||
|
use crate::{utility, AppState};
|
||||||
use actix_web::{post, web};
|
use actix_web::{post, web};
|
||||||
|
use database::query::Query;
|
||||||
use web::Json;
|
use web::Json;
|
||||||
|
|
||||||
async fn sign_in_combined(
|
async fn sign_in_combined(
|
||||||
data: SignInData,
|
data: SignInData,
|
||||||
app_state: &web::Data<AppState>,
|
app_state: &web::Data<AppState>,
|
||||||
) -> Result<UserResponse, ErrorCode> {
|
) -> Result<UserResponse, ErrorCode> {
|
||||||
|
let db = app_state.get_database();
|
||||||
|
|
||||||
let user = match &data {
|
let user = match &data {
|
||||||
Default(data) => driver::users::get_by_username(&app_state, &data.username).await,
|
Default(data) => Query::find_user_by_username(db, &data.username).await,
|
||||||
VkOAuth(id) => driver::users::get_by_vk_id(&app_state, *id).await,
|
VkOAuth(id) => Query::find_user_by_vk_id(db, *id).await,
|
||||||
};
|
}
|
||||||
|
.ok()
|
||||||
|
.flatten();
|
||||||
|
|
||||||
match user {
|
match user {
|
||||||
Ok(mut user) => {
|
Some(user) => {
|
||||||
if let Default(data) = data {
|
if let Default(data) = data {
|
||||||
if user.password.is_none() {
|
if user.password.is_none() {
|
||||||
return Err(ErrorCode::IncorrectCredentials);
|
return Err(ErrorCode::IncorrectCredentials);
|
||||||
}
|
}
|
||||||
|
|
||||||
match bcrypt::verify(&data.password, &user.password.as_ref().unwrap()) {
|
match bcrypt::verify(&data.password, user.password.as_ref().unwrap()) {
|
||||||
Ok(result) => {
|
Ok(result) => {
|
||||||
if !result {
|
if !result {
|
||||||
return Err(ErrorCode::IncorrectCredentials);
|
return Err(ErrorCode::IncorrectCredentials);
|
||||||
@@ -37,14 +40,11 @@ async fn sign_in_combined(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
user.access_token = Some(utility::jwt::encode(&user.id));
|
let access_token = utility::jwt::encode(&user.id);
|
||||||
|
Ok(UserResponse::from_user_with_token(user, access_token))
|
||||||
user.save(&app_state).await.expect("Failed to update user");
|
|
||||||
|
|
||||||
Ok(user.into())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Err(_) => Err(ErrorCode::IncorrectCredentials),
|
None => Err(ErrorCode::IncorrectCredentials),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -124,8 +124,6 @@ mod schema {
|
|||||||
InvalidVkAccessToken,
|
InvalidVkAccessToken,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Internal
|
|
||||||
|
|
||||||
/// Type of authorization.
|
/// Type of authorization.
|
||||||
pub enum SignInData {
|
pub enum SignInData {
|
||||||
/// User and password name and password.
|
/// User and password name and password.
|
||||||
@@ -139,16 +137,16 @@ mod schema {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::schema::*;
|
use super::schema::*;
|
||||||
use crate::database::driver;
|
|
||||||
use crate::database::models::{User, UserRole};
|
|
||||||
use crate::routes::auth::sign_in::sign_in;
|
use crate::routes::auth::sign_in::sign_in;
|
||||||
use crate::test_env::tests::{static_app_state, test_app_state, test_env};
|
use crate::test_env::tests::{static_app_state, test_app_state, test_env};
|
||||||
use crate::utility;
|
|
||||||
use actix_test::test_app;
|
use actix_test::test_app;
|
||||||
use actix_web::dev::ServiceResponse;
|
use actix_web::dev::ServiceResponse;
|
||||||
use actix_web::http::Method;
|
use actix_web::http::Method;
|
||||||
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::ActiveUser;
|
||||||
|
use database::sea_orm::{ActiveModelTrait, Set};
|
||||||
use sha1::{Digest, Sha1};
|
use sha1::{Digest, Sha1};
|
||||||
use std::fmt::Write;
|
use std::fmt::Write;
|
||||||
|
|
||||||
@@ -182,22 +180,24 @@ mod tests {
|
|||||||
test_env();
|
test_env();
|
||||||
|
|
||||||
let app_state = static_app_state().await;
|
let app_state = static_app_state().await;
|
||||||
driver::users::insert_or_ignore(
|
|
||||||
&app_state,
|
let active_user = ActiveUser {
|
||||||
&User {
|
id: Set(id.clone()),
|
||||||
id: id.clone(),
|
username: Set(username),
|
||||||
username,
|
password: Set(Some(
|
||||||
password: Some(bcrypt::hash("example".to_string(), bcrypt::DEFAULT_COST).unwrap()),
|
bcrypt::hash("example".to_string(), bcrypt::DEFAULT_COST).unwrap(),
|
||||||
vk_id: None,
|
)),
|
||||||
telegram_id: None,
|
vk_id: Set(None),
|
||||||
access_token: Some(utility::jwt::encode(&id)),
|
telegram_id: Set(None),
|
||||||
group: Some("ИС-214/23".to_string()),
|
group: Set(Some("ИС-214/23".to_string())),
|
||||||
role: UserRole::Student,
|
role: Set(UserRole::Student),
|
||||||
android_version: None,
|
android_version: Set(None),
|
||||||
},
|
};
|
||||||
)
|
|
||||||
.await
|
active_user
|
||||||
.unwrap();
|
.save(app_state.get_database())
|
||||||
|
.await
|
||||||
|
.expect("Failed to save user");
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_web::test]
|
#[actix_web::test]
|
||||||
|
|||||||
@@ -1,11 +1,13 @@
|
|||||||
use self::schema::*;
|
use self::schema::*;
|
||||||
use crate::AppState;
|
|
||||||
use crate::database::driver;
|
|
||||||
use crate::database::models::UserRole;
|
|
||||||
use crate::routes::auth::shared::parse_vk_id;
|
use crate::routes::auth::shared::parse_vk_id;
|
||||||
use crate::routes::schema::ResponseError;
|
|
||||||
use crate::routes::schema::user::UserResponse;
|
use crate::routes::schema::user::UserResponse;
|
||||||
|
use crate::routes::schema::ResponseError;
|
||||||
|
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::ActiveUser;
|
||||||
|
use database::query::Query;
|
||||||
|
use database::sea_orm::ActiveModelTrait;
|
||||||
use web::Json;
|
use web::Json;
|
||||||
|
|
||||||
async fn sign_up_combined(
|
async fn sign_up_combined(
|
||||||
@@ -28,22 +30,30 @@ async fn sign_up_combined(
|
|||||||
return Err(ErrorCode::InvalidGroupName);
|
return Err(ErrorCode::InvalidGroupName);
|
||||||
}
|
}
|
||||||
|
|
||||||
// If user with specified username already exists.
|
let db = app_state.get_database();
|
||||||
if driver::users::contains_by_username(&app_state, &data.username).await {
|
|
||||||
|
// If user with specified username already exists.O
|
||||||
|
if Query::find_user_by_username(db, &data.username)
|
||||||
|
.await
|
||||||
|
.is_ok_and(|user| user.is_some())
|
||||||
|
{
|
||||||
return Err(ErrorCode::UsernameAlreadyExists);
|
return Err(ErrorCode::UsernameAlreadyExists);
|
||||||
}
|
}
|
||||||
|
|
||||||
// If user with specified VKID already exists.
|
// If user with specified VKID already exists.
|
||||||
if let Some(id) = data.vk_id {
|
if let Some(id) = data.vk_id
|
||||||
if driver::users::contains_by_vk_id(&app_state, id).await {
|
&& Query::is_user_exists_by_vk_id(db, id)
|
||||||
return Err(ErrorCode::VkAlreadyExists);
|
.await
|
||||||
}
|
.expect("Failed to check user existence")
|
||||||
|
{
|
||||||
|
return Err(ErrorCode::VkAlreadyExists);
|
||||||
}
|
}
|
||||||
|
|
||||||
let user = data.into();
|
let active_user: ActiveUser = data.into();
|
||||||
driver::users::insert(&app_state, &user).await.unwrap();
|
let user = active_user.insert(db).await.unwrap();
|
||||||
|
let access_token = utility::jwt::encode(&user.id);
|
||||||
|
|
||||||
Ok(UserResponse::from(&user)).into()
|
Ok(UserResponse::from_user_with_token(user, access_token))
|
||||||
}
|
}
|
||||||
|
|
||||||
#[utoipa::path(responses(
|
#[utoipa::path(responses(
|
||||||
@@ -101,10 +111,11 @@ pub async fn sign_up_vk(
|
|||||||
}
|
}
|
||||||
|
|
||||||
mod schema {
|
mod schema {
|
||||||
use crate::database::models::{User, UserRole};
|
|
||||||
use crate::routes::schema::user::UserResponse;
|
use crate::routes::schema::user::UserResponse;
|
||||||
use crate::utility;
|
|
||||||
use actix_macros::ErrResponse;
|
use actix_macros::ErrResponse;
|
||||||
|
use database::entity::sea_orm_active_enums::UserRole;
|
||||||
|
use database::entity::ActiveUser;
|
||||||
|
use database::sea_orm::Set;
|
||||||
use derive_more::Display;
|
use derive_more::Display;
|
||||||
use objectid::ObjectId;
|
use objectid::ObjectId;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -134,7 +145,7 @@ mod schema {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub mod vk {
|
pub mod vk {
|
||||||
use crate::database::models::UserRole;
|
use database::entity::sea_orm_active_enums::UserRole;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, utoipa::ToSchema)]
|
#[derive(Serialize, Deserialize, utoipa::ToSchema)]
|
||||||
@@ -189,8 +200,6 @@ mod schema {
|
|||||||
VkAlreadyExists,
|
VkAlreadyExists,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Internal
|
|
||||||
|
|
||||||
/// Data for registration.
|
/// Data for registration.
|
||||||
pub struct SignUpData {
|
pub struct SignUpData {
|
||||||
// TODO: сделать ограничение на минимальную и максимальную длину при регистрации и смене.
|
// TODO: сделать ограничение на минимальную и максимальную длину при регистрации и смене.
|
||||||
@@ -215,25 +224,21 @@ mod schema {
|
|||||||
pub version: String,
|
pub version: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Into<User> for SignUpData {
|
impl From<SignUpData> for ActiveUser {
|
||||||
fn into(self) -> User {
|
fn from(value: SignUpData) -> Self {
|
||||||
assert_ne!(self.password.is_some(), self.vk_id.is_some());
|
assert_ne!(value.password.is_some(), value.vk_id.is_some());
|
||||||
|
|
||||||
let id = ObjectId::new().unwrap().to_string();
|
ActiveUser {
|
||||||
let access_token = Some(utility::jwt::encode(&id));
|
id: Set(ObjectId::new().unwrap().to_string()),
|
||||||
|
username: Set(value.username),
|
||||||
User {
|
password: Set(value
|
||||||
id,
|
|
||||||
username: self.username,
|
|
||||||
password: self
|
|
||||||
.password
|
.password
|
||||||
.map(|x| bcrypt::hash(x, bcrypt::DEFAULT_COST).unwrap()),
|
.map(|x| bcrypt::hash(x, bcrypt::DEFAULT_COST).unwrap())),
|
||||||
vk_id: self.vk_id,
|
vk_id: Set(value.vk_id),
|
||||||
telegram_id: None,
|
telegram_id: Set(None),
|
||||||
access_token,
|
group: Set(Some(value.group)),
|
||||||
group: Some(self.group),
|
role: Set(value.role),
|
||||||
role: self.role,
|
android_version: Set(Some(value.version)),
|
||||||
android_version: Some(self.version),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -241,8 +246,6 @@ mod schema {
|
|||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use crate::database::driver;
|
|
||||||
use crate::database::models::UserRole;
|
|
||||||
use crate::routes::auth::sign_up::schema::Request;
|
use crate::routes::auth::sign_up::schema::Request;
|
||||||
use crate::routes::auth::sign_up::sign_up;
|
use crate::routes::auth::sign_up::sign_up;
|
||||||
use crate::test_env::tests::{static_app_state, test_app_state, test_env};
|
use crate::test_env::tests::{static_app_state, test_app_state, test_env};
|
||||||
@@ -251,6 +254,10 @@ mod tests {
|
|||||||
use actix_web::http::Method;
|
use actix_web::http::Method;
|
||||||
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::{UserColumn, UserEntity};
|
||||||
|
use database::sea_orm::ColumnTrait;
|
||||||
|
use database::sea_orm::{EntityTrait, QueryFilter};
|
||||||
|
|
||||||
struct SignUpPartial<'a> {
|
struct SignUpPartial<'a> {
|
||||||
username: &'a str,
|
username: &'a str,
|
||||||
@@ -282,7 +289,12 @@ mod tests {
|
|||||||
test_env();
|
test_env();
|
||||||
|
|
||||||
let app_state = static_app_state().await;
|
let app_state = static_app_state().await;
|
||||||
driver::users::delete_by_username(&app_state, &"test::sign_up_valid".to_string()).await;
|
|
||||||
|
UserEntity::delete_many()
|
||||||
|
.filter(UserColumn::Username.eq("test::sign_up_valid"))
|
||||||
|
.exec(app_state.get_database())
|
||||||
|
.await
|
||||||
|
.expect("Failed to delete user");
|
||||||
|
|
||||||
// test
|
// test
|
||||||
|
|
||||||
@@ -303,7 +315,12 @@ mod tests {
|
|||||||
test_env();
|
test_env();
|
||||||
|
|
||||||
let app_state = static_app_state().await;
|
let app_state = static_app_state().await;
|
||||||
driver::users::delete_by_username(&app_state, &"test::sign_up_multiple".to_string()).await;
|
|
||||||
|
UserEntity::delete_many()
|
||||||
|
.filter(UserColumn::Username.eq("test::sign_up_multiple"))
|
||||||
|
.exec(app_state.get_database())
|
||||||
|
.await
|
||||||
|
.expect("Failed to delete user");
|
||||||
|
|
||||||
let create = sign_up_client(SignUpPartial {
|
let create = sign_up_client(SignUpPartial {
|
||||||
username: "test::sign_up_multiple",
|
username: "test::sign_up_multiple",
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
use self::schema::*;
|
use self::schema::*;
|
||||||
use crate::database::driver;
|
|
||||||
use crate::database::driver::users::UserSave;
|
|
||||||
use crate::database::models::{User, UserRole};
|
|
||||||
use crate::routes::schema::ResponseError;
|
use crate::routes::schema::ResponseError;
|
||||||
use crate::utility::telegram::{WebAppInitDataMap, WebAppUser};
|
use crate::utility::telegram::{WebAppInitDataMap, WebAppUser};
|
||||||
use crate::{AppState, utility};
|
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::ActiveUser;
|
||||||
|
use database::query::Query;
|
||||||
|
use database::sea_orm::{ActiveModelTrait, Set};
|
||||||
use objectid::ObjectId;
|
use objectid::ObjectId;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use web::Json;
|
use web::Json;
|
||||||
@@ -22,10 +23,6 @@ pub async fn telegram_auth(
|
|||||||
) -> ServiceResponse {
|
) -> ServiceResponse {
|
||||||
let init_data = WebAppInitDataMap::from_str(data_json.into_inner().init_data);
|
let init_data = WebAppInitDataMap::from_str(data_json.into_inner().init_data);
|
||||||
|
|
||||||
// for (key, value) in &init_data.data_map {
|
|
||||||
// println!("key: {} | value: {}", key, value);
|
|
||||||
// }
|
|
||||||
|
|
||||||
{
|
{
|
||||||
let env = &app_state.get_env().telegram;
|
let env = &app_state.get_env().telegram;
|
||||||
|
|
||||||
@@ -52,39 +49,32 @@ pub async fn telegram_auth(
|
|||||||
let web_app_user =
|
let web_app_user =
|
||||||
serde_json::from_str::<WebAppUser>(init_data.data_map.get("user").unwrap()).unwrap();
|
serde_json::from_str::<WebAppUser>(init_data.data_map.get("user").unwrap()).unwrap();
|
||||||
|
|
||||||
let mut user = {
|
let user = match Query::find_user_by_telegram_id(app_state.get_database(), web_app_user.id)
|
||||||
match driver::users::get_by_telegram_id(&app_state, web_app_user.id).await {
|
.await
|
||||||
Ok(value) => Ok(value),
|
.expect("Failed to find user by telegram id")
|
||||||
Err(_) => {
|
{
|
||||||
let new_user = User {
|
Some(value) => value,
|
||||||
id: ObjectId::new().unwrap().to_string(),
|
None => {
|
||||||
username: format!("telegram_{}", web_app_user.id), // можно оставить, а можно поменять
|
let new_user = ActiveUser {
|
||||||
password: None, // ибо нехуй
|
id: Set(ObjectId::new().unwrap().to_string()),
|
||||||
vk_id: None,
|
username: Set(format!("telegram_{}", web_app_user.id)), // можно оставить, а можно поменять
|
||||||
telegram_id: Some(web_app_user.id),
|
password: Set(None), // ибо нехуй
|
||||||
access_token: None, // установится ниже
|
vk_id: Set(None),
|
||||||
group: None,
|
telegram_id: Set(Some(web_app_user.id)),
|
||||||
role: UserRole::Student, // TODO: при реге проверять данные
|
group: Set(None),
|
||||||
android_version: None,
|
role: Set(UserRole::Student), // TODO: при реге проверять данные
|
||||||
};
|
android_version: Set(None),
|
||||||
|
};
|
||||||
|
|
||||||
driver::users::insert(&app_state, &new_user)
|
new_user
|
||||||
.await
|
.insert(app_state.get_database())
|
||||||
.map(|_| new_user)
|
.await
|
||||||
}
|
.expect("Failed to insert user")
|
||||||
}
|
}
|
||||||
.expect("Failed to get or add user")
|
|
||||||
};
|
};
|
||||||
|
|
||||||
user.access_token = Some(utility::jwt::encode(&user.id));
|
let access_token = utility::jwt::encode(&user.id);
|
||||||
|
Ok(Response::new(&access_token, user.group.is_some())).into()
|
||||||
user.save(&app_state).await.expect("Failed to update user");
|
|
||||||
|
|
||||||
Ok(Response::new(
|
|
||||||
&*user.access_token.unwrap(),
|
|
||||||
user.group.is_some(),
|
|
||||||
))
|
|
||||||
.into()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
mod schema {
|
mod schema {
|
||||||
@@ -93,9 +83,9 @@ mod schema {
|
|||||||
use crate::utility::telegram::VerifyError;
|
use crate::utility::telegram::VerifyError;
|
||||||
use actix_macros::ErrResponse;
|
use actix_macros::ErrResponse;
|
||||||
use actix_web::body::EitherBody;
|
use actix_web::body::EitherBody;
|
||||||
use actix_web::cookie::CookieBuilder;
|
|
||||||
use actix_web::cookie::time::OffsetDateTime;
|
use actix_web::cookie::time::OffsetDateTime;
|
||||||
use actix_web::{HttpRequest, HttpResponse, web};
|
use actix_web::cookie::CookieBuilder;
|
||||||
|
use actix_web::{web, HttpRequest, HttpResponse};
|
||||||
use derive_more::Display;
|
use derive_more::Display;
|
||||||
use serde::{Deserialize, Serialize, Serializer};
|
use serde::{Deserialize, Serialize, Serializer};
|
||||||
use std::ops::Add;
|
use std::ops::Add;
|
||||||
@@ -114,8 +104,8 @@ mod schema {
|
|||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
#[schema(as = Flow::TelegramAuth::Response)]
|
#[schema(as = Flow::TelegramAuth::Response)]
|
||||||
pub struct Response {
|
pub struct Response {
|
||||||
#[serde(skip)]
|
// #[serde(skip)] // TODO: я пока не придумал как не отдавать сырой токен в ответе
|
||||||
#[schema(ignore)]
|
// #[schema(ignore)]
|
||||||
access_token: String,
|
access_token: String,
|
||||||
|
|
||||||
pub completed: bool,
|
pub completed: bool,
|
||||||
@@ -135,7 +125,7 @@ mod schema {
|
|||||||
&mut self,
|
&mut self,
|
||||||
request: &HttpRequest,
|
request: &HttpRequest,
|
||||||
response: &mut HttpResponse<EitherBody<String>>,
|
response: &mut HttpResponse<EitherBody<String>>,
|
||||||
) -> () {
|
) {
|
||||||
let access_token = &self.access_token;
|
let access_token = &self.access_token;
|
||||||
|
|
||||||
let app_state = request.app_data::<web::Data<AppState>>().unwrap();
|
let app_state = request.app_data::<web::Data<AppState>>().unwrap();
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
use self::schema::*;
|
use self::schema::*;
|
||||||
use crate::AppState;
|
|
||||||
use crate::database::driver;
|
|
||||||
use crate::database::driver::users::UserSave;
|
|
||||||
use crate::database::models::User;
|
|
||||||
use crate::extractors::base::AsyncExtractor;
|
use crate::extractors::base::AsyncExtractor;
|
||||||
use crate::routes::schema::ResponseError;
|
use crate::routes::schema::ResponseError;
|
||||||
|
use crate::AppState;
|
||||||
use actix_web::{post, web};
|
use actix_web::{post, web};
|
||||||
|
use database::entity::User;
|
||||||
|
use database::query::Query;
|
||||||
|
use database::sea_orm::{ActiveModelTrait, IntoActiveModel, Set};
|
||||||
use web::Json;
|
use web::Json;
|
||||||
|
|
||||||
#[utoipa::path(responses(
|
#[utoipa::path(responses(
|
||||||
@@ -20,7 +20,7 @@ pub async fn telegram_complete(
|
|||||||
app_state: web::Data<AppState>,
|
app_state: web::Data<AppState>,
|
||||||
user: AsyncExtractor<User>,
|
user: AsyncExtractor<User>,
|
||||||
) -> ServiceResponse {
|
) -> ServiceResponse {
|
||||||
let mut user = user.into_inner();
|
let user = user.into_inner();
|
||||||
|
|
||||||
// проверка на перезапись уже имеющихся данных
|
// проверка на перезапись уже имеющихся данных
|
||||||
if user.group.is_some() {
|
if user.group.is_some() {
|
||||||
@@ -29,13 +29,19 @@ pub async fn telegram_complete(
|
|||||||
|
|
||||||
let data = data.into_inner();
|
let data = data.into_inner();
|
||||||
|
|
||||||
|
let db = app_state.get_database();
|
||||||
|
let mut active_user = user.clone().into_active_model();
|
||||||
|
|
||||||
// замена существующего имени, если оно отличается
|
// замена существующего имени, если оно отличается
|
||||||
if user.username != data.username {
|
if user.username != data.username {
|
||||||
if driver::users::contains_by_username(&app_state, &data.username).await {
|
if Query::is_user_exists_by_username(db, &data.username)
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
{
|
||||||
return Err(ErrorCode::UsernameAlreadyExists).into();
|
return Err(ErrorCode::UsernameAlreadyExists).into();
|
||||||
}
|
}
|
||||||
|
|
||||||
user.username = data.username;
|
active_user.username = Set(data.username);
|
||||||
}
|
}
|
||||||
|
|
||||||
// проверка на существование группы
|
// проверка на существование группы
|
||||||
@@ -50,9 +56,12 @@ pub async fn telegram_complete(
|
|||||||
return Err(ErrorCode::InvalidGroupName).into();
|
return Err(ErrorCode::InvalidGroupName).into();
|
||||||
}
|
}
|
||||||
|
|
||||||
user.group = Some(data.group);
|
active_user.group = Set(Some(data.group));
|
||||||
|
|
||||||
user.save(&app_state).await.expect("Failed to update user");
|
active_user
|
||||||
|
.update(db)
|
||||||
|
.await
|
||||||
|
.expect("Failed to update user");
|
||||||
|
|
||||||
Ok(()).into()
|
Ok(()).into()
|
||||||
}
|
}
|
||||||
@@ -80,11 +89,11 @@ mod schema {
|
|||||||
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
|
||||||
#[schema(as = Flow::TelegramFill::ErrorCode)]
|
#[schema(as = Flow::TelegramFill::ErrorCode)]
|
||||||
pub enum ErrorCode {
|
pub enum ErrorCode {
|
||||||
#[display("This flow already completed.")]
|
#[display("This flow is already completed.")]
|
||||||
#[status_code = "actix_web::http::StatusCode::CONFLICT"]
|
#[status_code = "actix_web::http::StatusCode::CONFLICT"]
|
||||||
AlreadyCompleted,
|
AlreadyCompleted,
|
||||||
|
|
||||||
#[display("Username is already exists.")]
|
#[display("User with that name already exists.")]
|
||||||
#[status_code = "actix_web::http::StatusCode::BAD_REQUEST"]
|
#[status_code = "actix_web::http::StatusCode::BAD_REQUEST"]
|
||||||
UsernameAlreadyExists,
|
UsernameAlreadyExists,
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,17 @@
|
|||||||
use crate::AppState;
|
|
||||||
use crate::routes::schedule::schema::CacheStatus;
|
use crate::routes::schedule::schema::CacheStatus;
|
||||||
|
use crate::AppState;
|
||||||
use actix_web::{get, web};
|
use actix_web::{get, web};
|
||||||
|
use std::ops::Deref;
|
||||||
|
|
||||||
#[utoipa::path(responses(
|
#[utoipa::path(responses(
|
||||||
(status = OK, body = CacheStatus),
|
(status = OK, body = CacheStatus),
|
||||||
))]
|
))]
|
||||||
#[get("/cache-status")]
|
#[get("/cache-status")]
|
||||||
pub async fn cache_status(app_state: web::Data<AppState>) -> CacheStatus {
|
pub async fn cache_status(app_state: web::Data<AppState>) -> CacheStatus {
|
||||||
CacheStatus::from(&app_state).await.into()
|
app_state
|
||||||
|
.get_schedule_snapshot("eng_polytechnic")
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.deref()
|
||||||
|
.into()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
use self::schema::*;
|
use self::schema::*;
|
||||||
use crate::AppState;
|
use crate::AppState;
|
||||||
use crate::database::models::User;
|
|
||||||
use crate::extractors::base::AsyncExtractor;
|
use crate::extractors::base::AsyncExtractor;
|
||||||
use crate::routes::schedule::schema::ScheduleEntryResponse;
|
use crate::routes::schedule::schema::ScheduleEntryResponse;
|
||||||
use crate::routes::schema::ResponseError;
|
use crate::routes::schema::ResponseError;
|
||||||
use actix_web::{get, web};
|
use actix_web::{get, web};
|
||||||
|
use database::entity::User;
|
||||||
|
|
||||||
#[utoipa::path(responses(
|
#[utoipa::path(responses(
|
||||||
(status = OK, body = ScheduleEntryResponse),
|
(status = OK, body = ScheduleEntryResponse),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
mod cache_status;
|
mod cache_status;
|
||||||
mod group;
|
mod group;
|
||||||
mod group_names;
|
mod group_names;
|
||||||
mod schedule;
|
mod get;
|
||||||
mod schema;
|
mod schema;
|
||||||
mod teacher;
|
mod teacher;
|
||||||
mod teacher_names;
|
mod teacher_names;
|
||||||
@@ -9,6 +9,6 @@ mod teacher_names;
|
|||||||
pub use cache_status::*;
|
pub use cache_status::*;
|
||||||
pub use group::*;
|
pub use group::*;
|
||||||
pub use group_names::*;
|
pub use group_names::*;
|
||||||
pub use schedule::*;
|
pub use get::*;
|
||||||
pub use teacher::*;
|
pub use teacher::*;
|
||||||
pub use teacher_names::*;
|
pub use teacher_names::*;
|
||||||
|
|||||||
@@ -63,18 +63,6 @@ pub struct CacheStatus {
|
|||||||
pub updated_at: i64,
|
pub updated_at: i64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CacheStatus {
|
|
||||||
pub async fn from(value: &web::Data<AppState>) -> Self {
|
|
||||||
From::<&ScheduleSnapshot>::from(
|
|
||||||
value
|
|
||||||
.get_schedule_snapshot("eng_polytechnic")
|
|
||||||
.await
|
|
||||||
.unwrap()
|
|
||||||
.deref(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl From<&ScheduleSnapshot> for CacheStatus {
|
impl From<&ScheduleSnapshot> for CacheStatus {
|
||||||
fn from(value: &ScheduleSnapshot) -> Self {
|
fn from(value: &ScheduleSnapshot) -> Self {
|
||||||
Self {
|
Self {
|
||||||
|
|||||||
@@ -13,13 +13,13 @@ where
|
|||||||
E: Serialize + PartialSchema + Display + PartialErrResponse;
|
E: Serialize + PartialSchema + Display + PartialErrResponse;
|
||||||
|
|
||||||
/// Transform Response<T, E> into Result<T, E>
|
/// Transform Response<T, E> into Result<T, E>
|
||||||
impl<T, E> Into<Result<T, E>> for Response<T, E>
|
impl<T, E> From<Response<T, E>> for Result<T, E>
|
||||||
where
|
where
|
||||||
T: Serialize + PartialSchema + PartialOkResponse,
|
T: Serialize + PartialSchema + PartialOkResponse,
|
||||||
E: Serialize + PartialSchema + Display + PartialErrResponse,
|
E: Serialize + PartialSchema + Display + PartialErrResponse,
|
||||||
{
|
{
|
||||||
fn into(self) -> Result<T, E> {
|
fn from(value: Response<T, E>) -> Self {
|
||||||
self.0
|
value.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,7 +46,7 @@ where
|
|||||||
{
|
{
|
||||||
match &self.0 {
|
match &self.0 {
|
||||||
Ok(ok) => serializer.serialize_some(&ok),
|
Ok(ok) => serializer.serialize_some(&ok),
|
||||||
Err(err) => serializer.serialize_some(&ResponseError::<E>::from(err.clone().into())),
|
Err(err) => serializer.serialize_some(&err.clone().into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -95,7 +95,7 @@ pub trait PartialOkResponse {
|
|||||||
&mut self,
|
&mut self,
|
||||||
_request: &HttpRequest,
|
_request: &HttpRequest,
|
||||||
_response: &mut HttpResponse<EitherBody<String>>,
|
_response: &mut HttpResponse<EitherBody<String>>,
|
||||||
) -> () {
|
) {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -126,8 +126,9 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub mod user {
|
pub mod user {
|
||||||
use crate::database::models::{User, UserRole};
|
|
||||||
use actix_macros::{OkResponse, ResponderJson};
|
use actix_macros::{OkResponse, ResponderJson};
|
||||||
|
use database::entity::sea_orm_active_enums::UserRole;
|
||||||
|
use database::entity::User;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
|
|
||||||
//noinspection SpellCheckingInspection
|
//noinspection SpellCheckingInspection
|
||||||
@@ -165,17 +166,31 @@ pub mod user {
|
|||||||
pub access_token: Option<String>,
|
pub access_token: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create UserResponse from User ref.
|
impl UserResponse {
|
||||||
impl From<&User> for UserResponse {
|
pub fn from_user_with_token(user: User, access_token: String) -> Self {
|
||||||
fn from(user: &User) -> Self {
|
Self {
|
||||||
UserResponse {
|
|
||||||
id: user.id.clone(),
|
id: user.id.clone(),
|
||||||
username: user.username.clone(),
|
username: user.username.clone(),
|
||||||
group: user.group.clone(),
|
group: user.group.clone(),
|
||||||
role: user.role.clone(),
|
role: user.role.clone(),
|
||||||
vk_id: user.vk_id.clone(),
|
vk_id: user.vk_id,
|
||||||
telegram_id: user.telegram_id.clone(),
|
telegram_id: user.telegram_id,
|
||||||
access_token: user.access_token.clone(),
|
access_token: Some(access_token),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create UserResponse from User ref.
|
||||||
|
impl From<&User> for UserResponse {
|
||||||
|
fn from(user: &User) -> Self {
|
||||||
|
Self {
|
||||||
|
id: user.id.clone(),
|
||||||
|
username: user.username.clone(),
|
||||||
|
group: user.group.clone(),
|
||||||
|
role: user.role.clone(),
|
||||||
|
vk_id: user.vk_id,
|
||||||
|
telegram_id: user.telegram_id,
|
||||||
|
access_token: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -183,14 +198,14 @@ pub mod user {
|
|||||||
/// Transform User to UserResponse.
|
/// Transform User to UserResponse.
|
||||||
impl From<User> for UserResponse {
|
impl From<User> for UserResponse {
|
||||||
fn from(user: User) -> Self {
|
fn from(user: User) -> Self {
|
||||||
UserResponse {
|
Self {
|
||||||
id: user.id,
|
id: user.id,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
group: user.group,
|
group: user.group,
|
||||||
role: user.role,
|
role: user.role,
|
||||||
vk_id: user.vk_id,
|
vk_id: user.vk_id,
|
||||||
telegram_id: user.telegram_id,
|
telegram_id: user.telegram_id,
|
||||||
access_token: user.access_token,
|
access_token: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
use self::schema::*;
|
use self::schema::*;
|
||||||
use crate::database::driver::users::UserSave;
|
|
||||||
use crate::database::models::User;
|
|
||||||
use crate::extractors::base::AsyncExtractor;
|
use crate::extractors::base::AsyncExtractor;
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
use actix_web::{post, web};
|
use actix_web::{post, web};
|
||||||
|
use database::entity::User;
|
||||||
|
use database::sea_orm::{ActiveModelTrait, IntoActiveModel, Set};
|
||||||
|
|
||||||
#[utoipa::path(responses((status = OK)))]
|
#[utoipa::path(responses((status = OK)))]
|
||||||
#[post("/change-group")]
|
#[post("/change-group")]
|
||||||
@@ -12,9 +12,13 @@ pub async fn change_group(
|
|||||||
user: AsyncExtractor<User>,
|
user: AsyncExtractor<User>,
|
||||||
data: web::Json<Request>,
|
data: web::Json<Request>,
|
||||||
) -> ServiceResponse {
|
) -> ServiceResponse {
|
||||||
let mut user = user.into_inner();
|
let user = user.into_inner();
|
||||||
|
|
||||||
if user.group.is_some_and(|group| group == data.group) {
|
if user
|
||||||
|
.group
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|group| group.eq(&data.group))
|
||||||
|
{
|
||||||
return Ok(()).into();
|
return Ok(()).into();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -29,8 +33,10 @@ pub async fn change_group(
|
|||||||
return Err(ErrorCode::NotFound).into();
|
return Err(ErrorCode::NotFound).into();
|
||||||
}
|
}
|
||||||
|
|
||||||
user.group = Some(data.into_inner().group);
|
let mut active_user = user.clone().into_active_model();
|
||||||
user.save(&app_state).await.unwrap();
|
active_user.group = Set(Some(data.into_inner().group));
|
||||||
|
|
||||||
|
active_user.update(app_state.get_database()).await.unwrap();
|
||||||
|
|
||||||
Ok(()).into()
|
Ok(()).into()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
use self::schema::*;
|
use self::schema::*;
|
||||||
use crate::database::driver;
|
|
||||||
use crate::database::driver::users::UserSave;
|
|
||||||
use crate::database::models::User;
|
|
||||||
use crate::extractors::base::AsyncExtractor;
|
use crate::extractors::base::AsyncExtractor;
|
||||||
use crate::state::AppState;
|
use crate::state::AppState;
|
||||||
use actix_web::{post, web};
|
use actix_web::{post, web};
|
||||||
|
use database::entity::User;
|
||||||
|
use database::query::Query;
|
||||||
|
use database::sea_orm::{ActiveModelTrait, IntoActiveModel, Set};
|
||||||
|
|
||||||
#[utoipa::path(responses((status = OK)))]
|
#[utoipa::path(responses((status = OK)))]
|
||||||
#[post("/change-username")]
|
#[post("/change-username")]
|
||||||
@@ -13,21 +13,24 @@ pub async fn change_username(
|
|||||||
user: AsyncExtractor<User>,
|
user: AsyncExtractor<User>,
|
||||||
data: web::Json<Request>,
|
data: web::Json<Request>,
|
||||||
) -> ServiceResponse {
|
) -> ServiceResponse {
|
||||||
let mut user = user.into_inner();
|
let user = user.into_inner();
|
||||||
|
|
||||||
if user.username == data.username {
|
if user.username == data.username {
|
||||||
return Ok(()).into();
|
return Ok(()).into();
|
||||||
}
|
}
|
||||||
|
|
||||||
if driver::users::get_by_username(&app_state, &data.username)
|
let db = app_state.get_database();
|
||||||
|
|
||||||
|
if Query::is_user_exists_by_username(db, &data.username)
|
||||||
.await
|
.await
|
||||||
.is_ok()
|
.unwrap()
|
||||||
{
|
{
|
||||||
return Err(ErrorCode::AlreadyExists).into();
|
return Err(ErrorCode::AlreadyExists).into();
|
||||||
}
|
}
|
||||||
|
|
||||||
user.username = data.into_inner().username;
|
let mut active_user = user.into_active_model();
|
||||||
user.save(&app_state).await.unwrap();
|
active_user.username = Set(data.into_inner().username);
|
||||||
|
active_user.update(db).await.unwrap();
|
||||||
|
|
||||||
Ok(()).into()
|
Ok(()).into()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use crate::database::models::User;
|
|
||||||
use crate::extractors::base::AsyncExtractor;
|
use crate::extractors::base::AsyncExtractor;
|
||||||
use crate::routes::schema::user::UserResponse;
|
use crate::routes::schema::user::UserResponse;
|
||||||
use actix_web::get;
|
use actix_web::get;
|
||||||
|
use database::entity::User;
|
||||||
|
|
||||||
#[utoipa::path(responses((status = OK, body = UserResponse)))]
|
#[utoipa::path(responses((status = OK, body = UserResponse)))]
|
||||||
#[get("/me")]
|
#[get("/me")]
|
||||||
|
|||||||
@@ -2,29 +2,28 @@ mod env;
|
|||||||
|
|
||||||
pub use crate::state::env::AppEnv;
|
pub use crate::state::env::AppEnv;
|
||||||
use actix_web::web;
|
use actix_web::web;
|
||||||
use diesel::{Connection, PgConnection};
|
use database::sea_orm::{Database, DatabaseConnection};
|
||||||
use providers::base::{ScheduleProvider, ScheduleSnapshot};
|
use providers::base::{ScheduleProvider, ScheduleSnapshot};
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use tokio::sync::{Mutex, MutexGuard};
|
|
||||||
use tokio_util::sync::CancellationToken;
|
use tokio_util::sync::CancellationToken;
|
||||||
|
|
||||||
/// Common data provided to endpoints.
|
/// Common data provided to endpoints.
|
||||||
pub struct AppState {
|
pub struct AppState {
|
||||||
cancel_token: CancellationToken,
|
cancel_token: CancellationToken,
|
||||||
database: Mutex<PgConnection>,
|
database: DatabaseConnection,
|
||||||
providers: HashMap<String, Arc<dyn ScheduleProvider>>,
|
providers: HashMap<String, Arc<dyn ScheduleProvider>>,
|
||||||
env: AppEnv,
|
env: AppEnv,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AppState {
|
impl AppState {
|
||||||
pub async fn new() -> Result<Self, Box<dyn std::error::Error>> {
|
pub async fn new(
|
||||||
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
database: Option<DatabaseConnection>,
|
||||||
|
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||||
let env = AppEnv::default();
|
let env = AppEnv::default();
|
||||||
let providers: HashMap<String, Arc<dyn ScheduleProvider>> = HashMap::from([(
|
let providers: HashMap<String, Arc<dyn ScheduleProvider>> = HashMap::from([(
|
||||||
"eng_polytechnic".to_string(),
|
"eng_polytechnic".to_string(),
|
||||||
providers::EngelsPolytechnicProvider::new({
|
providers::EngelsPolytechnicProvider::get({
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
{
|
{
|
||||||
providers::EngelsPolytechnicUpdateSource::Prepared(ScheduleSnapshot {
|
providers::EngelsPolytechnicUpdateSource::Prepared(ScheduleSnapshot {
|
||||||
@@ -52,16 +51,20 @@ impl AppState {
|
|||||||
|
|
||||||
let this = Self {
|
let this = Self {
|
||||||
cancel_token: CancellationToken::new(),
|
cancel_token: CancellationToken::new(),
|
||||||
database: Mutex::new(
|
database: if let Some(database) = database {
|
||||||
PgConnection::establish(&database_url)
|
database
|
||||||
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url)),
|
} else {
|
||||||
),
|
let database_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set");
|
||||||
|
Database::connect(&database_url)
|
||||||
|
.await
|
||||||
|
.unwrap_or_else(|_| panic!("Error connecting to {}", database_url))
|
||||||
|
},
|
||||||
env,
|
env,
|
||||||
providers,
|
providers,
|
||||||
};
|
};
|
||||||
|
|
||||||
if this.env.schedule.auto_update {
|
if this.env.schedule.auto_update {
|
||||||
for (_, provider) in &this.providers {
|
for provider in this.providers.values() {
|
||||||
let provider = provider.clone();
|
let provider = provider.clone();
|
||||||
let cancel_token = this.cancel_token.clone();
|
let cancel_token = this.cancel_token.clone();
|
||||||
|
|
||||||
@@ -80,8 +83,8 @@ impl AppState {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_database(&'_ self) -> MutexGuard<'_, PgConnection> {
|
pub fn get_database(&'_ self) -> &DatabaseConnection {
|
||||||
self.database.lock().await
|
&self.database
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_env(&self) -> &AppEnv {
|
pub fn get_env(&self) -> &AppEnv {
|
||||||
@@ -90,6 +93,8 @@ impl AppState {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Create a new object web::Data<AppState>.
|
/// Create a new object web::Data<AppState>.
|
||||||
pub async fn new_app_state() -> Result<web::Data<AppState>, Box<dyn std::error::Error>> {
|
pub async fn new_app_state(
|
||||||
Ok(web::Data::new(AppState::new().await?))
|
database: Option<DatabaseConnection>,
|
||||||
|
) -> Result<web::Data<AppState>, Box<dyn std::error::Error>> {
|
||||||
|
Ok(web::Data::new(AppState::new(database).await?))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,13 +7,16 @@ pub(crate) mod tests {
|
|||||||
|
|
||||||
pub fn test_env() {
|
pub fn test_env() {
|
||||||
info!("Loading test environment file...");
|
info!("Loading test environment file...");
|
||||||
|
|
||||||
dotenvy::from_filename(".env.test.local")
|
dotenvy::from_filename(".env.test.local")
|
||||||
.or_else(|_| dotenvy::from_filename(".env.test"))
|
.or_else(|_| dotenvy::from_filename(".env.test"))
|
||||||
.expect("Failed to load test environment file");
|
.expect("Failed to load test environment file");
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn test_app_state() -> web::Data<AppState> {
|
pub async fn test_app_state() -> web::Data<AppState> {
|
||||||
let state = new_app_state().await.unwrap();
|
let state = new_app_state(Some(static_app_state().await.get_database().clone()))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
state.clone()
|
state.clone()
|
||||||
}
|
}
|
||||||
@@ -21,6 +24,14 @@ pub(crate) mod tests {
|
|||||||
pub async fn static_app_state() -> web::Data<AppState> {
|
pub async fn static_app_state() -> web::Data<AppState> {
|
||||||
static STATE: OnceCell<web::Data<AppState>> = OnceCell::const_new();
|
static STATE: OnceCell<web::Data<AppState>> = OnceCell::const_new();
|
||||||
|
|
||||||
STATE.get_or_init(|| test_app_state()).await.clone()
|
STATE
|
||||||
|
.get_or_init(async || -> web::Data<AppState> {
|
||||||
|
#[cfg(feature = "trace")]
|
||||||
|
console_subscriber::init();
|
||||||
|
|
||||||
|
new_app_state(None).await.unwrap()
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.clone()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -63,13 +63,13 @@ struct Claims {
|
|||||||
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: &String) -> Result<String, 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");
|
||||||
validation.validate_exp = false;
|
validation.validate_exp = false;
|
||||||
|
|
||||||
let result = decode::<Claims>(&token, &*DECODING_KEY, &validation);
|
let result = decode::<Claims>(token, &DECODING_KEY, &validation);
|
||||||
|
|
||||||
match result {
|
match result {
|
||||||
Ok(token_data) => {
|
Ok(token_data) => {
|
||||||
@@ -88,7 +88,7 @@ pub fn verify_and_decode(token: &String) -> Result<String, Error> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Creating a user token.
|
/// Creating a user token.
|
||||||
pub fn encode(id: &String) -> 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()
|
||||||
@@ -98,12 +98,12 @@ pub fn encode(id: &String) -> String {
|
|||||||
let exp = iat + Duration::days(365 * 4);
|
let exp = iat + Duration::days(365 * 4);
|
||||||
|
|
||||||
let claims = Claims {
|
let claims = Claims {
|
||||||
id: id.clone(),
|
id: id.to_string(),
|
||||||
iat: iat.timestamp().unsigned_abs(),
|
iat: iat.timestamp().unsigned_abs(),
|
||||||
exp: exp.timestamp().unsigned_abs(),
|
exp: exp.timestamp().unsigned_abs(),
|
||||||
};
|
};
|
||||||
|
|
||||||
jsonwebtoken::encode(&header, &claims, &*ENCODING_KEY).unwrap()
|
jsonwebtoken::encode(&header, &claims, &ENCODING_KEY).unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
|||||||
@@ -33,7 +33,7 @@ impl WebAppInitDataMap {
|
|||||||
};
|
};
|
||||||
|
|
||||||
data.split('&')
|
data.split('&')
|
||||||
.map(|kv| kv.split_once('=').unwrap_or_else(|| (kv, "")))
|
.map(|kv| kv.split_once('=').unwrap_or((kv, "")))
|
||||||
.for_each(|(key, value)| {
|
.for_each(|(key, value)| {
|
||||||
this.data_map.insert(key.to_string(), value.to_string());
|
this.data_map.insert(key.to_string(), value.to_string());
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user