Move auth related methods to their own module

This commit is contained in:
Cameron Cordes
2021-02-18 20:31:29 -05:00
parent fae7b2a962
commit 8b5ba9d48c
2 changed files with 61 additions and 53 deletions

View File

@@ -2,71 +2,36 @@
extern crate diesel;
extern crate rayon;
use crate::auth::login;
use futures::stream::StreamExt;
use std::fs::File;
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::sync::{Arc};
use std::sync::mpsc::channel;
use std::sync::Arc;
use actix::{Actor, Addr};
use actix_files::NamedFile;
use actix_multipart as mp;
use actix_web::{App, get, HttpServer, post, Responder, web};
use actix_web::web::{HttpRequest, HttpResponse, Json};
use chrono::{Duration, Utc};
use futures::stream::StreamExt;
use jsonwebtoken::{encode, EncodingKey, Header};
use notify::{DebouncedEvent, RecursiveMode, watcher, Watcher};
use actix_web::{get, post, web, App, HttpServer, Responder};
use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher};
use rayon::prelude::*;
use serde::Serialize;
use data::{AddFavoriteRequest, LoginRequest, ThumbnailRequest};
use data::{AddFavoriteRequest, ThumbnailRequest};
use crate::data::{Claims, CreateAccountRequest, secret_key, Token};
use crate::database::{add_favorite, create_user, get_favorites, get_user, user_exists};
use crate::data::Claims;
use crate::database::{add_favorite, get_favorites};
use crate::files::{is_valid_path, list_files};
use crate::video::*;
mod auth;
mod data;
mod database;
mod files;
mod video;
#[post("/register")]
async fn register(user: Json<CreateAccountRequest>) -> impl Responder {
if !user.username.is_empty() && user.password.len() > 5 && user.password == user.confirmation {
if user_exists(&user.username) {
HttpResponse::BadRequest()
} else if let Some(_user) = create_user(&user.username, &user.password) {
HttpResponse::Ok()
} else {
HttpResponse::InternalServerError()
}
} else {
HttpResponse::BadRequest()
}
}
#[post("/login")]
async fn login(creds: Json<LoginRequest>) -> impl Responder {
println!("Logging in: {}", creds.username);
if let Some(user) = get_user(&creds.username, &creds.password) {
let claims = Claims {
sub: user.id.to_string(),
exp: (Utc::now() + Duration::days(5)).timestamp(),
};
let token = encode(
&Header::default(),
&claims,
&EncodingKey::from_secret(secret_key().as_bytes()),
)
.unwrap();
HttpResponse::Ok().json(Token { token: &token })
} else {
HttpResponse::NotFound().finish()
}
}
#[post("/photos")]
async fn list_photos(_claims: Claims, req: Json<ThumbnailRequest>) -> impl Responder {
println!("{}", req.path);
@@ -187,7 +152,8 @@ async fn generate_video(
let playlist = format!("tmp/{}.m3u8", filename);
if let Some(path) = is_valid_path(&body.path) {
if let Ok(child) = create_playlist(&path.to_str().unwrap(), &playlist) {
data.stream_manager.do_send(ProcessMessage(playlist.clone(), child));
data.stream_manager
.do_send(ProcessMessage(playlist.clone(), child));
}
} else {
return HttpResponse::BadRequest().finish();
@@ -291,7 +257,7 @@ fn create_thumbnails() {
.filter(|entry| {
let path = entry.path();
let relative_path = &path.strip_prefix(&images).unwrap();
let thumb_path = Path::new(thumbnail_directory).join(relative_path);
let thumb_path = Path::new(thumbnail_directory).join(dbg!(relative_path));
!thumb_path.exists()
})
.map(|entry| (image::open(entry.path()), entry.path().to_path_buf()))
@@ -303,7 +269,7 @@ fn create_thumbnails() {
let thumb_path = Path::new(thumbnail_directory).join(relative_path);
std::fs::create_dir_all(&thumb_path.parent().unwrap())
.expect("There was an issue creating directory");
println!("{:?}", thumb_path);
println!("Saving thumbnail: {:?}", thumb_path);
image.save(thumb_path).expect("Failure saving thumbnail");
})
.for_each(drop);
@@ -322,11 +288,10 @@ fn main() -> std::io::Result<()> {
.unwrap();
loop {
let ev = wrx.recv_timeout(std::time::Duration::from_secs(10));
let ev = wrx.recv();
if let Ok(event) = ev {
match event {
DebouncedEvent::Create(_) => create_thumbnails(),
DebouncedEvent::Rename(_, _) => create_thumbnails(),
DebouncedEvent::Create(_) | DebouncedEvent::Rename(_, _) => create_thumbnails(),
_ => continue,
};
}
@@ -353,9 +318,9 @@ fn main() -> std::io::Result<()> {
.service(post_add_favorite)
.app_data(app_data.clone())
})
.bind(dotenv::var("BIND_URL").unwrap())?
.bind("localhost:8088")?
.run();
.bind(dotenv::var("BIND_URL").unwrap())?
.bind("localhost:8088")?
.run();
system.run()
}