Working on auth

This commit is contained in:
Benjamin Sherriff
2023-10-17 20:49:27 -04:00
parent 140488c925
commit 3b15f520c8
18 changed files with 454 additions and 49 deletions

View File

@@ -6,6 +6,9 @@ DATABASE_NAME=siren
DATABASE_HOST=localhost
DATABASE_PORT=5432
REDIS_HOST=localhost
REDIS_PORT=6379
SERVICE_HOST=localhost
SERVICE_PORT=5000
DATA_DIR_PATH=

View File

@@ -16,6 +16,8 @@ actix-web = "4.4.0"
actix-rt = "2.9.0"
actix-cors = "0.6.4"
actix-web-httpauth = "0.8.1"
actix-identity = "0.6.0"
actix-session = { version = "0.8.0", features = ["redis-actor-session", "cookie-session"] }
chrono = { version = "0.4.31", features = ["serde"] }
dotenv = "0.15.0"
serde_json = "1.0.107"
@@ -25,6 +27,7 @@ diesel_migrations = { version = "2.1.0", features = ["postgres"] }
r2d2 = "0.8.10"
lazy_static = "1.4.0"
uuid = { version = "1.4.1", features = ["serde", "v4"] }
argon2 = "0.5.2"
[dependencies.tokio]
version = "1.32.0"

View File

@@ -15,6 +15,7 @@ build: ## Build the docker image
utils: ## Start the utils
docker compose up -d db
docker compose up -d redis
up: ## Start the app
docker compose up -d

View File

@@ -15,6 +15,8 @@ services:
environment:
DATABASE_HOST: db
DATABASE_PORT: 5432
REDIS_HOST: redis
REDIS_PORT: 6379
SERVICE_HOST: service
SERVICE_PORT: 5000
DATA_DIR_PATH: /data
@@ -45,6 +47,14 @@ services:
networks:
- backend
restart: unless-stopped
redis:
image: redis:latest
container_name: siren-redis
ports:
- ${REDIS_PORT:-6379}:6379
networks:
- backend
restart: unless-stopped
volumes:
db:

View File

@@ -0,0 +1 @@
DROP TABLE users;

View File

@@ -0,0 +1,7 @@
CREATE TABLE IF NOT EXISTS users (
email TEXT PRIMARY KEY NOT NULL,
hash TEXT NOT NULL,
role TEXT NOT NULL,
first_name TEXT NOT NULL,
last_name TEXT NOT NULL
);

View File

@@ -37,4 +37,14 @@ diesel::table! {
bot_id -> BigInt,
volume -> Integer,
}
}
diesel::table! {
users (email) {
email -> Text,
hash -> Text,
role -> Text,
first_name -> Text,
last_name -> Text,
}
}

View File

@@ -1,3 +1,5 @@
mod model;
mod routes;
pub use model::*;
pub use routes::init_routes;

View File

