feat: integrate token authentication
This commit is contained in:
parent
1d0f8ecd00
commit
725a16d1f5
6 changed files with 154 additions and 32 deletions
|
@ -1,10 +1,12 @@
|
||||||
|
use std::time::{SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use actix_web::{error, post, web, Error, HttpResponse};
|
use actix_web::{error, post, web, Error, HttpResponse};
|
||||||
use argon2::{Argon2, PasswordHash, PasswordVerifier};
|
use argon2::{Argon2, PasswordHash, PasswordVerifier};
|
||||||
use regex::Regex;
|
use regex::Regex;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
|
|
||||||
use crate::Data;
|
use crate::{crypto::{generate_access_token, generate_refresh_token}, Data};
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct LoginInformation {
|
struct LoginInformation {
|
||||||
|
@ -23,7 +25,7 @@ struct Response {
|
||||||
const MAX_SIZE: usize = 262_144;
|
const MAX_SIZE: usize = 262_144;
|
||||||
|
|
||||||
#[post("/login")]
|
#[post("/login")]
|
||||||
pub async fn res(mut payload: web::Payload, data: web::Data<Data>) -> Result<HttpResponse, Error> {
|
pub async fn response(mut payload: web::Payload, data: web::Data<Data>) -> Result<HttpResponse, Error> {
|
||||||
let mut body = web::BytesMut::new();
|
let mut body = web::BytesMut::new();
|
||||||
while let Some(chunk) = payload.next().await {
|
while let Some(chunk) = payload.next().await {
|
||||||
let chunk = chunk?;
|
let chunk = chunk?;
|
||||||
|
@ -49,14 +51,16 @@ pub async fn res(mut payload: web::Payload, data: web::Data<Data>) -> Result<Htt
|
||||||
}
|
}
|
||||||
|
|
||||||
if email_regex.is_match(&login_information.username) {
|
if email_regex.is_match(&login_information.username) {
|
||||||
if let Ok(password) = sqlx::query_scalar("SELECT password FROM users WHERE email = $1").bind(login_information.username).fetch_one(&data.pool).await {
|
if let Ok(row) = sqlx::query_as("SELECT CAST(uuid as VARCHAR), password FROM users WHERE email = $1").bind(login_information.username).fetch_one(&data.pool).await {
|
||||||
return Ok(login(data.argon2.clone(), login_information.password, password))
|
let (uuid, password): (String, String) = row;
|
||||||
|
return Ok(login(data.clone(), uuid, login_information.password, password).await)
|
||||||
}
|
}
|
||||||
|
|
||||||
return Ok(HttpResponse::Unauthorized().finish())
|
return Ok(HttpResponse::Unauthorized().finish())
|
||||||
} else if username_regex.is_match(&login_information.username) {
|
} else if username_regex.is_match(&login_information.username) {
|
||||||
if let Ok(password) = sqlx::query_scalar("SELECT password FROM users WHERE username = $1").bind(login_information.username).fetch_one(&data.pool).await {
|
if let Ok(row) = sqlx::query_as("SELECT CAST(uuid as VARCHAR), password FROM users WHERE username = $1").bind(login_information.username).fetch_one(&data.pool).await {
|
||||||
return Ok(login(data.argon2.clone(), login_information.password, password))
|
let (uuid, password): (String, String) = row;
|
||||||
|
return Ok(login(data.clone(), uuid, login_information.password, password).await)
|
||||||
}
|
}
|
||||||
|
|
||||||
return Ok(HttpResponse::Unauthorized().finish())
|
return Ok(HttpResponse::Unauthorized().finish())
|
||||||
|
@ -65,9 +69,47 @@ pub async fn res(mut payload: web::Payload, data: web::Data<Data>) -> Result<Htt
|
||||||
Ok(HttpResponse::Unauthorized().finish())
|
Ok(HttpResponse::Unauthorized().finish())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn login(argon2: Argon2, request_password: String, database_password: String) -> HttpResponse {
|
async fn login(data: actix_web::web::Data<Data>, uuid: String, request_password: String, database_password: String) -> HttpResponse {
|
||||||
if let Ok(parsed_hash) = PasswordHash::new(&database_password) {
|
if let Ok(parsed_hash) = PasswordHash::new(&database_password) {
|
||||||
if argon2.verify_password(request_password.as_bytes(), &parsed_hash).is_ok() {
|
if data.argon2.verify_password(request_password.as_bytes(), &parsed_hash).is_ok() {
|
||||||
|
let refresh_token = generate_refresh_token();
|
||||||
|
let access_token = generate_access_token();
|
||||||
|
|
||||||
|
if refresh_token.is_err() {
|
||||||
|
eprintln!("{}", refresh_token.unwrap_err());
|
||||||
|
return HttpResponse::InternalServerError().finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
let refresh_token = refresh_token.unwrap();
|
||||||
|
|
||||||
|
if access_token.is_err() {
|
||||||
|
eprintln!("{}", access_token.unwrap_err());
|
||||||
|
return HttpResponse::InternalServerError().finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
let access_token = access_token.unwrap();
|
||||||
|
|
||||||
|
let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
|
||||||
|
|
||||||
|
if let Err(error) = sqlx::query(&format!("INSERT INTO refresh_tokens (token, uuid, created) VALUES ($1, '{}', $2 )", uuid))
|
||||||
|
.bind(&refresh_token)
|
||||||
|
.bind(current_time)
|
||||||
|
.execute(&data.pool)
|
||||||
|
.await {
|
||||||
|
eprintln!("{}", error);
|
||||||
|
return HttpResponse::InternalServerError().finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Err(error) = sqlx::query(&format!("INSERT INTO refresh_tokens (token, refresh_token, uuid, created) VALUES ($1, $2, '{}', $3 )", uuid))
|
||||||
|
.bind(&access_token)
|
||||||
|
.bind(&refresh_token)
|
||||||
|
.bind(current_time)
|
||||||
|
.execute(&data.pool)
|
||||||
|
.await {
|
||||||
|
eprintln!("{}", error);
|
||||||
|
return HttpResponse::InternalServerError().finish()
|
||||||
|
}
|
||||||
|
|
||||||
return HttpResponse::Ok().json(Response {
|
return HttpResponse::Ok().json(Response {
|
||||||
access_token: "bogus".to_string(),
|
access_token: "bogus".to_string(),
|
||||||
expires_in: 0,
|
expires_in: 0,
|
||||||
|
|
|
@ -7,6 +7,6 @@ mod refresh;
|
||||||
pub fn web() -> Scope {
|
pub fn web() -> Scope {
|
||||||
web::scope("/auth")
|
web::scope("/auth")
|
||||||
.service(register::res)
|
.service(register::res)
|
||||||
.service(login::res)
|
.service(login::response)
|
||||||
.service(refresh::res)
|
.service(refresh::res)
|
||||||
}
|
}
|
||||||
|
|
|
@ -3,7 +3,7 @@ use actix_web::{error, post, web, Error, HttpResponse};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use futures::StreamExt;
|
use futures::StreamExt;
|
||||||
|
|
||||||
use crate::Data;
|
use crate::{crypto::{generate_access_token, generate_refresh_token}, Data};
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct RefreshRequest {
|
struct RefreshRequest {
|
||||||
|
@ -12,9 +12,8 @@ struct RefreshRequest {
|
||||||
|
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
struct Response {
|
struct Response {
|
||||||
refresh_token: Option<String>,
|
refresh_token: String,
|
||||||
access_token: String,
|
access_token: String,
|
||||||
expires_in: u64,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_SIZE: usize = 262_144;
|
const MAX_SIZE: usize = 262_144;
|
||||||
|
@ -35,15 +34,82 @@ pub async fn res(mut payload: web::Payload, data: web::Data<Data>) -> Result<Htt
|
||||||
|
|
||||||
let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
|
let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
|
||||||
|
|
||||||
let row: (String, i64) = sqlx::query_as("SELECT CAST(uuid as VARCHAR), created FROM refresh_tokens WHERE token = $1")
|
if let Ok(row) = sqlx::query_as("SELECT CAST(uuid as VARCHAR), created FROM refresh_tokens WHERE token = $1").bind(&refresh_request.refresh_token).fetch_one(&data.pool).await {
|
||||||
.bind(refresh_request.refresh_token)
|
let (uuid, created): (String, i64) = row;
|
||||||
.fetch_one(&data.pool)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let (uuid, created) = row;
|
if let Err(error) = sqlx::query("DELETE FROM access_tokens WHERE refresh_token = $1")
|
||||||
|
.bind(&refresh_request.refresh_token)
|
||||||
println!("{}, {}", uuid, created);
|
.execute(&data.pool)
|
||||||
|
.await {
|
||||||
Ok(HttpResponse::InternalServerError().finish())
|
eprintln!("{}", error);
|
||||||
|
}
|
||||||
|
|
||||||
|
let lifetime = current_time - created;
|
||||||
|
|
||||||
|
if lifetime > 2592000 {
|
||||||
|
if let Err(error) = sqlx::query("DELETE FROM refresh_tokens WHERE token = $1")
|
||||||
|
.bind(&refresh_request.refresh_token)
|
||||||
|
.execute(&data.pool)
|
||||||
|
.await {
|
||||||
|
eprintln!("{}", error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(HttpResponse::Unauthorized().finish())
|
||||||
|
}
|
||||||
|
|
||||||
|
let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
|
||||||
|
|
||||||
|
let mut refresh_token = refresh_request.refresh_token;
|
||||||
|
|
||||||
|
if lifetime > 1987200 {
|
||||||
|
let new_refresh_token = generate_refresh_token();
|
||||||
|
|
||||||
|
if new_refresh_token.is_err() {
|
||||||
|
eprintln!("{}", new_refresh_token.unwrap_err());
|
||||||
|
return Ok(HttpResponse::InternalServerError().finish())
|
||||||
|
}
|
||||||
|
|
||||||
|
let new_refresh_token = new_refresh_token.unwrap();
|
||||||
|
|
||||||
|
match sqlx::query(&format!("UPDATE refresh_tokens SET token = $1, uuid = {}, created = $2 WHERE token = $3", uuid))
|
||||||
|
.bind(&new_refresh_token)
|
||||||
|
.bind(¤t_time)
|
||||||
|
.bind(&refresh_token)
|
||||||
|
.execute(&data.pool)
|
||||||
|
.await {
|
||||||
|
Ok(_) => {
|
||||||
|
refresh_token = new_refresh_token;
|
||||||
|
},
|
||||||
|
Err(error) => {
|
||||||
|
eprintln!("{}", error);
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let access_token = generate_access_token();
|
||||||
|
|
||||||
|
if access_token.is_err() {
|
||||||
|
eprintln!("{}", access_token.unwrap_err());
|
||||||
|
return Ok(HttpResponse::InternalServerError().finish())
|
||||||
|
}
|
||||||
|
|
||||||
|
let access_token = access_token.unwrap();
|
||||||
|
|
||||||
|
if let Err(error) = sqlx::query(&format!("INSERT INTO access_tokens (token, refresh_token, uuid, created) VALUES ($1, $2, '{}', $3 )", uuid))
|
||||||
|
.bind(&access_token)
|
||||||
|
.bind(&refresh_token)
|
||||||
|
.bind(current_time)
|
||||||
|
.execute(&data.pool)
|
||||||
|
.await {
|
||||||
|
eprintln!("{}", error);
|
||||||
|
return Ok(HttpResponse::InternalServerError().finish())
|
||||||
|
}
|
||||||
|
|
||||||
|
return Ok(HttpResponse::Ok().json(Response {
|
||||||
|
refresh_token,
|
||||||
|
access_token
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(HttpResponse::Unauthorized().finish())
|
||||||
}
|
}
|
||||||
|
|
|
@ -7,7 +7,7 @@ use futures::StreamExt;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
use argon2::{password_hash::{rand_core::OsRng, SaltString}, PasswordHasher};
|
use argon2::{password_hash::{rand_core::OsRng, SaltString}, PasswordHasher};
|
||||||
|
|
||||||
use crate::Data;
|
use crate::{crypto::{generate_access_token, generate_refresh_token}, Data};
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct AccountInformation {
|
struct AccountInformation {
|
||||||
|
@ -95,7 +95,7 @@ pub async fn res(mut payload: web::Payload, data: web::Data<Data>) -> Result<Htt
|
||||||
}
|
}
|
||||||
|
|
||||||
// Password is expected to be hashed using SHA3-384
|
// Password is expected to be hashed using SHA3-384
|
||||||
let password_regex = Regex::new(r"/[0-9a-f]{96}/i").unwrap();
|
let password_regex = Regex::new(r"[0-9a-f]{96}").unwrap();
|
||||||
|
|
||||||
if !password_regex.is_match(&account_information.password) {
|
if !password_regex.is_match(&account_information.password) {
|
||||||
return Ok(HttpResponse::Forbidden().json(
|
return Ok(HttpResponse::Forbidden().json(
|
||||||
|
@ -110,7 +110,7 @@ pub async fn res(mut payload: web::Payload, data: web::Data<Data>) -> Result<Htt
|
||||||
|
|
||||||
if let Ok(hashed_password) = data.argon2.hash_password(account_information.password.as_bytes(), &salt) {
|
if let Ok(hashed_password) = data.argon2.hash_password(account_information.password.as_bytes(), &salt) {
|
||||||
// TODO: Check security of this implementation
|
// TODO: Check security of this implementation
|
||||||
return Ok(match sqlx::query(&format!("INSERT INTO users (uuid, username, password, email,) VALUES ( '{}', $1, $2, $3 )", uuid))
|
return Ok(match sqlx::query(&format!("INSERT INTO users (uuid, username, password, email) VALUES ( '{}', $1, $2, $3 )", uuid))
|
||||||
.bind(account_information.identifier)
|
.bind(account_information.identifier)
|
||||||
// FIXME: Password has no security currently, either from a client or server perspective
|
// FIXME: Password has no security currently, either from a client or server perspective
|
||||||
.bind(hashed_password.to_string())
|
.bind(hashed_password.to_string())
|
||||||
|
@ -118,13 +118,27 @@ pub async fn res(mut payload: web::Payload, data: web::Data<Data>) -> Result<Htt
|
||||||
.execute(&data.pool)
|
.execute(&data.pool)
|
||||||
.await {
|
.await {
|
||||||
Ok(_out) => {
|
Ok(_out) => {
|
||||||
let refresh_token = todo!();
|
let refresh_token = generate_refresh_token();
|
||||||
let access_token = todo!();
|
let access_token = generate_access_token();
|
||||||
|
|
||||||
|
if refresh_token.is_err() {
|
||||||
|
eprintln!("{}", refresh_token.unwrap_err());
|
||||||
|
return Ok(HttpResponse::InternalServerError().finish())
|
||||||
|
}
|
||||||
|
|
||||||
|
let refresh_token = refresh_token.unwrap();
|
||||||
|
|
||||||
|
if access_token.is_err() {
|
||||||
|
eprintln!("{}", access_token.unwrap_err());
|
||||||
|
return Ok(HttpResponse::InternalServerError().finish())
|
||||||
|
}
|
||||||
|
|
||||||
|
let access_token = access_token.unwrap();
|
||||||
|
|
||||||
let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
|
let current_time = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() as i64;
|
||||||
|
|
||||||
if let Err(error) = sqlx::query(&format!("INSERT INTO refresh_tokens (token, uuid, created) VALUES ($1, '{}', $2 )", uuid))
|
if let Err(error) = sqlx::query(&format!("INSERT INTO refresh_tokens (token, uuid, created) VALUES ($1, '{}', $2 )", uuid))
|
||||||
.bind(refresh_token)
|
.bind(&refresh_token)
|
||||||
.bind(current_time)
|
.bind(current_time)
|
||||||
.execute(&data.pool)
|
.execute(&data.pool)
|
||||||
.await {
|
.await {
|
||||||
|
@ -132,9 +146,9 @@ pub async fn res(mut payload: web::Payload, data: web::Data<Data>) -> Result<Htt
|
||||||
return Ok(HttpResponse::InternalServerError().finish())
|
return Ok(HttpResponse::InternalServerError().finish())
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Err(error) = sqlx::query(&format!("INSERT INTO refresh_tokens (token, refresh_token, uuid, created) VALUES ($1, $2, '{}', $3 )", uuid))
|
if let Err(error) = sqlx::query(&format!("INSERT INTO access_tokens (token, refresh_token, uuid, created) VALUES ($1, $2, '{}', $3 )", uuid))
|
||||||
.bind(access_token)
|
.bind(&access_token)
|
||||||
.bind(refresh_token)
|
.bind(&refresh_token)
|
||||||
.bind(current_time)
|
.bind(current_time)
|
||||||
.execute(&data.pool)
|
.execute(&data.pool)
|
||||||
.await {
|
.await {
|
||||||
|
|
|
@ -1,13 +1,13 @@
|
||||||
use getrandom::fill;
|
use getrandom::fill;
|
||||||
use hex::encode;
|
use hex::encode;
|
||||||
|
|
||||||
fn generate_access_token() -> Result<String, getrandom::Error> {
|
pub fn generate_access_token() -> Result<String, getrandom::Error> {
|
||||||
let mut buf = [0u8; 16];
|
let mut buf = [0u8; 16];
|
||||||
fill(&mut buf)?;
|
fill(&mut buf)?;
|
||||||
Ok(encode(&buf))
|
Ok(encode(&buf))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn generate_refresh_token() -> Result<String, getrandom::Error> {
|
pub fn generate_refresh_token() -> Result<String, getrandom::Error> {
|
||||||
let mut buf = [0u8; 32];
|
let mut buf = [0u8; 32];
|
||||||
fill(&mut buf)?;
|
fill(&mut buf)?;
|
||||||
Ok(encode(&buf))
|
Ok(encode(&buf))
|
||||||
|
|
|
@ -6,7 +6,7 @@ use std::time::SystemTime;
|
||||||
mod config;
|
mod config;
|
||||||
use config::{Config, ConfigBuilder};
|
use config::{Config, ConfigBuilder};
|
||||||
mod api;
|
mod api;
|
||||||
mod crypto;
|
pub mod crypto;
|
||||||
|
|
||||||
type Error = Box<dyn std::error::Error>;
|
type Error = Box<dyn std::error::Error>;
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue