Setup Auth DB
This commit is contained in:
62
database/src/lib.rs
Normal file
62
database/src/lib.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
#[macro_use]
|
||||
extern crate diesel;
|
||||
|
||||
use bcrypt::{hash, verify, DEFAULT_COST};
|
||||
use diesel::prelude::*;
|
||||
use diesel::sqlite::SqliteConnection;
|
||||
use dotenv::dotenv;
|
||||
|
||||
use crate::models::{InsertUser, User};
|
||||
|
||||
pub mod models;
|
||||
pub 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,
|
||||
}
|
||||
}
|
||||
15
database/src/models.rs
Normal file
15
database/src/models.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
use crate::schema::users;
|
||||
|
||||
#[derive(Insertable)]
|
||||
#[table_name = "users"]
|
||||
pub struct InsertUser<'a> {
|
||||
pub username: &'a str,
|
||||
pub password: &'a str,
|
||||
}
|
||||
|
||||
#[derive(Queryable, Clone)]
|
||||
pub struct User {
|
||||
pub id: i32,
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
7
database/src/schema.rs
Normal file
7
database/src/schema.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
table! {
|
||||
users (id) {
|
||||
id -> Integer,
|
||||
username -> Text,
|
||||
password -> Text,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user