Skip to content

Commit

Permalink
Merge pull request #79 from kochamaltki/hasz
Browse files Browse the repository at this point in the history
Hasz
  • Loading branch information
malinowy5 authored Apr 28, 2024
2 parents 814bcfd + 60e5bad commit a46f92d
Show file tree
Hide file tree
Showing 9 changed files with 86 additions and 85 deletions.
2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ tokio = { version = "1", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }
tokio-rusqlite = "0.5"
jsonwebtoken = "=7.2"
argon2 = "0.5.3"
time = "0.3"
tracing = "0.1"
tracing-subscriber = "0.3"
uuid = { version = "0.8", features = ["v4"] }
futures = { version = "0.3", default-features = false }
bytes = "1.0"

35 changes: 17 additions & 18 deletions src/api_calls.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::database_functions::*;
use crate::get_token::get_token;
use crate::types::*;
use crate::verify_token::{self};
use crate::auth::*;
use bytes::BufMut;
use futures::{StreamExt, TryStreamExt};

Expand Down Expand Up @@ -495,7 +494,7 @@ pub async fn get_images_from_post(post_id: i64) -> Result<impl warp::Reply, warp

pub async fn validate_token(token: Option<String>) -> Result<impl warp::Reply, warp::Rejection> {
match token {
Some(token) => match verify_token::verify_token(token) {
Some(token) => match verify_token(token) {
Ok(val) => {
let r = val.claims.uid;
Ok(warp::reply::with_status(
Expand Down Expand Up @@ -525,7 +524,7 @@ pub async fn post(
token: String,
request: PostCreateRequest,
) -> Result<impl warp::Reply, warp::Rejection> {
let token = match verify_token::verify_token(token) {
let token = match verify_token(token) {
Ok(val) => val,
Err(_) => {
let r = "Wrong token";
Expand Down Expand Up @@ -594,7 +593,7 @@ pub async fn react(
token: String,
request: LikeRequest,
) -> Result<impl warp::Reply, warp::Rejection> {
let token = match verify_token::verify_token(token) {
let token = match verify_token(token) {
Ok(val) => val,
Err(_) => {
let r = "Wrong token";
Expand Down Expand Up @@ -656,7 +655,7 @@ pub async fn unreact(
token: String,
request: UnlikeRequest,
) -> Result<impl warp::Reply, warp::Rejection> {
let token = match verify_token::verify_token(token) {
let token = match verify_token(token) {
Ok(val) => val,
Err(_) => {
let r = "Wrong token";
Expand Down Expand Up @@ -733,13 +732,13 @@ pub async fn login(request: LoginRequest) -> Result<impl warp::Reply, warp::Reje
let name = request.user_name;

match get_id_passwd_adm(&connection, name.clone()).await {
Ok((user_id, passwd, is_admin)) => {
Ok((user_id, hash, is_admin)) => {
if check_banned(&connection, user_id).await {
info!("Can't log in user {}, reason - ban", user_id);
return Err(warp::reject::custom(UserBanned));
};

if passwd == request.passwd {
if verify_hash(request.passwd, hash) {
info!("User {} logged in", name);
let token = get_token(user_id, is_admin);
let mut cookie_params =
Expand All @@ -762,7 +761,7 @@ pub async fn login(request: LoginRequest) -> Result<impl warp::Reply, warp::Reje
}

pub async fn logout(token: String) -> Result<impl warp::Reply, warp::Rejection> {
match verify_token::verify_token(token) {
match verify_token(token) {
Ok(_) => {}
Err(_) => {
return Err(warp::reject::custom(WrongToken));
Expand Down Expand Up @@ -812,7 +811,7 @@ pub async fn delete_user(
_request: UserDeleteRequest,
) -> Result<impl warp::Reply, warp::Rejection> {
info!("{}", token);
let token = match verify_token::verify_token(token) {
let token = match verify_token(token) {
Ok(val) => val,
Err(_) => {
return Err(warp::reject::custom(WrongToken));
Expand Down Expand Up @@ -849,7 +848,7 @@ pub async fn upgrade_user(
token: String,
request: UserUpgradeRequest,
) -> Result<impl warp::Reply, warp::Rejection> {
let token = match verify_token::verify_token(token) {
let token = match verify_token(token) {
Ok(val) => val,
Err(_) => {
let r = "Wrong token";
Expand Down Expand Up @@ -902,7 +901,7 @@ pub async fn ban_user(
token: String,
request: UserBanRequest,
) -> Result<impl warp::Reply, warp::Rejection> {
let token = match verify_token::verify_token(token) {
let token = match verify_token(token) {
Ok(val) => val,
Err(_) => {
let r = "Wrong token";
Expand Down Expand Up @@ -962,7 +961,7 @@ pub async fn unban_user(
token: String,
request: UserUnbanRequest,
) -> Result<impl warp::Reply, warp::Rejection> {
let token = match verify_token::verify_token(token) {
let token = match verify_token(token) {
Ok(val) => val,
Err(_) => {
let r = "Wrong token";
Expand Down Expand Up @@ -1015,7 +1014,7 @@ pub async fn change_display_name(
token: String,
request: DisplayNameChangeRequest,
) -> Result<impl warp::Reply, warp::Rejection> {
let token = match verify_token::verify_token(token) {
let token = match verify_token(token) {
Ok(val) => val,
Err(_) => {
let r = "Wrong token";
Expand Down Expand Up @@ -1075,7 +1074,7 @@ pub async fn change_description(
token: String,
request: DescriptionChangeRequest,
) -> Result<impl warp::Reply, warp::Rejection> {
let token = match verify_token::verify_token(token) {
let token = match verify_token(token) {
Ok(val) => val,
Err(_) => {
let r = "Wrong token";
Expand Down Expand Up @@ -1132,7 +1131,7 @@ pub async fn upload_image(
token: String,
form: FormData,
) -> Result<impl warp::Reply, warp::Rejection> {
let token = match verify_token::verify_token(token) {
let token = match verify_token(token) {
Ok(val) => val,
Err(_) => {
let r = "Wrong token";
Expand Down Expand Up @@ -1244,7 +1243,7 @@ pub async fn set_pfp(
.await
.unwrap();

let token = match verify_token::verify_token(token) {
let token = match verify_token(token) {
Ok(val) => val,
Err(_) => {
let r = "Wrong token";
Expand Down Expand Up @@ -1304,7 +1303,7 @@ pub async fn add_image_to_post(
.await
.unwrap();

let token = match verify_token::verify_token(token) {
let token = match verify_token(token) {
Ok(val) => val,
Err(_) => {
let r = "Wrong token";
Expand Down
53 changes: 53 additions & 0 deletions src/auth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
use argon2::{password_hash::{rand_core::OsRng, PasswordHash, PasswordHasher, PasswordVerifier, SaltString}, Argon2};
// argon2 jest wolny generalnie ale nie az tak jak jest teraz, zmiana na release build powinna przyspieszyc
// https://www.reddit.com/r/rust/comments/1ajkqd7/argon2_slow_is_hashing_password/
use jsonwebtoken::{decode, encode, errors, EncodingKey, Header, DecodingKey, Validation, Algorithm, TokenData};
use std::time::SystemTime;
use std::fs;
use crate::types::Claims;

pub fn get_secret() -> String{
let contents = fs::read_to_string("./SECRET")
.expect("Should have been able to read the file");
contents
}

fn get_sys_time_in_secs() -> u64 {
match SystemTime::now().duration_since(SystemTime::UNIX_EPOCH) {
Ok(n) => n.as_secs(),
Err(_) => panic!("SystemTime before UNIX EPOCH!"),
}
}

pub fn get_token(user_id: i64, is_admin_value: i64) -> String {
let file_contents = get_secret();
let jwt_secret = file_contents.as_str().trim();
let expiration = get_sys_time_in_secs() + 1209600; // wazny przez 10 dni

let claims = Claims {
uid: user_id,
exp: expiration,
is_admin: is_admin_value
};
let header = Header::new(Algorithm::HS256);
let tkn = encode(&header, &claims, &EncodingKey::from_base64_secret(jwt_secret).expect("Nie udalo sie zdekodowac sekretu"));
tkn.expect("REASON")
}

pub fn verify_token(token: String) -> Result<TokenData<Claims>, errors::Error>{
let file_contents = get_secret();
let jwt_secret = file_contents.as_str().trim();
// Claims is a struct that implements Deserialize
decode::<Claims>(&token, &DecodingKey::from_base64_secret(jwt_secret).expect("Nie udalo sie zdekodowac sekretu"), &Validation::new(Algorithm::HS256))
}

pub fn get_hash(password: String) -> String {
let salt = SaltString::generate(&mut OsRng);
let argon2 = Argon2::default();
argon2.hash_password(password.as_bytes(), &salt).unwrap().to_string()
}

pub fn verify_hash(password: String, hash: String) -> bool {
let parsed_hash = PasswordHash::new(&hash).unwrap();
Argon2::default().verify_password(password.as_bytes(), &parsed_hash).is_ok()
}
8 changes: 5 additions & 3 deletions src/database_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ use tokio_rusqlite::{Connection, params};
use tracing::info;


use crate::{get_token::get_token, types::{Post, SignupRequest}};
use crate::types::{Post, SignupRequest};
use crate::auth::*;

pub async fn check_user_id(connection: &Connection, id: i64) -> bool {
let query = "SELECT user_id FROM users WHERE user_id = ?";
Expand Down Expand Up @@ -293,11 +294,12 @@ pub async fn add_post_db(connection: &Connection, post: Post, tags: Vec<String>)
pub async fn add_user_db(connection: &Connection, request: SignupRequest) -> String {
let user_id = max_user_id(connection).await.unwrap();
let user_name = request.user_name.clone();

let password = request.passwd.clone();
let password_hash = get_hash(password);
let signup_query = "INSERT INTO users VALUES (:user_id, :user_name, :user_name, '', :passwd, 0, '')";
connection.call(move |conn| {
let mut statement = conn.prepare(signup_query).unwrap();
statement.execute(params![user_id, request.user_name, request.passwd]).unwrap();
statement.execute(params![user_id, request.user_name, password_hash]).unwrap();
Ok(0)
}).await.unwrap();

Expand Down
7 changes: 0 additions & 7 deletions src/get_secret.rs

This file was deleted.

36 changes: 0 additions & 36 deletions src/get_token.rs

This file was deleted.

6 changes: 2 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use warp::Filter;
pub mod get_token;
pub mod get_secret;
pub mod verify_token;
pub mod auth;
pub mod api_calls;
pub mod types;
pub mod database_functions;
Expand Down Expand Up @@ -192,6 +190,6 @@ async fn main() {
.allow_headers(vec!["content-type", "Access-Control-Allow-Origin"])
.allow_credentials(true);

let routes = routes().recover(handle_rejection).with(cors);
let routes = routes().recover(handle_rejection).with(cors); // change back to do error handling
warp::serve(routes).run(([0, 0, 0, 0], 8000)).await;
}
7 changes: 7 additions & 0 deletions src/types.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
use serde::{Serialize, Deserialize};

#[derive(Debug, Serialize, Deserialize)]
pub struct Claims {
pub uid: i64,
pub exp: u64,
pub is_admin: i64,
}

#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Post {
pub post_id: i64,
Expand Down
17 changes: 0 additions & 17 deletions src/verify_token.rs

This file was deleted.

0 comments on commit a46f92d

Please sign in to comment.