Compare commits

..

No commits in common. "d7b4a45a9ac12af53275edc64ea56178d7de44d2" and "ea16071903a7706f28ee5d108dc19f7237d51d01" have entirely different histories.

3 changed files with 25 additions and 104 deletions

View File

@ -6,16 +6,3 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
anyhow = "1.0.86"
axum = "0.7.5"
axum_session = "0.14.0"
axum_session_auth = "0.14.0"
axum_session_mongo = "0.1.0"
candle-nn = "0.5.1"
chrono = "0.4.38"
http = "1.1.0"
mongodb = { version = "2.8.2", features = ["bson-chrono-0_4", "tokio-runtime"]}
rlg = "0.0.4"
serde = "1.0.203"
tokio = "1.38.0"
vrd = "0.0.7"

View File

@ -1,32 +1,26 @@
pub mod db; pub mod db;
use axum::{ use axum::{
body::Body,
extract::Path, extract::Path,
routing::{get, post},
Json, Json,
response::Response, Router
Router,
routing::{get, post}
}; };
use axum_session_auth::AuthSession; use axum_session_auth::AuthSession;
use axum_session_mongo::SessionMongoPool; use axum_session_mongo::SessionMongoPool;
use chrono::Utc;
use crate::AppError; use crate::AppError;
use db::{get_users, User}; use db::{get_users, User};
use http::StatusCode;
use mongodb::{ use mongodb::{
bson::{doc, oid::ObjectId, to_document}, bson::{doc, oid::ObjectId, to_document},
Client Client
}; };
use rlg::macro_info_log;
type AuthenticationSession = AuthSession<User, ObjectId, SessionMongoPool, Client>; type AuthenticationSession = AuthSession<User, ObjectId, SessionMongoPool, Client>;
type ApiResult = Result<Response, AppError>;
pub fn router() -> Router { pub fn router() -> Router {
Router::new() Router::new()
.nest("/:user_id", user_router()) .nest("/:user_id", user_router())
.route("/sign-up", .route("/",
post(post_sign_up) post(post_sign_up)
) )
} }
@ -47,109 +41,65 @@ fn user_router() -> Router {
) )
} }
pub async fn get_sign_in(Path(user_id): Path<ObjectId>) -> ApiResult { pub async fn get_sign_in(Path(user_id): Path<ObjectId>) -> Result<String, AppError> {
let id = format!("user_id: {}", user_id);
macro_info_log!(&Utc::now().to_string(), &id, "Salt request initiated");
let db = get_users().await?; let db = get_users().await?;
let query = doc! { "_id" : user_id}; let query = doc! { "_id" : user_id};
match db.find_one(query, None).await? { match db.find_one(query, None).await? {
Some(user) => { Some(user) => {
macro_info_log!(&Utc::now().to_string(), &id, "Salt request successful"); //TODO: Return User salt
Ok(String::new())
Ok(Response::builder()
.status(StatusCode::CREATED)
.body(Body::from(user.auth.salt.unwrap()))?)
}, },
None => { None => {
macro_info_log!(&Utc::now().to_string(), &id, "Salt Request unsuccessful: username does not exist"); //TODO: Return User does not exist
Ok(String::new())
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::from("User does not exist"))?)
} }
} }
} }
pub async fn post_sign_in(Path(user_id): Path<ObjectId>, auth: AuthenticationSession, body: String) -> ApiResult { pub async fn post_sign_in(Path(user_id): Path<ObjectId>, auth: AuthenticationSession, body: String) -> Result<String, AppError> {
let id = format!("user_id: {}", user_id);
macro_info_log!(&Utc::now().to_string(), &id, "Sign-in request initiated");
let db = get_users().await?; let db = get_users().await?;
let query = doc! { "_id": &user_id, "_auth._hash": body }; let query = doc! { "_id": &user_id, "_auth._hash": body };
match db.find_one(query, None).await? { match db.find_one(query, None).await? {
Some(_user) => { Some(_user) => {
macro_info_log!(&Utc::now().to_string(), &id, "Sign-in request successful");
auth.login_user(user_id); auth.login_user(user_id);
auth.remember_user(true); auth.remember_user(true);
//TODO: Return API Key or Auth Key and User ID
Ok(Response::builder()
.status(StatusCode::OK)
.body(Body::from(format!("{}", user_id)))?)
}, },
None => { None => {
macro_info_log!(&Utc::now().to_string(), &id, "Sign-in request unsuccessful: incorrect credentials"); //TODO: Return or Redirect Unauthorized
Ok(Response::builder()
.status(StatusCode::UNAUTHORIZED)
.body(Body::from("Username or password is incorrect"))?)
}, },
} };
Ok(String::new())
} }
pub async fn post_sign_up(Json(body): Json<User>) -> ApiResult { pub async fn post_sign_up(Json(body): Json<User>) -> Result<(), AppError> {
let id = "guest_user";
macro_info_log!(&Utc::now().to_string(), &id, "Sign-up request initiated");
let db = get_users().await?; let db = get_users().await?;
let query = to_document(&body)?; let query = to_document(&body)?;
match db.find_one(query.clone(), None).await? { match db.find_one(query, None).await? {
Some(_user) => { Some(_user) => {
macro_info_log!(&Utc::now().to_string(), &id, "Sign-up request unsuccessful: username already exists"); //TODO: Return or Redirect User Exists
Ok(Response::builder()
.status(StatusCode::NOT_ACCEPTABLE)
.body(Body::from("Username is already taken"))?)
}, },
None => { None => {
macro_info_log!(&Utc::now().to_string(), &id, "Sign-up request successful"); //TODO: Reutrn UsedId
db.insert_one(body, None).await?;
Ok(Response::builder()
.status(StatusCode::CREATED)
.body(Body::from("Account created successfully"))?)
} }
} }
Ok(())
} }
pub async fn post_sign_out(Path(user_id): Path<ObjectId>, auth: AuthenticationSession) -> ApiResult { pub async fn post_sign_out(auth: AuthenticationSession) {
let id = format!("user_id: {}", user_id);
macro_info_log!(&Utc::now().to_string(), &id, "Sign-out request initiated");
match auth.is_authenticated() { match auth.is_authenticated() {
true => { true => auth.logout_user(),
macro_info_log!(&Utc::now().to_string(), &id, "Sign-out request successful");
auth.logout_user();
Ok(Response::builder()
.status(StatusCode::OK)
.body(Body::from("Sign out successful"))?)
},
false => { false => {
macro_info_log!(&Utc::now().to_string(), &id, "Sign-out request unsuccessful: user was not logged in"); //TODO: Redirect Not Logged in
Ok(Response::builder()
.status(StatusCode::NOT_ACCEPTABLE)
.body(Body::from("No user is not logged in"))?)
}, },
} }
} }
pub async fn post_backup() {} //TODO: Backup pub async fn post_backup() {} //TODO: Backup
pub async fn get_restore() {} //TODO: restore pub async fn get_restore() {} //TODO: Restore

View File

@ -7,41 +7,31 @@ use axum::response::{IntoResponse, Response};
use axum_session::{SessionConfig, SessionLayer, SessionStore}; use axum_session::{SessionConfig, SessionLayer, SessionStore};
use axum_session_auth::{AuthConfig, AuthSessionLayer}; use axum_session_auth::{AuthConfig, AuthSessionLayer};
use axum_session_mongo::SessionMongoPool; use axum_session_mongo::SessionMongoPool;
use chrono::Utc;
use http::StatusCode; use http::StatusCode;
use mongodb::{bson::oid::ObjectId, Client}; use mongodb::{bson::oid::ObjectId, Client};
use rlg::{config::Config, macro_info_log};
pub async fn run() -> Result<()> { pub async fn run() -> Result<()> {
let id = "server";
init_logging();
macro_info_log!(&Utc::now().to_string(), id, "Server Initializing...");
let db = get_db_client().await?; let db = get_db_client().await?;
let session_store = session(db.clone()).await?; let session_store = session(db.clone()).await?;
let auth_config = AuthConfig::<ObjectId>::default(); let auth_config = AuthConfig::<ObjectId>::default();
macro_info_log!(&Utc::now().to_string(), id, "Routes Initializing...");
let app = router() let app = router()
.layer(SessionLayer::new(session_store)) .layer(SessionLayer::new(session_store))
.layer(AuthSessionLayer::<User, ObjectId, SessionMongoPool, Client> .layer(AuthSessionLayer::<User, ObjectId, SessionMongoPool, Client>
::new(Some(db)).with_config(auth_config) ::new(Some(db)).with_config(auth_config)
); );
macro_info_log!(&Utc::now().to_string(), id, "Routes Initialized");
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await?; axum::serve(listener, app).await?;
macro_info_log!(&Utc::now().to_string(), id, "Server Initialized");
Ok(()) Ok(())
} }
fn router() -> axum::Router { fn router() -> axum::Router {
axum::Router::new() axum::Router::new()
.nest("/account", account::router()) .nest("/account", account::router())
//.nest("/predict", model::router()) .nest("/predict", model::router())
} }
async fn session(db: Client) -> Result<SessionStore<SessionMongoPool>> { async fn session(db: Client) -> Result<SessionStore<SessionMongoPool>> {
@ -72,9 +62,3 @@ where
Self(err.into()) Self(err.into())
} }
} }
fn init_logging() {
std::env::set_var("LOG_FILE_PATH", "$HOME/.dermy/server.log");
let config = Config::load();
}