refactor: Remove unused code
- DbConn moved to /src/api/guards/db.rs - Removed redundant imports in /src/api/routes Signed-off-by: supercmmetry <vishaals2000@gmail.com>
This commit is contained in:
parent
f16e906ff4
commit
de741f451e
@ -1,103 +0,0 @@
|
||||
use std::env;
|
||||
use std::result::Result;
|
||||
use chrono::prelude::*;
|
||||
use jsonwebtoken::{Header, Algorithm, EncodingKey, Validation, DecodingKey};
|
||||
use rocket::request::{FromRequest, Outcome};
|
||||
use rocket::{Request};
|
||||
|
||||
use crate::utils::errors::Error;
|
||||
use crate::utils::errors::ErrorCode;
|
||||
|
||||
#[derive(Serialize, Deserialize, Clone)]
|
||||
pub struct Claims {
|
||||
pub user_id: String,
|
||||
#[serde(with = "date_serializer")]
|
||||
iat: DateTime<Utc>,
|
||||
#[serde(with = "date_serializer")]
|
||||
exp: DateTime<Utc>
|
||||
}
|
||||
|
||||
mod date_serializer {
|
||||
use chrono::{DateTime, TimeZone, Utc};
|
||||
use serde::{self, Deserialize, Deserializer, Serializer};
|
||||
use serde::de::Error;
|
||||
|
||||
/// Serializes a DateTime<Utc> to a Unix timestamp (milliseconds since 1970/1/1T00:00:00T)
|
||||
pub fn serialize<S>(date: &DateTime<Utc>, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let timestamp = date.timestamp();
|
||||
serializer.serialize_i64(timestamp)
|
||||
}
|
||||
|
||||
/// Attempts to deserialize an i64 and use as a Unix timestamp
|
||||
pub fn deserialize<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Error>
|
||||
where
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
Utc.timestamp_opt(i64::deserialize(deserializer)?, 0)
|
||||
.single() // If there are multiple or no valid DateTimes from timestamp, return None
|
||||
.ok_or_else(|| Error::custom("invalid Unix timestamp value"))
|
||||
}
|
||||
}
|
||||
|
||||
impl Claims {
|
||||
pub fn new(user_id: String) -> Claims {
|
||||
let iat = Utc::now();
|
||||
let exp = iat + chrono::Duration::days(1);
|
||||
|
||||
Claims {
|
||||
user_id,
|
||||
iat: iat.date().and_hms_milli(iat.hour(), iat.minute(), iat.second(), 0),
|
||||
exp: exp.date().and_hms_milli(exp.hour(), exp.minute(), exp.second(), 0)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn jwt(&self) -> Result<String, Error> {
|
||||
let mut header = Header::default();
|
||||
header.alg = Algorithm::HS512;
|
||||
header.kid = Some(env::var("JWT_SIGNING_KEY").unwrap());
|
||||
let key = env::var("JWT_PASSWORD").unwrap();
|
||||
|
||||
|
||||
match jsonwebtoken::encode(&header, self, &EncodingKey::from_secret(key.as_bytes())) {
|
||||
Ok(token) => Ok(token),
|
||||
Err(_) => Err(Error::new(ErrorCode::AuthTokenCreationFailed))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from(token: String) -> Result<Claims, Error> {
|
||||
let key = env::var("JWT_PASSWORD").unwrap();
|
||||
match jsonwebtoken::decode::<Claims>(&token, &DecodingKey::from_secret(key.as_bytes()),
|
||||
&Validation::new(Algorithm::HS512)) {
|
||||
Ok(token_data) => Ok(token_data.claims),
|
||||
Err(_) => Err(Error::new(ErrorCode::MalformedAuthToken))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ClaimResult(Result<Claims, Error>);
|
||||
|
||||
impl ClaimResult {
|
||||
pub fn inner(&self) -> Result<Claims, Error> {
|
||||
self.0.clone()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'r> FromRequest<'a, 'r> for ClaimResult {
|
||||
type Error = Error;
|
||||
|
||||
fn from_request(request: &'a Request<'r>) -> Outcome<Self, Self::Error> {
|
||||
let values: Vec<_> = request.headers().get("Authorization").collect();
|
||||
if values.len() > 1 {
|
||||
return Outcome::Success(ClaimResult(Err(Error::new(ErrorCode::MultipleAuthToken))));
|
||||
} else if values.len() == 0 {
|
||||
return Outcome::Success(ClaimResult(Err(Error::new(ErrorCode::NoAuthToken))));
|
||||
}
|
||||
|
||||
let token = values[0].to_string();
|
||||
|
||||
Outcome::Success(ClaimResult(Claims::from(token)))
|
||||
}
|
||||
}
|
29
src/api/guards/db.rs
Normal file
29
src/api/guards/db.rs
Normal file
@ -0,0 +1,29 @@
|
||||
use diesel::PgConnection;
|
||||
use diesel::r2d2::{PooledConnection, ConnectionManager};
|
||||
use rocket::{Request, request, State, Outcome};
|
||||
use rocket::request::FromRequest;
|
||||
use rocket::http::Status;
|
||||
use crate::utils::db::Pool;
|
||||
use std::ops::Deref;
|
||||
|
||||
pub struct DbConn(pub PooledConnection<ConnectionManager<PgConnection>>);
|
||||
|
||||
impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
|
||||
type Error = ();
|
||||
|
||||
fn from_request(request: &'a Request<'r>) -> request::Outcome<DbConn, Self::Error> {
|
||||
let pool = request.guard::<State<Pool>>()?;
|
||||
match pool.get() {
|
||||
Ok(conn) => Outcome::Success(DbConn(conn)),
|
||||
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for DbConn {
|
||||
type Target = PgConnection;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
@ -1 +1 @@
|
||||
pub mod auth;
|
||||
pub mod db;
|
@ -7,8 +7,9 @@ use serde_json::Value;
|
||||
|
||||
use crate::core::paste::{entity::Paste, service::create_paste, service::fetch_paste};
|
||||
use crate::core::users::{service::create_or_fetch_user};
|
||||
use crate::utils::{db, phonetic_key};
|
||||
use crate::utils::phonetic_key::get_random_id;
|
||||
use crate::utils::phonetic_key;
|
||||
use crate::api::guards::db;
|
||||
|
||||
use diesel::result::Error;
|
||||
|
||||
#[post("/", data = "<paste>")]
|
||||
@ -17,7 +18,7 @@ fn create(mut paste: Json<Paste>, conn: db::DbConn, mut ck: Cookies) -> Custom<J
|
||||
let user_id = match ck.get_private("session") {
|
||||
Some(c) => c.value().to_string(),
|
||||
None => {
|
||||
let user_id = get_random_id();
|
||||
let user_id = phonetic_key::get_random_id();
|
||||
ck.add_private(Cookie::new("session", user_id.clone()));
|
||||
user_id
|
||||
}
|
||||
|
@ -1,12 +1,7 @@
|
||||
use diesel::pg::PgConnection;
|
||||
use diesel::{r2d2, Connection};
|
||||
use diesel::r2d2::{PooledConnection, ConnectionManager};
|
||||
use rocket::{Outcome, Request, State};
|
||||
use rocket::http::Status;
|
||||
use rocket::request::{self, FromRequest};
|
||||
use diesel::r2d2::ConnectionManager;
|
||||
use std::env;
|
||||
use std::ops::Deref;
|
||||
use crate::utils::errors::{Error, ErrorCode};
|
||||
|
||||
pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>;
|
||||
|
||||
@ -21,35 +16,4 @@ fn database_url() -> String {
|
||||
|
||||
pub fn pg_connection() -> PgConnection {
|
||||
PgConnection::establish(database_url().as_str()).unwrap()
|
||||
}
|
||||
|
||||
pub struct DbConn(pub r2d2::PooledConnection<ConnectionManager<PgConnection>>);
|
||||
|
||||
impl<'a, 'r> FromRequest<'a, 'r> for DbConn {
|
||||
type Error = ();
|
||||
|
||||
fn from_request(request: &'a Request<'r>) -> request::Outcome<DbConn, Self::Error> {
|
||||
let pool = request.guard::<State<Pool>>()?;
|
||||
match pool.get() {
|
||||
Ok(conn) => Outcome::Success(DbConn(conn)),
|
||||
Err(_) => Outcome::Failure((Status::ServiceUnavailable, ())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Deref for DbConn {
|
||||
type Target = PgConnection;
|
||||
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_connection(pool: &Pool) -> Result<PooledConnection<ConnectionManager<PgConnection>>, Error> {
|
||||
let result = pool.get();
|
||||
if let Err(e) = result {
|
||||
return Err(Error::custom(ErrorCode::DatabaseError, e.to_string()));
|
||||
}
|
||||
|
||||
Ok(result.unwrap())
|
||||
}
|
@ -94,33 +94,4 @@ impl<'r> Responder<'r> for Error {
|
||||
.sized_body(Cursor::new(serde_json::to_string(&self).unwrap()))
|
||||
.ok()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
pub struct Success {
|
||||
msg: String
|
||||
}
|
||||
|
||||
impl Success {
|
||||
pub fn new(msg: &str) -> Success {
|
||||
Success {
|
||||
msg: msg.to_string()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'r> Responder<'r> for Success {
|
||||
fn respond_to(self, request: &Request) -> response::Result<'r> {
|
||||
let logger = request.guard::<State<Logger>>();
|
||||
|
||||
if let Outcome::Success(logger) = logger {
|
||||
info!(logger, "{}", serde_json::to_string(&self).unwrap());
|
||||
}
|
||||
|
||||
Response::build()
|
||||
.status(Status::Ok)
|
||||
.header(ContentType::JSON)
|
||||
.sized_body(Cursor::new(serde_json::to_string(&self).unwrap()))
|
||||
.ok()
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user