Add Login (#4)
Rust Build / Check (push) Successful in 1m21s
Rust Build / Rustfmt (push) Successful in 31s
Rust Build / Test Suite (push) Successful in 2m21s
Rust Build / Clippy (push) Successful in 2m3s
Rust Build / build (push) Successful in 1m55s
Rust Build / Rustfmt (pull_request) Successful in 44s
Rust Build / Check (pull_request) Successful in 1m21s
Rust Build / Clippy (pull_request) Successful in 1m56s
Rust Build / build (pull_request) Successful in 1m57s
Rust Build / Test Suite (pull_request) Failing after 3m35s
Rust Build / Check (push) Successful in 1m21s
Rust Build / Rustfmt (push) Successful in 31s
Rust Build / Test Suite (push) Successful in 2m21s
Rust Build / Clippy (push) Successful in 2m3s
Rust Build / build (push) Successful in 1m55s
Rust Build / Rustfmt (pull_request) Successful in 44s
Rust Build / Check (pull_request) Successful in 1m21s
Rust Build / Clippy (pull_request) Successful in 1m56s
Rust Build / build (pull_request) Successful in 1m57s
Rust Build / Test Suite (pull_request) Failing after 3m35s
Reviewed-on: phoenix/textsender-auth#4
This commit was merged in pull request #4.
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
use crate::hashing;
|
||||
use crate::repo;
|
||||
use crate::token_stuff;
|
||||
|
||||
pub mod request {
|
||||
use serde::Deserialize;
|
||||
#[derive(Default, Deserialize, utoipa::ToSchema)]
|
||||
pub struct LoginRequest {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
}
|
||||
|
||||
pub mod response {
|
||||
use serde::{Deserialize, Serialize};
|
||||
#[derive(Default, Deserialize, Serialize, utoipa::ToSchema)]
|
||||
pub struct LoginResponse {
|
||||
pub message: String,
|
||||
pub data: Vec<textsender_models::token::LoginResult>,
|
||||
}
|
||||
|
||||
pub async fn extract(
|
||||
response: axum::response::Response,
|
||||
) -> Result<LoginResponse, std::io::Error> {
|
||||
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
let _parsed_body: LoginResponse = serde_json::from_slice(&body).unwrap();
|
||||
todo!("Add code to convert axum::Response to this type");
|
||||
}
|
||||
}
|
||||
|
||||
/// Endpoint for a user login
|
||||
#[utoipa::path(
|
||||
post,
|
||||
path = super::endpoints::LOGIN,
|
||||
request_body(
|
||||
content = request::LoginRequest,
|
||||
description = "Data required for a user to lgoin",
|
||||
content_type = "application/json"
|
||||
),
|
||||
responses(
|
||||
(status = 201, description = "User login successful", body = response::LoginResponse),
|
||||
(status = 400, description = "Bad data", body = response::LoginResponse),
|
||||
(status = 500, description = "Something went wrong", body = response::LoginResponse)
|
||||
)
|
||||
)]
|
||||
pub async fn user_login(
|
||||
axum::Extension(pool): axum::Extension<sqlx::PgPool>,
|
||||
axum::Json(payload): axum::Json<request::LoginRequest>,
|
||||
) -> (axum::http::StatusCode, axum::Json<response::LoginResponse>) {
|
||||
if payload.username.is_empty() || payload.password.is_empty() {
|
||||
let reason = if payload.username.is_empty() {
|
||||
String::from("Username not provided")
|
||||
} else {
|
||||
String::from("Password not provided")
|
||||
};
|
||||
|
||||
(
|
||||
axum::http::StatusCode::BAD_REQUEST,
|
||||
axum::Json(response::LoginResponse {
|
||||
message: reason,
|
||||
data: Vec::new(),
|
||||
}),
|
||||
)
|
||||
} else {
|
||||
match repo::user::exists(&pool, &payload.username).await {
|
||||
Ok(exists) => {
|
||||
if !exists {
|
||||
println!("User does not exists");
|
||||
(
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
axum::Json(response::LoginResponse {
|
||||
message: String::from("Unable to login"),
|
||||
data: Vec::new(),
|
||||
}),
|
||||
)
|
||||
} else {
|
||||
let user = match repo::user::get(&pool, &payload.username).await {
|
||||
Ok(user) => user,
|
||||
Err(_err) => {
|
||||
return (
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
axum::Json(response::LoginResponse {
|
||||
message: String::from("Unable to login"),
|
||||
data: Vec::new(),
|
||||
}),
|
||||
);
|
||||
}
|
||||
};
|
||||
let hashed_password = user.password.clone();
|
||||
|
||||
match hashing::verify_password(&payload.password, hashed_password) {
|
||||
Ok(matches) => {
|
||||
if matches {
|
||||
// Create token
|
||||
let key = textsender_models::envy::environment::get_secret_key()
|
||||
.await
|
||||
.value;
|
||||
let (token_literal, duration) =
|
||||
token_stuff::create_token(&key, &user.id).unwrap();
|
||||
|
||||
if token_stuff::verify_token(&key, &token_literal) {
|
||||
let current_time = time::OffsetDateTime::now_utc();
|
||||
let _ =
|
||||
repo::user::update_last_login(&pool, &user, ¤t_time)
|
||||
.await;
|
||||
|
||||
(
|
||||
axum::http::StatusCode::OK,
|
||||
axum::Json(response::LoginResponse {
|
||||
message: String::from("Successful"),
|
||||
data: vec![textsender_models::token::LoginResult {
|
||||
user_id: user.id,
|
||||
access_token: token_literal,
|
||||
token_type: String::from(
|
||||
textsender_models::token::TOKEN_TYPE,
|
||||
),
|
||||
issued_at: duration,
|
||||
..Default::default()
|
||||
}],
|
||||
}),
|
||||
)
|
||||
} else {
|
||||
(
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
axum::Json(response::LoginResponse {
|
||||
message: String::from("Invalid attempt"),
|
||||
data: Vec::new(),
|
||||
}),
|
||||
)
|
||||
}
|
||||
} else {
|
||||
(
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
axum::Json(response::LoginResponse {
|
||||
message: String::from("Invalid attempt"),
|
||||
data: Vec::new(),
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
Err(err) => (
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
axum::Json(response::LoginResponse {
|
||||
message: err.to_string(),
|
||||
data: Vec::new(),
|
||||
}),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => (
|
||||
axum::http::StatusCode::INTERNAL_SERVER_ERROR,
|
||||
axum::Json(response::LoginResponse {
|
||||
message: err.to_string(),
|
||||
data: Vec::new(),
|
||||
}),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
pub mod common;
|
||||
pub mod login;
|
||||
pub mod register;
|
||||
|
||||
pub mod endpoints {
|
||||
pub const ROOT: &str = "/";
|
||||
pub const REGISTER: &str = "/api/v1/register";
|
||||
/// Endpoint for a user to login
|
||||
pub const LOGIN: &str = "/api/v1/login";
|
||||
pub const DBTEST: &str = "/api/v1/test/db";
|
||||
}
|
||||
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
pub mod callers;
|
||||
pub mod config;
|
||||
pub mod db;
|
||||
pub mod hashing;
|
||||
pub mod repo;
|
||||
pub mod token_stuff;
|
||||
|
||||
pub mod init {
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{get, post},
|
||||
};
|
||||
use utoipa::OpenApi;
|
||||
|
||||
use super::callers;
|
||||
use callers::common as common_callers;
|
||||
use callers::login as login_caller;
|
||||
use callers::register as register_caller;
|
||||
use login_caller::response as login_responses;
|
||||
use register_caller::response as register_responses;
|
||||
|
||||
#[derive(utoipa::OpenApi)]
|
||||
#[openapi(
|
||||
paths(
|
||||
common_callers::endpoint::db_ping, common_callers::endpoint::root,
|
||||
register_caller::register_user, login_caller::user_login,
|
||||
),
|
||||
components(schemas(common_callers::response::TestResult,
|
||||
register_responses::Response, login_responses::LoginResponse)),
|
||||
tags(
|
||||
(name = "TextSender Auth API", description = "Auth API for TextSender API")
|
||||
)
|
||||
)]
|
||||
struct ApiDoc;
|
||||
|
||||
mod cors {
|
||||
pub async fn configure_cors() -> tower_http::cors::CorsLayer {
|
||||
// Start building the CORS layer with common settings
|
||||
let cors = tower_http::cors::CorsLayer::new()
|
||||
.allow_methods([
|
||||
axum::http::Method::GET,
|
||||
axum::http::Method::POST,
|
||||
axum::http::Method::PUT,
|
||||
axum::http::Method::DELETE,
|
||||
]) // Specify allowed methods:cite[2]
|
||||
.allow_headers([
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
axum::http::header::AUTHORIZATION,
|
||||
]) // Specify allowed headers:cite[2]
|
||||
.allow_credentials(true) // If you need to send cookies or authentication headers:cite[2]
|
||||
.max_age(std::time::Duration::from_secs(3600)); // Cache the preflight response for 1 hour:cite[2]
|
||||
|
||||
// Dynamically set the allowed origin based on the environment
|
||||
match std::env::var(textsender_models::envy::keys::APP_ENV).as_deref() {
|
||||
Ok("production") => {
|
||||
let allowed_origins_env =
|
||||
textsender_models::envy::environment::get_allowed_origins().await;
|
||||
match textsender_models::envy::utility::delimitize(&allowed_origins_env) {
|
||||
Ok(alwd) => {
|
||||
let allowed_origins: Vec<axum::http::HeaderValue> = alwd
|
||||
.into_iter()
|
||||
.map(|s| s.parse::<axum::http::HeaderValue>().unwrap())
|
||||
.collect();
|
||||
cors.allow_origin(allowed_origins)
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"Could not parse out allowed origins from env: Error: {err:?}"
|
||||
);
|
||||
std::process::exit(-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// Development (default): Allow localhost origins
|
||||
cors.allow_origin(vec![
|
||||
"http://localhost:4200".parse().unwrap(),
|
||||
"http://127.0.0.1:4200".parse().unwrap(),
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn routes() -> Router {
|
||||
// build our application with a route
|
||||
Router::new()
|
||||
.route(
|
||||
callers::endpoints::DBTEST,
|
||||
get(callers::common::endpoint::db_ping),
|
||||
)
|
||||
.route(
|
||||
callers::endpoints::ROOT,
|
||||
get(callers::common::endpoint::root),
|
||||
)
|
||||
.route(
|
||||
callers::endpoints::REGISTER,
|
||||
post(callers::register::register_user),
|
||||
)
|
||||
.route(callers::endpoints::LOGIN, post(callers::login::user_login))
|
||||
.layer(cors::configure_cors().await)
|
||||
}
|
||||
|
||||
pub async fn app() -> Router {
|
||||
let pool = super::db::init::create_pool()
|
||||
.await
|
||||
.expect("Failed to create pool");
|
||||
|
||||
super::db::init::migrations(&pool).await;
|
||||
|
||||
routes()
|
||||
.await
|
||||
.merge(
|
||||
utoipa_swagger_ui::SwaggerUi::new("/swagger-ui")
|
||||
.url("/api-docs/openapi.json", ApiDoc::openapi()),
|
||||
)
|
||||
.layer(axum::Extension(pool))
|
||||
}
|
||||
}
|
||||
+2
-119
@@ -1,129 +1,12 @@
|
||||
pub mod callers;
|
||||
pub mod config;
|
||||
pub mod db;
|
||||
pub mod hashing;
|
||||
pub mod repo;
|
||||
pub mod token_stuff;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() {
|
||||
// initialize tracing
|
||||
tracing_subscriber::fmt::init();
|
||||
|
||||
let app = init::app().await;
|
||||
let app = textsender_auth::init::app().await;
|
||||
|
||||
// run our app with hyper, listening globally on port 9080
|
||||
let url = config::get_full();
|
||||
let url = textsender_auth::config::get_full();
|
||||
let listener = tokio::net::TcpListener::bind(url).await.unwrap();
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
}
|
||||
|
||||
mod init {
|
||||
use axum::{
|
||||
Router,
|
||||
routing::{get, post},
|
||||
};
|
||||
use utoipa::OpenApi;
|
||||
|
||||
use super::callers;
|
||||
use callers::common as common_callers;
|
||||
use callers::register as register_caller;
|
||||
use register_caller::response as register_responses;
|
||||
|
||||
#[derive(utoipa::OpenApi)]
|
||||
#[openapi(
|
||||
paths(
|
||||
common_callers::endpoint::db_ping, common_callers::endpoint::root,
|
||||
register_caller::register_user,
|
||||
),
|
||||
components(schemas(common_callers::response::TestResult,
|
||||
register_responses::Response)),
|
||||
tags(
|
||||
(name = "TextSender Auth API", description = "Auth API for TextSender API")
|
||||
)
|
||||
)]
|
||||
struct ApiDoc;
|
||||
|
||||
mod cors {
|
||||
pub async fn configure_cors() -> tower_http::cors::CorsLayer {
|
||||
// Start building the CORS layer with common settings
|
||||
let cors = tower_http::cors::CorsLayer::new()
|
||||
.allow_methods([
|
||||
axum::http::Method::GET,
|
||||
axum::http::Method::POST,
|
||||
axum::http::Method::PUT,
|
||||
axum::http::Method::DELETE,
|
||||
]) // Specify allowed methods:cite[2]
|
||||
.allow_headers([
|
||||
axum::http::header::CONTENT_TYPE,
|
||||
axum::http::header::AUTHORIZATION,
|
||||
]) // Specify allowed headers:cite[2]
|
||||
.allow_credentials(true) // If you need to send cookies or authentication headers:cite[2]
|
||||
.max_age(std::time::Duration::from_secs(3600)); // Cache the preflight response for 1 hour:cite[2]
|
||||
|
||||
// Dynamically set the allowed origin based on the environment
|
||||
match std::env::var(textsender_models::envy::keys::APP_ENV).as_deref() {
|
||||
Ok("production") => {
|
||||
let allowed_origins_env =
|
||||
textsender_models::envy::environment::get_allowed_origins().await;
|
||||
match textsender_models::envy::utility::delimitize(&allowed_origins_env) {
|
||||
Ok(alwd) => {
|
||||
let allowed_origins: Vec<axum::http::HeaderValue> = alwd
|
||||
.into_iter()
|
||||
.map(|s| s.parse::<axum::http::HeaderValue>().unwrap())
|
||||
.collect();
|
||||
cors.allow_origin(allowed_origins)
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!(
|
||||
"Could not parse out allowed origins from env: Error: {err:?}"
|
||||
);
|
||||
std::process::exit(-1);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
// Development (default): Allow localhost origins
|
||||
cors.allow_origin(vec![
|
||||
"http://localhost:4200".parse().unwrap(),
|
||||
"http://127.0.0.1:4200".parse().unwrap(),
|
||||
])
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn routes() -> Router {
|
||||
// build our application with a route
|
||||
Router::new()
|
||||
.route(
|
||||
callers::endpoints::DBTEST,
|
||||
get(callers::common::endpoint::db_ping),
|
||||
)
|
||||
.route(
|
||||
callers::endpoints::ROOT,
|
||||
get(callers::common::endpoint::root),
|
||||
)
|
||||
.route(
|
||||
callers::endpoints::REGISTER,
|
||||
post(callers::register::register_user),
|
||||
)
|
||||
.layer(cors::configure_cors().await)
|
||||
}
|
||||
|
||||
pub async fn app() -> Router {
|
||||
let pool = super::db::init::create_pool()
|
||||
.await
|
||||
.expect("Failed to create pool");
|
||||
|
||||
super::db::init::migrations(&pool).await;
|
||||
|
||||
routes()
|
||||
.await
|
||||
.merge(
|
||||
utoipa_swagger_ui::SwaggerUi::new("/swagger-ui")
|
||||
.url("/api-docs/openapi.json", ApiDoc::openapi()),
|
||||
)
|
||||
.layer(axum::Extension(pool))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,10 +11,6 @@ pub const MESSAGE: &str = "Something random";
|
||||
pub const ISSUER: &str = "textsender_auth";
|
||||
pub const AUDIENCE: &str = "textsender";
|
||||
|
||||
pub fn get_issued() -> time::Result<time::OffsetDateTime> {
|
||||
Ok(time::OffsetDateTime::now_utc())
|
||||
}
|
||||
|
||||
pub fn get_expiration(issued: &time::OffsetDateTime) -> Result<time::OffsetDateTime, time::Error> {
|
||||
let duration_expire = time::Duration::hours(4);
|
||||
Ok(*issued + duration_expire)
|
||||
|
||||
Reference in New Issue
Block a user