started development
This commit is contained in:
@@ -0,0 +1 @@
|
||||
/target
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1 @@
|
||||
MANIFEST-000013
|
||||
@@ -0,0 +1 @@
|
||||
9ae77887-bae0-4a92-a7d2-3df6127bec33
|
||||
Binary file not shown.
@@ -0,0 +1,206 @@
|
||||
# This is a RocksDB option file.
|
||||
#
|
||||
# For detailed file format spec, please refer to the example file
|
||||
# in examples/rocksdb_option_file_example.ini
|
||||
#
|
||||
|
||||
[Version]
|
||||
rocksdb_version=8.10.0
|
||||
options_file_version=1.1
|
||||
|
||||
[DBOptions]
|
||||
compaction_readahead_size=2097152
|
||||
strict_bytes_per_sync=false
|
||||
bytes_per_sync=0
|
||||
max_background_jobs=32
|
||||
avoid_flush_during_shutdown=false
|
||||
max_background_flushes=-1
|
||||
delayed_write_rate=16777216
|
||||
max_open_files=-1
|
||||
max_subcompactions=1
|
||||
writable_file_max_buffer_size=1048576
|
||||
wal_bytes_per_sync=0
|
||||
max_background_compactions=-1
|
||||
max_total_wal_size=0
|
||||
delete_obsolete_files_period_micros=21600000000
|
||||
stats_dump_period_sec=600
|
||||
stats_history_buffer_size=1048576
|
||||
stats_persist_period_sec=600
|
||||
enforce_single_del_contracts=true
|
||||
lowest_used_cache_tier=kNonVolatileBlockTier
|
||||
bgerror_resume_retry_interval=1000000
|
||||
best_efforts_recovery=false
|
||||
log_readahead_size=0
|
||||
write_dbid_to_manifest=false
|
||||
wal_compression=kNoCompression
|
||||
manual_wal_flush=false
|
||||
db_host_id=__hostname__
|
||||
two_write_queues=false
|
||||
random_access_max_buffer_size=1048576
|
||||
avoid_unnecessary_blocking_io=false
|
||||
skip_checking_sst_file_sizes_on_db_open=false
|
||||
flush_verify_memtable_count=true
|
||||
fail_if_options_file_error=true
|
||||
atomic_flush=false
|
||||
verify_sst_unique_id_in_manifest=true
|
||||
skip_stats_update_on_db_open=false
|
||||
track_and_verify_wals_in_manifest=false
|
||||
compaction_verify_record_count=true
|
||||
paranoid_checks=true
|
||||
create_if_missing=true
|
||||
max_write_batch_group_size_bytes=1048576
|
||||
avoid_flush_during_recovery=false
|
||||
file_checksum_gen_factory=nullptr
|
||||
enable_thread_tracking=false
|
||||
allow_fallocate=true
|
||||
allow_data_in_errors=false
|
||||
error_if_exists=false
|
||||
use_direct_io_for_flush_and_compaction=false
|
||||
create_missing_column_families=true
|
||||
WAL_size_limit_MB=0
|
||||
use_direct_reads=false
|
||||
persist_stats_to_disk=false
|
||||
allow_2pc=false
|
||||
is_fd_close_on_exec=true
|
||||
max_log_file_size=0
|
||||
access_hint_on_compaction_start=NORMAL
|
||||
max_file_opening_threads=16
|
||||
wal_filter=nullptr
|
||||
allow_mmap_reads=false
|
||||
allow_mmap_writes=false
|
||||
use_adaptive_mutex=false
|
||||
use_fsync=false
|
||||
table_cache_numshardbits=6
|
||||
dump_malloc_stats=false
|
||||
db_write_buffer_size=0
|
||||
allow_ingest_behind=false
|
||||
keep_log_file_num=20
|
||||
max_bgerror_resume_count=2147483647
|
||||
allow_concurrent_memtable_write=true
|
||||
recycle_log_file_num=0
|
||||
log_file_time_to_roll=0
|
||||
manifest_preallocation_size=4194304
|
||||
enable_write_thread_adaptive_yield=true
|
||||
WAL_ttl_seconds=0
|
||||
max_manifest_file_size=1073741824
|
||||
wal_recovery_mode=kPointInTimeRecovery
|
||||
enable_pipelined_write=true
|
||||
write_thread_slow_yield_usec=3
|
||||
unordered_write=false
|
||||
write_thread_max_yield_usec=100
|
||||
advise_random_on_open=true
|
||||
info_log_level=WARN_LEVEL
|
||||
|
||||
|
||||
[CFOptions "default"]
|
||||
memtable_max_range_deletions=0
|
||||
compression_opts={checksum=false;max_dict_buffer_bytes=0;enabled=false;max_dict_bytes=0;max_compressed_bytes_per_kb=896;parallel_threads=1;zstd_max_train_bytes=0;level=32767;use_zstd_dict_trainer=true;strategy=0;window_bits=-14;}
|
||||
block_protection_bytes_per_key=0
|
||||
bottommost_file_compaction_delay=0
|
||||
memtable_protection_bytes_per_key=0
|
||||
target_file_size_multiplier=1
|
||||
report_bg_io_stats=false
|
||||
write_buffer_size=268435456
|
||||
memtable_huge_page_size=0
|
||||
max_successive_merges=0
|
||||
max_write_buffer_number=32
|
||||
prefix_extractor=nullptr
|
||||
bottommost_compression_opts={checksum=false;max_dict_buffer_bytes=0;enabled=false;max_dict_bytes=0;max_compressed_bytes_per_kb=896;parallel_threads=1;zstd_max_train_bytes=0;level=32767;use_zstd_dict_trainer=true;strategy=0;window_bits=-14;}
|
||||
paranoid_file_checks=false
|
||||
blob_garbage_collection_force_threshold=1.000000
|
||||
enable_blob_files=true
|
||||
blob_file_starting_level=0
|
||||
memtable_prefix_bloom_size_ratio=0.000000
|
||||
inplace_update_num_locks=10000
|
||||
blob_compaction_readahead_size=0
|
||||
ignore_max_compaction_bytes_for_input=true
|
||||
arena_block_size=1048576
|
||||
level0_stop_writes_trigger=36
|
||||
blob_compression_type=kNoCompression
|
||||
level0_slowdown_writes_trigger=20
|
||||
hard_pending_compaction_bytes_limit=274877906944
|
||||
soft_pending_compaction_bytes_limit=68719476736
|
||||
target_file_size_base=67108864
|
||||
level0_file_num_compaction_trigger=4
|
||||
max_compaction_bytes=1677721600
|
||||
disable_auto_compactions=false
|
||||
check_flush_compaction_key_order=true
|
||||
min_blob_size=4096
|
||||
memtable_whole_key_filtering=false
|
||||
max_bytes_for_level_base=268435456
|
||||
last_level_temperature=kUnknown
|
||||
compaction_options_fifo={file_temperature_age_thresholds=;allow_compaction=false;age_for_warm=0;max_table_files_size=1073741824;}
|
||||
max_bytes_for_level_multiplier=10.000000
|
||||
compression_per_level=kNoCompression:kNoCompression:kLZ4HCCompression:kLZ4HCCompression:kLZ4HCCompression
|
||||
max_bytes_for_level_multiplier_additional=1:1:1:1:1:1:1
|
||||
max_sequential_skip_in_iterations=8
|
||||
prepopulate_blob_cache=kDisable
|
||||
compression=kSnappyCompression
|
||||
compaction_options_universal={incremental=false;compression_size_percent=-1;allow_trivial_move=false;max_size_amplification_percent=200;max_merge_width=4294967295;stop_style=kCompactionStopStyleTotalSize;min_merge_width=2;size_ratio=1;}
|
||||
blob_garbage_collection_age_cutoff=0.250000
|
||||
ttl=2592000
|
||||
periodic_compaction_seconds=0
|
||||
sample_for_compression=0
|
||||
blob_file_size=268435456
|
||||
enable_blob_garbage_collection=false
|
||||
experimental_mempurge_threshold=0.000000
|
||||
bottommost_compression=kDisableCompressionOption
|
||||
persist_user_defined_timestamps=true
|
||||
preserve_internal_time_seconds=0
|
||||
preclude_last_level_data_seconds=0
|
||||
sst_partitioner_factory=nullptr
|
||||
num_levels=7
|
||||
force_consistency_checks=true
|
||||
memtable_insert_with_hint_prefix_extractor=nullptr
|
||||
memtable_factory=SkipListFactory
|
||||
compaction_pri=kMinOverlappingRatio
|
||||
max_write_buffer_size_to_maintain=8589934592
|
||||
level_compaction_dynamic_file_size=true
|
||||
max_write_buffer_number_to_maintain=0
|
||||
optimize_filters_for_hits=false
|
||||
table_properties_collectors={{id=CompactOnDeletionCollector;deletion_ratio=0.500000;deletion_trigger=50;window_size=1000;}}
|
||||
level_compaction_dynamic_level_bytes=true
|
||||
default_temperature=kUnknown
|
||||
inplace_update_support=false
|
||||
merge_operator=nullptr
|
||||
table_factory=BlockBasedTable
|
||||
min_write_buffer_number_to_merge=4
|
||||
compaction_filter=nullptr
|
||||
compaction_style=kCompactionStyleLevel
|
||||
bloom_locality=0
|
||||
comparator=leveldb.BytewiseComparator
|
||||
compaction_filter_factory=nullptr
|
||||
|
||||
[TableOptions/BlockBasedTable "default"]
|
||||
initial_auto_readahead_size=8192
|
||||
pin_top_level_index_and_filter=true
|
||||
block_align=false
|
||||
block_size_deviation=10
|
||||
checksum=kXXH3
|
||||
index_shortening=kShortenSeparators
|
||||
num_file_reads_for_auto_readahead=2
|
||||
whole_key_filtering=true
|
||||
data_block_index_type=kDataBlockBinarySearch
|
||||
index_type=kBinarySearch
|
||||
no_block_cache=false
|
||||
index_block_restart_interval=1
|
||||
data_block_hash_table_util_ratio=0.750000
|
||||
prepopulate_block_cache=kDisable
|
||||
pin_l0_filter_and_index_blocks_in_cache=false
|
||||
filter_policy=nullptr
|
||||
cache_index_and_filter_blocks_with_high_priority=true
|
||||
verify_compression=false
|
||||
block_restart_interval=16
|
||||
max_auto_readahead_size=262144
|
||||
flush_block_policy_factory=FlushBlockBySizePolicyFactory
|
||||
partition_filters=false
|
||||
cache_index_and_filter_blocks=false
|
||||
block_size=4096
|
||||
metadata_block_size=4096
|
||||
optimize_filters_for_memory=false
|
||||
detect_filter_construct_corruption=false
|
||||
format_version=5
|
||||
metadata_cache_options={unpartitioned_pinning=kFallback;partition_pinning=kFallback;top_level_index_pinning=kFallback;}
|
||||
read_amp_bytes_per_bit=0
|
||||
enable_index_compression=true
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
# This is a RocksDB option file.
|
||||
#
|
||||
# For detailed file format spec, please refer to the example file
|
||||
# in examples/rocksdb_option_file_example.ini
|
||||
#
|
||||
|
||||
[Version]
|
||||
rocksdb_version=8.10.0
|
||||
options_file_version=1.1
|
||||
|
||||
[DBOptions]
|
||||
compaction_readahead_size=2097152
|
||||
strict_bytes_per_sync=false
|
||||
bytes_per_sync=0
|
||||
max_background_jobs=32
|
||||
avoid_flush_during_shutdown=false
|
||||
max_background_flushes=-1
|
||||
delayed_write_rate=16777216
|
||||
max_open_files=-1
|
||||
max_subcompactions=1
|
||||
writable_file_max_buffer_size=1048576
|
||||
wal_bytes_per_sync=0
|
||||
max_background_compactions=-1
|
||||
max_total_wal_size=0
|
||||
delete_obsolete_files_period_micros=21600000000
|
||||
stats_dump_period_sec=600
|
||||
stats_history_buffer_size=1048576
|
||||
stats_persist_period_sec=600
|
||||
enforce_single_del_contracts=true
|
||||
lowest_used_cache_tier=kNonVolatileBlockTier
|
||||
bgerror_resume_retry_interval=1000000
|
||||
best_efforts_recovery=false
|
||||
log_readahead_size=0
|
||||
write_dbid_to_manifest=false
|
||||
wal_compression=kNoCompression
|
||||
manual_wal_flush=false
|
||||
db_host_id=__hostname__
|
||||
two_write_queues=false
|
||||
random_access_max_buffer_size=1048576
|
||||
avoid_unnecessary_blocking_io=false
|
||||
skip_checking_sst_file_sizes_on_db_open=false
|
||||
flush_verify_memtable_count=true
|
||||
fail_if_options_file_error=true
|
||||
atomic_flush=false
|
||||
verify_sst_unique_id_in_manifest=true
|
||||
skip_stats_update_on_db_open=false
|
||||
track_and_verify_wals_in_manifest=false
|
||||
compaction_verify_record_count=true
|
||||
paranoid_checks=true
|
||||
create_if_missing=true
|
||||
max_write_batch_group_size_bytes=1048576
|
||||
avoid_flush_during_recovery=false
|
||||
file_checksum_gen_factory=nullptr
|
||||
enable_thread_tracking=false
|
||||
allow_fallocate=true
|
||||
allow_data_in_errors=false
|
||||
error_if_exists=false
|
||||
use_direct_io_for_flush_and_compaction=false
|
||||
create_missing_column_families=true
|
||||
WAL_size_limit_MB=0
|
||||
use_direct_reads=false
|
||||
persist_stats_to_disk=false
|
||||
allow_2pc=false
|
||||
is_fd_close_on_exec=true
|
||||
max_log_file_size=0
|
||||
access_hint_on_compaction_start=NORMAL
|
||||
max_file_opening_threads=16
|
||||
wal_filter=nullptr
|
||||
allow_mmap_reads=false
|
||||
allow_mmap_writes=false
|
||||
use_adaptive_mutex=false
|
||||
use_fsync=false
|
||||
table_cache_numshardbits=6
|
||||
dump_malloc_stats=false
|
||||
db_write_buffer_size=0
|
||||
allow_ingest_behind=false
|
||||
keep_log_file_num=20
|
||||
max_bgerror_resume_count=2147483647
|
||||
allow_concurrent_memtable_write=true
|
||||
recycle_log_file_num=0
|
||||
log_file_time_to_roll=0
|
||||
manifest_preallocation_size=4194304
|
||||
enable_write_thread_adaptive_yield=true
|
||||
WAL_ttl_seconds=0
|
||||
max_manifest_file_size=1073741824
|
||||
wal_recovery_mode=kPointInTimeRecovery
|
||||
enable_pipelined_write=true
|
||||
write_thread_slow_yield_usec=3
|
||||
unordered_write=false
|
||||
write_thread_max_yield_usec=100
|
||||
advise_random_on_open=true
|
||||
info_log_level=WARN_LEVEL
|
||||
|
||||
|
||||
[CFOptions "default"]
|
||||
memtable_max_range_deletions=0
|
||||
compression_opts={checksum=false;max_dict_buffer_bytes=0;enabled=false;max_dict_bytes=0;max_compressed_bytes_per_kb=896;parallel_threads=1;zstd_max_train_bytes=0;level=32767;use_zstd_dict_trainer=true;strategy=0;window_bits=-14;}
|
||||
block_protection_bytes_per_key=0
|
||||
bottommost_file_compaction_delay=0
|
||||
memtable_protection_bytes_per_key=0
|
||||
target_file_size_multiplier=1
|
||||
report_bg_io_stats=false
|
||||
write_buffer_size=268435456
|
||||
memtable_huge_page_size=0
|
||||
max_successive_merges=0
|
||||
max_write_buffer_number=32
|
||||
prefix_extractor=nullptr
|
||||
bottommost_compression_opts={checksum=false;max_dict_buffer_bytes=0;enabled=false;max_dict_bytes=0;max_compressed_bytes_per_kb=896;parallel_threads=1;zstd_max_train_bytes=0;level=32767;use_zstd_dict_trainer=true;strategy=0;window_bits=-14;}
|
||||
paranoid_file_checks=false
|
||||
blob_garbage_collection_force_threshold=1.000000
|
||||
enable_blob_files=true
|
||||
blob_file_starting_level=0
|
||||
memtable_prefix_bloom_size_ratio=0.000000
|
||||
inplace_update_num_locks=10000
|
||||
blob_compaction_readahead_size=0
|
||||
ignore_max_compaction_bytes_for_input=true
|
||||
arena_block_size=1048576
|
||||
level0_stop_writes_trigger=36
|
||||
blob_compression_type=kNoCompression
|
||||
level0_slowdown_writes_trigger=20
|
||||
hard_pending_compaction_bytes_limit=274877906944
|
||||
soft_pending_compaction_bytes_limit=68719476736
|
||||
target_file_size_base=67108864
|
||||
level0_file_num_compaction_trigger=4
|
||||
max_compaction_bytes=1677721600
|
||||
disable_auto_compactions=false
|
||||
check_flush_compaction_key_order=true
|
||||
min_blob_size=4096
|
||||
memtable_whole_key_filtering=false
|
||||
max_bytes_for_level_base=268435456
|
||||
last_level_temperature=kUnknown
|
||||
compaction_options_fifo={file_temperature_age_thresholds=;allow_compaction=false;age_for_warm=0;max_table_files_size=1073741824;}
|
||||
max_bytes_for_level_multiplier=10.000000
|
||||
compression_per_level=kNoCompression:kNoCompression:kLZ4HCCompression:kLZ4HCCompression:kLZ4HCCompression
|
||||
max_bytes_for_level_multiplier_additional=1:1:1:1:1:1:1
|
||||
max_sequential_skip_in_iterations=8
|
||||
prepopulate_blob_cache=kDisable
|
||||
compression=kSnappyCompression
|
||||
compaction_options_universal={incremental=false;compression_size_percent=-1;allow_trivial_move=false;max_size_amplification_percent=200;max_merge_width=4294967295;stop_style=kCompactionStopStyleTotalSize;min_merge_width=2;size_ratio=1;}
|
||||
blob_garbage_collection_age_cutoff=0.250000
|
||||
ttl=2592000
|
||||
periodic_compaction_seconds=0
|
||||
sample_for_compression=0
|
||||
blob_file_size=268435456
|
||||
enable_blob_garbage_collection=false
|
||||
experimental_mempurge_threshold=0.000000
|
||||
bottommost_compression=kDisableCompressionOption
|
||||
persist_user_defined_timestamps=true
|
||||
preserve_internal_time_seconds=0
|
||||
preclude_last_level_data_seconds=0
|
||||
sst_partitioner_factory=nullptr
|
||||
num_levels=7
|
||||
force_consistency_checks=true
|
||||
memtable_insert_with_hint_prefix_extractor=nullptr
|
||||
memtable_factory=SkipListFactory
|
||||
compaction_pri=kMinOverlappingRatio
|
||||
max_write_buffer_size_to_maintain=8589934592
|
||||
level_compaction_dynamic_file_size=true
|
||||
max_write_buffer_number_to_maintain=0
|
||||
optimize_filters_for_hits=false
|
||||
table_properties_collectors={{id=CompactOnDeletionCollector;deletion_ratio=0.500000;deletion_trigger=50;window_size=1000;}}
|
||||
level_compaction_dynamic_level_bytes=true
|
||||
default_temperature=kUnknown
|
||||
inplace_update_support=false
|
||||
merge_operator=nullptr
|
||||
table_factory=BlockBasedTable
|
||||
min_write_buffer_number_to_merge=4
|
||||
compaction_filter=nullptr
|
||||
compaction_style=kCompactionStyleLevel
|
||||
bloom_locality=0
|
||||
comparator=leveldb.BytewiseComparator
|
||||
compaction_filter_factory=nullptr
|
||||
|
||||
[TableOptions/BlockBasedTable "default"]
|
||||
initial_auto_readahead_size=8192
|
||||
pin_top_level_index_and_filter=true
|
||||
block_align=false
|
||||
block_size_deviation=10
|
||||
checksum=kXXH3
|
||||
index_shortening=kShortenSeparators
|
||||
num_file_reads_for_auto_readahead=2
|
||||
whole_key_filtering=true
|
||||
data_block_index_type=kDataBlockBinarySearch
|
||||
index_type=kBinarySearch
|
||||
no_block_cache=false
|
||||
index_block_restart_interval=1
|
||||
data_block_hash_table_util_ratio=0.750000
|
||||
prepopulate_block_cache=kDisable
|
||||
pin_l0_filter_and_index_blocks_in_cache=false
|
||||
filter_policy=nullptr
|
||||
cache_index_and_filter_blocks_with_high_priority=true
|
||||
verify_compression=false
|
||||
block_restart_interval=16
|
||||
max_auto_readahead_size=262144
|
||||
flush_block_policy_factory=FlushBlockBySizePolicyFactory
|
||||
partition_filters=false
|
||||
cache_index_and_filter_blocks=false
|
||||
block_size=4096
|
||||
metadata_block_size=4096
|
||||
optimize_filters_for_memory=false
|
||||
detect_filter_construct_corruption=false
|
||||
format_version=5
|
||||
metadata_cache_options={unpartitioned_pinning=kFallback;partition_pinning=kFallback;top_level_index_pinning=kFallback;}
|
||||
read_amp_bytes_per_bit=0
|
||||
enable_index_compression=true
|
||||
|
||||
Generated
+5057
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "chatapp-backend"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
rocket = { version = "0.5.0-rc.3", features = ["json", "secrets", "tls"] }
|
||||
rocket_ws = "0.1.0"
|
||||
tokio = { version = "1.0", features = ["full"] }
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
futures = "0.3"
|
||||
surrealdb = "2.1.2"
|
||||
chrono = "0.4.38"
|
||||
rand = "0.8.5"
|
||||
sha2 = "0.10.8"
|
||||
@@ -0,0 +1,26 @@
|
||||
DEFINE FUNCTION friend::request($from: uuid, $to: uuid) {
|
||||
CREATE FriendRequest SET
|
||||
in = Entity:from,
|
||||
out = Entity:to,
|
||||
created = time::now(),
|
||||
}
|
||||
|
||||
DEFINE FUNCTION friend::accept($request: record<FriendRequest>) {
|
||||
|
||||
LET $fsid = uuid::new();
|
||||
|
||||
CREATE Friendship SET
|
||||
dm_channel = channel::new(),
|
||||
id = $fsid,
|
||||
since = time::now(),
|
||||
|
||||
CREATE HasFriendShip SET
|
||||
in = Entity:request.in,
|
||||
out = Friendship:fsid,
|
||||
nickname = Entity:request.out.displayname,
|
||||
|
||||
CREATE HasFriendShip SET
|
||||
in = Entity:request.out,
|
||||
out = Friendship:fsid,
|
||||
nickname = Entity:request.in.displayname,
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
DEFINE FUNCTION server::join($server_id: uuid, $entity_id: uuid) {
|
||||
|
||||
LET $user = (SELECT displayname FROM Entity WHERE id = $entity_id)[0];
|
||||
|
||||
CREATE HasServer SET
|
||||
in = Entity:entity_id,
|
||||
out = Server:server_id,
|
||||
nickname = $user.displayname,
|
||||
permissions = [],
|
||||
joined = time::now(),
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use rand::{thread_rng, Rng};
|
||||
use rocket::{http::{CookieJar, Status}, options, post, request::{FromRequest, Outcome}, serde::json::Json, Request};
|
||||
use serde::Deserialize;
|
||||
use sha2::{Digest, Sha256};
|
||||
use surrealdb::RecordId;
|
||||
|
||||
use crate::{database::DB, user::{
|
||||
User, AuthResponse
|
||||
}};
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct UserLoginForm {
|
||||
username: String,
|
||||
password: String
|
||||
}
|
||||
|
||||
#[options("/login")]
|
||||
pub fn login_options() -> Status {
|
||||
Status::Ok
|
||||
}
|
||||
|
||||
|
||||
#[post("/login", data = "<user>")]
|
||||
pub async fn login(user: Json<UserLoginForm>, jar: &CookieJar<'_>) -> Status {
|
||||
|
||||
println!("Logging in: {}", user.username);
|
||||
|
||||
if let Ok(response) = User::authenticate(user.username.clone(), user.password.clone()).await {
|
||||
if response.matches {
|
||||
|
||||
let token = SessionToken::new(response.user_id).await;
|
||||
jar.add_private(("auth", token.token));
|
||||
println!("success!");
|
||||
|
||||
return Status::Ok
|
||||
} else {
|
||||
println!("does not match");
|
||||
}
|
||||
} else {
|
||||
println!("response err");
|
||||
}
|
||||
|
||||
println!("failed!");
|
||||
return Status::Unauthorized
|
||||
}
|
||||
|
||||
#[options("/signup")]
|
||||
pub fn signup_options() -> Status {
|
||||
Status::Ok
|
||||
}
|
||||
|
||||
#[post("/signup", data = "<user>")]
|
||||
pub async fn signup(user: Json<UserLoginForm>, jar: &CookieJar<'_>) -> Status {
|
||||
|
||||
println!("signing up: {}", user.username);
|
||||
|
||||
User::create(user.username.clone(), user.password.clone()).await;
|
||||
|
||||
login(user, jar).await
|
||||
}
|
||||
|
||||
pub type SessionTokenGuard = User;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SessionToken {
|
||||
token: String,
|
||||
created_at: i64,
|
||||
expires_at: i64,
|
||||
user_id: RecordId,
|
||||
}
|
||||
|
||||
#[rocket::async_trait]
|
||||
impl<'r> FromRequest<'r> for SessionTokenGuard {
|
||||
type Error = ();
|
||||
|
||||
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
||||
if let Some(cookie) = req.cookies().get_private("auth") {
|
||||
let token = cookie.value().to_string();
|
||||
return match DB
|
||||
.query("
|
||||
SELECT * FROM User WHERE user_id = (SELECT user_id FROM SessionToken WHERE token = $1)[0]
|
||||
")
|
||||
.bind(("token", token))
|
||||
.await
|
||||
.unwrap()
|
||||
.take::<Option<User>>(0)
|
||||
{
|
||||
Ok(Some(user)) => Outcome::Success(user),
|
||||
_ => Outcome::Error((rocket::http::Status::Unauthorized, ())),
|
||||
}
|
||||
}
|
||||
Outcome::Error((rocket::http::Status::Unauthorized, ()))
|
||||
}
|
||||
}
|
||||
|
||||
impl SessionToken {
|
||||
pub async fn new(user_id: RecordId) -> SessionToken {
|
||||
let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
|
||||
let expiry = Duration::from_secs(7 * 24 * 60 * 60);
|
||||
let random_value: u32 = thread_rng().gen();
|
||||
let token = format!("{}-{}", current_time.as_secs(), random_value);
|
||||
let hashed = format!("{:x}", Sha256::digest(token.as_bytes()));
|
||||
|
||||
println!("{}", hashed);
|
||||
|
||||
let token = SessionToken {
|
||||
token: hashed,
|
||||
created_at: current_time.as_secs() as i64,
|
||||
expires_at: (current_time + expiry).as_secs() as i64,
|
||||
user_id,
|
||||
};
|
||||
|
||||
let tok = token.clone();
|
||||
DB
|
||||
.query("
|
||||
CREATE SessionToken SET
|
||||
token = $token,
|
||||
created_at = $created_at,
|
||||
expires_at = $expires_at,
|
||||
user_id = $user_id
|
||||
")
|
||||
.bind(("token", tok.token))
|
||||
.bind(("created_at", tok.created_at))
|
||||
.bind(("expires_at", tok.expires_at))
|
||||
.bind(("user_id", tok.user_id))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
token
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use surrealdb::{engine::remote::ws::{Client, Ws}, opt::auth::Root, Surreal};
|
||||
|
||||
pub static DB: LazyLock<Surreal<Client>> = LazyLock::new(|| Surreal::init());
|
||||
|
||||
pub async fn init() -> Result<(), surrealdb::Error> {
|
||||
DB.connect::<Ws>("localhost:8001").await?;
|
||||
|
||||
DB.signin(Root {
|
||||
username: "root",
|
||||
password: "root",
|
||||
}).await?;
|
||||
|
||||
DB.use_ns("database").use_db("database").await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use auth::{login, login_options, signup, signup_options};
|
||||
use rocket::{fs::FileServer, launch, routes};
|
||||
use std::sync::Arc;
|
||||
use rocket::tokio::sync::Mutex;
|
||||
|
||||
mod messenger;
|
||||
mod auth;
|
||||
mod user;
|
||||
mod database;
|
||||
|
||||
use messenger::{MessengerServer, connect};
|
||||
|
||||
#[launch]
|
||||
async fn rocket() -> _ {
|
||||
let messenger = Arc::new(Mutex::new(MessengerServer::new()));
|
||||
|
||||
database::init().await.unwrap();
|
||||
|
||||
rocket::build()
|
||||
.manage(messenger)
|
||||
.mount("/", routes![
|
||||
connect,
|
||||
login,
|
||||
signup,
|
||||
login_options,
|
||||
signup_options,
|
||||
])
|
||||
.mount("/static", FileServer::from("static"))
|
||||
.attach(rocket::fairing::AdHoc::on_response("CORS", |_, res| Box::pin(async move {
|
||||
res.set_header(rocket::http::Header::new(
|
||||
"Access-Control-Allow-Origin",
|
||||
"*"
|
||||
));
|
||||
res.set_header(rocket::http::Header::new(
|
||||
"Access-Control-Allow-Methods",
|
||||
"GET, POST, OPTIONS"
|
||||
));
|
||||
res.set_header(rocket::http::Header::new(
|
||||
"Access-Control-Allow-Headers",
|
||||
"*"
|
||||
));
|
||||
})))
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
use std::{collections::HashMap, sync::Arc, time::{SystemTime, UNIX_EPOCH}};
|
||||
|
||||
use rocket::{
|
||||
futures::{
|
||||
channel::mpsc,
|
||||
stream::{SplitSink, SplitStream},
|
||||
SinkExt,
|
||||
StreamExt
|
||||
},
|
||||
tokio::sync::Mutex,
|
||||
serde::json::to_string,
|
||||
get,
|
||||
http::Status,
|
||||
Shutdown
|
||||
};
|
||||
|
||||
use serde::Serialize;
|
||||
use rocket_ws::{Channel, WebSocket, stream::DuplexStream};
|
||||
use surrealdb::{RecordId, Uuid};
|
||||
|
||||
use crate::{auth::SessionTokenGuard, user::User};
|
||||
|
||||
|
||||
|
||||
|
||||
#[get("/messenger/connect/<channel_id>")]
|
||||
pub async fn connect<'r> (
|
||||
user: SessionTokenGuard,
|
||||
ws: WebSocket,
|
||||
messenger: &'r rocket::State<Arc<Mutex<MessengerServer>>>,
|
||||
channel_id: i32,
|
||||
mut shutdown: Shutdown,
|
||||
) -> Result<Channel<'r>, Status> {
|
||||
|
||||
let messenger = Arc::clone(messenger.inner());
|
||||
|
||||
Ok(ws.channel(move | channel| {
|
||||
Box::pin(async move {
|
||||
|
||||
let (sender, receiver) = mpsc::channel::<RealTimeMessage>(100);
|
||||
let (ws_sender, ws_receiver) = channel.split();
|
||||
|
||||
println!("REGISTERING: {}", user.id);
|
||||
messenger.lock().await.register(user.id.clone(), channel_id, sender);
|
||||
|
||||
tokio::select! {
|
||||
_ = inbound_message(ws_receiver, messenger.clone(), channel_id, &user) => {},
|
||||
_ = outbound_message(ws_sender, receiver) => {},
|
||||
_ = &mut shutdown => {},
|
||||
}
|
||||
|
||||
// Once the client disconnects, or the server is shutdown they are deregistered from the channel.
|
||||
println!("DEREGISTERING: {}", user.id);
|
||||
messenger.lock().await.deregister(user.id);
|
||||
Ok(())
|
||||
})
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
pub async fn inbound_message(
|
||||
mut ws_receiver: SplitStream<DuplexStream>,
|
||||
messenger: Arc<Mutex<MessengerServer>>,
|
||||
channel_id: i32,
|
||||
user: &User,
|
||||
) {
|
||||
while let Some(Ok(msg)) = ws_receiver.next().await {
|
||||
if let rocket_ws::Message::Text(text) = msg {
|
||||
|
||||
let message = RealTimeMessage {
|
||||
message_id: 0,
|
||||
user_id: user.id.key().to_string(),
|
||||
display_name: user.username.clone(),
|
||||
created_at: SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as i64,
|
||||
content: text,
|
||||
};
|
||||
|
||||
messenger.lock().await.send(channel_id, message).await;
|
||||
} else if let rocket_ws::Message::Binary(b) = msg {
|
||||
println!("recieved binary message: {}", String::from_utf8(b).unwrap());
|
||||
} else {
|
||||
println!("OTHER");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn outbound_message(
|
||||
mut ws_sender: SplitSink<DuplexStream, rocket_ws::Message>,
|
||||
mut receiver: mpsc::Receiver<RealTimeMessage>
|
||||
) {
|
||||
while let Some(msg) = receiver.next().await {
|
||||
if let Err(e) = ws_sender.send(to_string(&msg).unwrap().into()).await {
|
||||
println!("Failed to send message to client\nError: {}", e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
type UserId = RecordId;
|
||||
type ChannelId = i32;
|
||||
|
||||
pub struct MessengerServer {
|
||||
pub channels: HashMap<i32, HashMap<UserId, mpsc::Sender<RealTimeMessage>>> // map of the channel id to the channel object
|
||||
}
|
||||
|
||||
impl MessengerServer {
|
||||
pub fn new() -> MessengerServer {
|
||||
MessengerServer {
|
||||
channels: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register(&mut self, user_id: UserId, channel_id: ChannelId, sender: mpsc::Sender<RealTimeMessage>) {
|
||||
if let Some(channel) = self.channels.get_mut(&channel_id) {
|
||||
channel.insert(user_id, sender);
|
||||
} else {
|
||||
self.channels.insert(channel_id, HashMap::from([(user_id, sender)]));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn deregister(&mut self, user_id: UserId) {
|
||||
for (_, channel) in self.channels.iter_mut() {
|
||||
channel.remove(&user_id);
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn send(&mut self, channel_id: ChannelId, msg: RealTimeMessage) {
|
||||
if let Some(channel) = self.channels.get_mut(&channel_id) {
|
||||
for (_, sender) in channel.iter_mut() {
|
||||
if let Err(e) = sender.send(msg.clone()).await {
|
||||
println!("Failed to send message to channel {}\nError: {}", channel_id, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize, Clone)]
|
||||
pub struct RealTimeMessage {
|
||||
pub message_id: i32,
|
||||
pub user_id: String,
|
||||
pub display_name: String,
|
||||
pub created_at: i64,
|
||||
pub content: String,
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use surrealdb::RecordId;
|
||||
use crate::database::DB;
|
||||
|
||||
use chrono::Utc;
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
pub struct User {
|
||||
pub id: RecordId,
|
||||
pub username: String,
|
||||
pub passhash: String,
|
||||
pub displayname: String,
|
||||
pub joined: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct AuthResponse {
|
||||
pub matches: bool,
|
||||
pub user_id: RecordId,
|
||||
}
|
||||
|
||||
impl User {
|
||||
pub async fn authenticate(username: String, password: String) -> Result<AuthResponse, ()> {
|
||||
|
||||
match DB
|
||||
.query("
|
||||
LET $user = (SELECT id, passhash FROM User WHERE username = $username)[0];
|
||||
RETURN {
|
||||
matches: crypto::argon2::compare($user.passhash, $password),
|
||||
user_id: $user.id
|
||||
}"
|
||||
)
|
||||
.bind(("username", username))
|
||||
.bind(("password", password))
|
||||
.await
|
||||
.map_err(|_| ())?
|
||||
.take::<Option<AuthResponse>>(0)
|
||||
{
|
||||
Ok(Some(response)) => Ok(response),
|
||||
Ok(None) => {
|
||||
println!("User not found");
|
||||
Err(())
|
||||
}
|
||||
Err(e) => {
|
||||
println!("Error authenticating user: {}", e);
|
||||
Err(())
|
||||
}
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn create(username: String, password: String) -> Result<String, ()> {
|
||||
match DB
|
||||
.query("
|
||||
CREATE User:uuid() SET
|
||||
username = $username,
|
||||
displayname = $displayname,
|
||||
passhash = crypto::argon2::generate($passhash),
|
||||
joined = $joined;
|
||||
SELECT * FROM User WHERE username = $username
|
||||
")
|
||||
.bind(("username", username.clone()))
|
||||
.bind(("passhash", password))
|
||||
.bind(("displayname", username))
|
||||
.bind(("joined", Utc::now().timestamp()))
|
||||
.await
|
||||
.unwrap()
|
||||
.take::<Option<User>>(0)
|
||||
{
|
||||
Ok(Some(user)) => {
|
||||
let k = user.id.key().to_string();
|
||||
println!("Created User: {}", k);
|
||||
Ok(k)
|
||||
},
|
||||
_ => Err(())
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 696 KiB |
Reference in New Issue
Block a user