Move database into the main app

I was having issues including the lib as a crate, its fine just being a
module for now.
This commit is contained in:
Cameron Cordes
2020-07-07 21:48:29 -04:00
parent 1c1c8531aa
commit 2aa1b61429
13 changed files with 139 additions and 221 deletions

59
src/database/mod.rs Normal file
View File

@@ -0,0 +1,59 @@
use bcrypt::{hash, verify, DEFAULT_COST};
use diesel::prelude::*;
use diesel::sqlite::SqliteConnection;
use dotenv::dotenv;
use crate::database::models::{InsertUser, User};
mod models;
mod schema;
fn connect() -> SqliteConnection {
dotenv().ok();
let db_url = dotenv::var("DATABASE_URL").expect("DATABASE_URL must be set");
SqliteConnection::establish(&db_url).expect("Error connecting to DB")
}
// TODO: Should probably use Result here
pub fn create_user(user: &str, pass: &str) -> Option<User> {
use schema::users::dsl::*;
let hashed = hash(pass, DEFAULT_COST);
if let Ok(hash) = hashed {
let connection = connect();
diesel::insert_into(users)
.values(InsertUser {
username: user,
password: &hash,
})
.execute(&connection)
.unwrap();
match users
.filter(username.eq(user))
.load::<User>(&connection)
.unwrap()
.first()
{
Some(u) => Some(u.clone()),
None => None,
}
} else {
None
}
}
pub fn get_user(user: &str, pass: &str) -> Option<User> {
use schema::users::dsl::*;
match users
.filter(username.eq(user))
.load::<User>(&connect())
.unwrap_or(Vec::<User>::new())
.first()
{
Some(u) if verify(pass, &u.password).unwrap_or(false) => Some(u.clone()),
_ => None,
}
}

17
src/database/models.rs Normal file
View File

@@ -0,0 +1,17 @@
use crate::database::schema::users;
use serde::Serialize;
#[derive(Insertable)]
#[table_name = "users"]
pub struct InsertUser<'a> {
pub username: &'a str,
pub password: &'a str,
}
#[derive(Serialize, Queryable, Clone, Debug)]
pub struct User {
pub id: i32,
pub username: String,
#[serde(skip_serializing)]
pub password: String,
}

7
src/database/schema.rs Normal file
View File

@@ -0,0 +1,7 @@
table! {
users (id) {
id -> Integer,
username -> Text,
password -> Text,
}
}

View File

@@ -1,21 +1,32 @@
#[macro_use]
extern crate diesel;
use actix_web::web::{HttpResponse, Json};
use actix_web::{get, post, App, HttpServer, Responder};
use data::{LoginRequest, ThumbnailRequest};
use std::path::PathBuf;
use crate::files::list_files;
use crate::database::{create_user, get_user};
mod data;
mod database;
mod files;
#[post("/register")]
async fn register() -> impl Responder {
create_user("u", "p");
println!("{:?}", get_user("u", "p"));
"".to_owned()
}
#[post("/login")]
async fn login(_creds: Json<LoginRequest>) -> impl Responder {
"".to_owned()
async fn login(creds: Json<LoginRequest>) -> impl Responder {
if let Some(user) = get_user(&creds.username, &creds.password) {
HttpResponse::Ok().json(user)
} else {
HttpResponse::NotFound().finish()
}
}
#[get("/photos")]
@@ -43,7 +54,7 @@ async fn list_photos(req: Json<ThumbnailRequest>) -> impl Responder {
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(login).service(list_photos))
HttpServer::new(|| App::new().service(login).service(list_photos).service(register))
.bind("127.0.0.1:8088")?
.run()
.await