@@ -1,37 +1,140 @@
use actix_web::{dev::ServiceRequest, Error};
use actix_web_httpauth::extractors::bearer::BearerAuth;
use std::future::{ready, Ready};
use actix_identity::Identity;
use actix_web::{FromRequest, Error as ActixError, HttpRequest, dev::Payload};
use argon2::{password_hash::{rand_core::OsRng, PasswordHasher, PasswordVerifier, SaltString, Error as HashError}, Argon2, PasswordHash};
use diesel::prelude::*;
use serde::{Serialize, Deserialize};
use siren::ServiceError;
pub struct User {
pub id: i32,
use crate::db::schema::users;
#[derive(Debug, Serialize, Deserialize)]
pub struct RegisterUser {
pub email: String,
pub password: String,
pub first_name: String,
pub last_name: String,
}
impl RegisterUser {
pub fn convert_to_insert(self) -> Result<InsertUser, ServiceError> {
let hash = hash(self.password.as_bytes())?;
Ok(InsertUser {
email: self.email,
hash,
role: "user".to_string(),
first_name: self.first_name,
last_name: self.last_name,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LoginAuth {
pub email: String,
pub password: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LoggedUser {
pub email: String
}
impl FromRequest for LoggedUser {
type Error = ActixError;
type Future = Ready<Result<LoggedUser, ActixError>>;
fn from_request(req: &HttpRequest, pl: &mut Payload) -> Self::Future {
if let Ok(identity) = Identity::from_request(req, pl).into_inner() {
if let Ok(user_json) = identity.id() {
if let Ok(user) = serde_json::from_str(&user_json) {
return ready(Ok(user));
}
}
}
std::future::ready(Err(
ActixError::from(ServiceError {
status: 401,
message: "Unauthorized".to_string(),
})
))
}
}
#[derive(Debug, Queryable, QueryableByName, Serialize, Deserialize)]
#[diesel(table_name = users)]
pub struct QueryUser {
pub email: String,
pub hash: String,
pub role: String,
pub first_name: String,
pub last_name: String,
}
impl QueryUser {
pub fn get_by_email(email: &str) -> Result<QueryUser, ServiceError> {
let mut conn = crate::db::connection()?;
let user = users::table
.filter(users::email.eq(email))
.first(&mut conn)?;
Ok(user)
}
}
#[derive(Debug, Insertable, AsChangeset, Serialize, Deserialize)]
#[diesel(table_name = users)]
pub struct InsertUser {
pub email: String,
pub hash: String,
pub role: String,
pub first_name: String,
pub last_name: String,
}
impl InsertUser {
pub fn insert(user: Self) -> Result<QueryUser, ServiceError> {
let mut conn = crate::db::connection()?;
let user = diesel::insert_into(users::table)
.values(user)
.get_result(&mut conn)?;
Ok(user)
}
}
// https://github.com/Sirneij/rust-auth/blob/main/backend/src/routes/users/login.rs
// https://dev.to/sirneij/authentication-system-using-rust-actix-web-and-sveltekit-user-registration-580h
// https://github.com/actix/actix-extras/blob/master/actix-session/examples/basic.rs
// maybe https://github.com/actix/actix-extras/blob/master/actix-identity/examples/identity.rs
// https://www.lpalmieri.com/posts/session-based-authentication-in-rust/#3-3-1-postgres
pub async fn validator(req: ServiceRequest, credentials: BearerAuth) -> Result<ServiceRequest, (Error, ServiceRequest)> {
let token = credentials.token();
println!("{:?}", req);
match validate_token(token) {
Ok(res) => {
if res {
Ok(req)
} else {
Err((Error::from(actix_web::error::ErrorUnauthorized("Invalid token")), req))
}
},
Err(err) => {
Err((Error::from(actix_web::error::ErrorUnauthorized(err)), req))
}
}
// pub async fn validator(req: ServiceRequest, credentials: BearerAuth) -> Result<ServiceRequest, (ActixError, ServiceRequest)> {
// let token = credentials.token();
// println!("{:?}", req);
// match validate_token(token) {
// Ok(res) => {
// if res {
// Ok(req)
// } else {
// Err((ActixError::from(actix_web::error::ErrorUnauthorized("Invalid token")), req))
// }
// },
// Err(err) => {
// Err((ActixError::from(actix_web::error::ErrorUnauthorized(err)), req))
// }
// }
// }
// fn validate_token(token: &str) -> Result<bool, ServiceError> {
// println!("Validating token: {}", token);
// Ok(true)
// }
pub fn hash(password: &[u8]) -> Result<String, HashError> {
let salt = SaltString::generate(&mut OsRng);
Ok(Argon2::default().hash_password(password, &salt)?.to_string())
}
fn validate_token(token: &str) -> Result<bool, ServiceError> {
println!("Validating token: {}", token);
Ok(true)
}
pub fn verify(hash: &str, password: &[u8]) -> Result<(), HashError> {
let parsed_hash = PasswordHash::new(hash)?;
Ok(Argon2::default().verify_password(password, &parsed_hash)?)
}

View File

@@ -0,0 +1,75 @@
use actix_identity::Identity;
use actix_web::{get, post, web, HttpResponse, HttpRequest, ResponseError, HttpMessage};
use siren::ServiceError;
use crate::db::users::{LoginAuth, RegisterUser, InsertUser, QueryUser, verify, LoggedUser};
#[post("/register")]
async fn register(user: web::Json<RegisterUser>) -> HttpResponse {
let register_user = user.0;
let insert_user: InsertUser = match register_user.convert_to_insert() {
Ok(user) => user,
Err(err) => return ResponseError::error_response(&err)
};
match InsertUser::insert(insert_user) {
Ok(_) => {
HttpResponse::Created().finish()
},
Err(err) => {
// Obfuscate the service error message to prevent leaking database details
if err.status == 409 {
return HttpResponse::Conflict().finish();
} else {
return ResponseError::error_response(&err);
}
}
}
}
#[post("/login")]
async fn login(req: HttpRequest, auth: web::Json<LoginAuth>) -> HttpResponse {
let email = auth.email.clone();
match QueryUser::get_by_email(&email) {
Ok(query_user) => {
let hash = query_user.hash;
let password = auth.password.as_bytes();
match verify(&hash, password) {
Ok(_) => {
let user = LoggedUser {
email: email.clone()
};
let user_string = serde_json::to_string(&user).unwrap();
match Identity::login(&req.extensions(), user_string) {
Ok(_) => HttpResponse::Ok().finish(),
Err(err) => return ResponseError::error_response(&err)
}
},
Err(err) => ResponseError::error_response(&ServiceError {
status: 401,
message: err.to_string()
})
}
},
Err(err) => ResponseError::error_response(&err)
}
}
#[post("/logout")]
async fn logout(id: Identity) -> HttpResponse {
id.logout();
HttpResponse::Ok().finish()
}
#[get("/me")]
async fn me(user: LoggedUser) -> HttpResponse {
HttpResponse::Ok().json(user)
}
pub fn init_routes(config: &mut web::ServiceConfig) {
config.service(web::scope("users")
.service(register)
.service(login)
.service(logout)
.service(me));
}

View File

@@ -57,7 +57,14 @@ impl fmt::Display for ServiceError {
impl From<DieselError> for ServiceError {
fn from(error: DieselError) -> ServiceError {
match error {
DieselError::DatabaseError(_, err) => ServiceError::new(409, err.message().to_string()),
DieselError::DatabaseError(kind, err) => {
match kind {
diesel::result::DatabaseErrorKind::UniqueViolation => {
ServiceError::new(409, err.message().to_string())
},
_ => ServiceError::new(500, err.message().to_string())
}
},
DieselError::NotFound => {
ServiceError::new(404, "The record was not found".to_string())
},
@@ -87,6 +94,12 @@ impl From<serenity::Error> for ServiceError {
}
}
impl From<argon2::password_hash::Error> for ServiceError {
fn from(error: argon2::password_hash::Error) -> ServiceError {
ServiceError::new(500, format!("Unknown argon2 error: {}", error))
}
}
impl ResponseError for ServiceError {
fn error_response(&self) -> HttpResponse {
let status_code = match StatusCode::from_u16(self.status) {
@@ -101,4 +114,4 @@ impl ResponseError for ServiceError {
HttpResponse::build(status_code).json(serde_json::json!({ "status": status_code.as_u16(), "message": error_message }))
}
}
}

View File

@@ -5,8 +5,9 @@ extern crate diesel_migrations;
use std::env;
use std::collections::HashSet;
use std::sync::Arc;
use actix_web_httpauth::middleware::HttpAuthentication;
use db::users::validator;
use actix_identity::IdentityMiddleware;
use actix_session::{SessionMiddleware, storage::{RedisActorSessionStore, CookieSessionStore}, config::{PersistentSession, BrowserSession, CookieContentSecurity}};
// use db::users::validator;
use log::{error, warn, info};
use serenity::client::Cache;
use serenity::framework::StandardFramework;
@@ -15,7 +16,7 @@ use serenity::prelude::*;
use songbird::{SerenityInit, Songbird};
use actix_cors::Cors;
use actix_web::{HttpServer, App, web};
use actix_web::{HttpServer, App, web, cookie::{time::Duration, SameSite}};
use crate::bot::{commands::oai::GPTModel, handler::Handler};
use dotenv::dotenv;
@@ -113,18 +114,39 @@ async fn main() -> std::io::Result<()> {
let port = env::var("SERVICE_PORT").unwrap_or("5000".to_string());
let server = match HttpServer::new(move || {
let auth = HttpAuthentication::bearer(validator);
// let auth = HttpAuthentication::bearer(validator);
let private_key = actix_web::cookie::Key::generate();
// let redis_host = env::var("REDIS_HOST").unwrap_or("localhost".to_string());
// let redis_port = env::var("REDIS_PORT").unwrap_or("6379".to_string());
let session = SessionMiddleware::builder(
// RedisActorSessionStore::new(format!("{}:{}", redis_host, redis_port)),
CookieSessionStore::default(),
private_key
)
.session_lifecycle(BrowserSession::default())
.cookie_name("auth".to_owned())
.cookie_secure(false)
.cookie_http_only(false)
// .cookie_content_security(CookieContentSecurity::Private)
.cookie_domain(Some("localhost".to_owned()))
.cookie_path("/".to_owned())
.build();
let cors = Cors::default()
.allow_any_origin()
.allow_any_method()
.allow_any_header()
.supports_credentials()
.max_age(3600);
// let cors = Cors::permissive();
App::new()
.wrap(auth)
// .wrap(auth)
.wrap(IdentityMiddleware::default())
.wrap(session)
.wrap(cors)
.app_data(web::Data::new(Arc::clone(&app_data)))
.configure(crate::db::messages::init_routes)
.configure(crate::db::spells::init_routes)
.configure(crate::db::users::init_routes)
.configure(crate::bot::api::init_routes)
})
.bind(format!("{}:{}", host, port)) {