Fixed guard still using env var for jwt key
parent
fb2a6126fe
commit
f50008ff99
2
Rb.yaml
2
Rb.yaml
|
@ -16,7 +16,7 @@ debug:
|
||||||
key: "secret"
|
key: "secret"
|
||||||
refresh_token_size: 64
|
refresh_token_size: 64
|
||||||
# Just 5 seconds for debugging
|
# Just 5 seconds for debugging
|
||||||
refresh_token_expire: 5
|
refresh_token_expire: 60
|
||||||
|
|
||||||
databases:
|
databases:
|
||||||
postgres_rb:
|
postgres_rb:
|
||||||
|
|
|
@ -49,7 +49,7 @@ reorder_imports = true
|
||||||
reorder_modules = true
|
reorder_modules = true
|
||||||
report_fixme = "Always"
|
report_fixme = "Always"
|
||||||
report_todo = "Always"
|
report_todo = "Always"
|
||||||
required_version = "1.4.36"
|
required_version = "1.4.37"
|
||||||
skip_children = false
|
skip_children = false
|
||||||
space_after_colon = true
|
space_after_colon = true
|
||||||
space_before_colon = false
|
space_before_colon = false
|
||||||
|
|
|
@ -1,13 +1,16 @@
|
||||||
|
use std::convert::From;
|
||||||
|
|
||||||
use hmac::{Hmac, NewMac};
|
use hmac::{Hmac, NewMac};
|
||||||
use jwt::VerifyWithKey;
|
use jwt::VerifyWithKey;
|
||||||
use rocket::{
|
use rocket::{
|
||||||
http::Status,
|
http::Status,
|
||||||
outcome::try_outcome,
|
outcome::try_outcome,
|
||||||
request::{FromRequest, Outcome, Request},
|
request::{FromRequest, Outcome, Request},
|
||||||
|
State,
|
||||||
};
|
};
|
||||||
use sha2::Sha256;
|
use sha2::Sha256;
|
||||||
|
|
||||||
use crate::auth::jwt::Claims;
|
use crate::{auth::jwt::Claims, errors::RbError, RbConfig};
|
||||||
|
|
||||||
/// Extracts a "Authorization: Bearer" string from the headers.
|
/// Extracts a "Authorization: Bearer" string from the headers.
|
||||||
pub struct Bearer<'a>(&'a str);
|
pub struct Bearer<'a>(&'a str);
|
||||||
|
@ -42,26 +45,28 @@ impl<'r> FromRequest<'r> for Bearer<'r>
|
||||||
/// Verifies the provided JWT is valid.
|
/// Verifies the provided JWT is valid.
|
||||||
pub struct Jwt(Claims);
|
pub struct Jwt(Claims);
|
||||||
|
|
||||||
|
impl From<()> for RbError
|
||||||
|
{
|
||||||
|
fn from(_: ()) -> Self
|
||||||
|
{
|
||||||
|
RbError::Custom("Couldn't get config guard.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[rocket::async_trait]
|
#[rocket::async_trait]
|
||||||
impl<'r> FromRequest<'r> for Jwt
|
impl<'r> FromRequest<'r> for Jwt
|
||||||
{
|
{
|
||||||
type Error = crate::errors::RbError;
|
type Error = RbError;
|
||||||
|
|
||||||
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
|
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error>
|
||||||
{
|
{
|
||||||
let bearer = try_outcome!(req.guard::<Bearer>().await).0;
|
let bearer = try_outcome!(req.guard::<Bearer>().await).0;
|
||||||
|
let config = try_outcome!(req.guard::<&State<RbConfig>>().await.map_failure(|_| (
|
||||||
|
Status::InternalServerError,
|
||||||
|
RbError::Custom("Couldn't get config guard.")
|
||||||
|
)));
|
||||||
|
|
||||||
// Get secret & key
|
let key: Hmac<Sha256> = match Hmac::new_from_slice(&config.jwt.key.as_bytes()) {
|
||||||
let secret = match std::env::var("JWT_KEY") {
|
|
||||||
Ok(key) => key,
|
|
||||||
Err(_) => {
|
|
||||||
return Outcome::Failure((
|
|
||||||
Status::InternalServerError,
|
|
||||||
Self::Error::AuthUnauthorized,
|
|
||||||
))
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let key: Hmac<Sha256> = match Hmac::new_from_slice(secret.as_bytes()) {
|
|
||||||
Ok(key) => key,
|
Ok(key) => key,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
return Outcome::Failure((
|
return Outcome::Failure((
|
||||||
|
|
|
@ -0,0 +1,64 @@
|
||||||
|
import requests
|
||||||
|
|
||||||
|
|
||||||
|
class RbClient:
|
||||||
|
def __init__(self, username, password, base_url = "http://localhost:8000/api"):
|
||||||
|
self.username = username
|
||||||
|
self.password = password
|
||||||
|
self.base_url = base_url
|
||||||
|
|
||||||
|
self.jwt = None
|
||||||
|
self.refresh_token = None
|
||||||
|
|
||||||
|
def _login(self):
|
||||||
|
r = requests.post(f"{self.base_url}/auth/login", json={
|
||||||
|
"username": self.username,
|
||||||
|
"password": self.password,
|
||||||
|
})
|
||||||
|
|
||||||
|
if r.status_code != 200:
|
||||||
|
raise Exception("Couldn't login")
|
||||||
|
|
||||||
|
res = r.json()
|
||||||
|
self.jwt = res["token"]
|
||||||
|
self.refresh_token = res["refreshToken"]
|
||||||
|
|
||||||
|
def _refresh(self):
|
||||||
|
r = requests.post(f"{self.base_url}/auth/refresh", json={"refreshToken": self.refresh_token})
|
||||||
|
|
||||||
|
if r.status_code != 200:
|
||||||
|
raise Exception("Couldn't refresh")
|
||||||
|
|
||||||
|
res = r.json()
|
||||||
|
self.jwt = res["token"]
|
||||||
|
self.refresh_token = res["refreshToken"]
|
||||||
|
|
||||||
|
def _request(self, type_, url, retry=2, *args, **kwargs):
|
||||||
|
if self.jwt:
|
||||||
|
headers = kwargs.get("headers", {})
|
||||||
|
headers["Authorization"] = f"Bearer {self.jwt}"
|
||||||
|
kwargs["headers"] = headers
|
||||||
|
print(kwargs["headers"])
|
||||||
|
|
||||||
|
r = requests.request(type_, url, *args, **kwargs)
|
||||||
|
|
||||||
|
if r.status_code != 200 and retry > 0:
|
||||||
|
if self.refresh_token:
|
||||||
|
self._refresh()
|
||||||
|
|
||||||
|
else:
|
||||||
|
self._login()
|
||||||
|
|
||||||
|
r = self._request(type_, url, *args, **kwargs, retry=retry - 1)
|
||||||
|
|
||||||
|
return r
|
||||||
|
|
||||||
|
def get(self, url, *args, **kwargs):
|
||||||
|
return self._request("GET", f"{self.base_url}{url}", *args, **kwargs)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
client = RbClient("admin", "password")
|
||||||
|
|
||||||
|
print(client.get("/admin/users").json())
|
Reference in New Issue