Skip to content
This repository has been archived by the owner on Sep 20, 2023. It is now read-only.

Add HMAC middleware #8

Draft
wants to merge 8 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,6 @@ bson = "1.0"
serde = { version = "1.0", features = ["derive"]}
uuid = { version = "0.8.1", features = ["v4", "serde"] }
mongodb = "1.0"
hmac = "0.8.1"
hcor = { git="https://github.com/hackagotchi/hcor" }
sha2 = "0.9.1"
1 change: 1 addition & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use actix_web::{get, web, App, HttpRequest, HttpResponse, HttpServer};
pub mod data;
pub mod models;
pub mod routes;
pub mod middlewares;

#[get("/user/{id}")]
async fn get_user(_req: HttpRequest) -> HttpResponse {
Expand Down
40 changes: 40 additions & 0 deletions src/middlewares.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
use actix_web::HttpRequest;
use actix_web::middleware::{Middleware, Started};
use hcor::errors::ServiceError;
use actix_web::Result;
use std::env;

use hmac::{Hmac, Mac, NewMac};
use sha2::Sha256;



pub struct VerifySignature;

impl <S> Middleware<S> for VerifySignature {
fn start(&self, req: &mut HttpRequest<S>) -> Result<Started> {
use std::io::Read;

let r = req.clone();
let s = r.headers()
.get("X-Signature")
.ok_or(ServiceError::Unauthorized)?
.to_str()
.map_err(ServiceError::Unauthorized)?;

let (_, sig) = s.split_at(5);

let mut mac = Hmac::<Sha256>::new_varkey(String::as_bytes(env::var("SECERT_KEY").unwrap_or("changemepls")));
Muirrum marked this conversation as resolved.
Show resolved Hide resolved


cedric-h marked this conversation as resolved.
Show resolved Hide resolved

let mut body = String::new();
req.read_to_string(&mut body)
.map_err(ServiceError::InternalServerError)?;

mac.update(String::as_bytes(sig));
Muirrum marked this conversation as resolved.
Show resolved Hide resolved

mac.verify(String::as_bytes(body));
Muirrum marked this conversation as resolved.
Show resolved Hide resolved

cedric-h marked this conversation as resolved.
Show resolved Hide resolved
}
}