Compare commits
No commits in common. "505907d3a1073a3ea02ca9e50b7dc981d6d65b98" and "fb2a6126fedd853635ec89195d5789efda5ec043" have entirely different histories.
505907d3a1
...
fb2a6126fe
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: 60
|
refresh_token_expire: 5
|
||||||
|
|
||||||
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.37"
|
required_version = "1.4.36"
|
||||||
skip_children = false
|
skip_children = false
|
||||||
space_after_colon = true
|
space_after_colon = true
|
||||||
space_before_colon = false
|
space_before_colon = false
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,6 @@ pub enum RbError
|
||||||
AuthRefreshTokenExpired,
|
AuthRefreshTokenExpired,
|
||||||
AuthInvalidRefreshToken,
|
AuthInvalidRefreshToken,
|
||||||
AuthDuplicateRefreshToken,
|
AuthDuplicateRefreshToken,
|
||||||
AuthMissingHeader,
|
|
||||||
|
|
||||||
// UM = User Management
|
// UM = User Management
|
||||||
UMDuplicateUser,
|
UMDuplicateUser,
|
||||||
|
|
@ -40,7 +39,6 @@ impl RbError
|
||||||
RbError::AuthRefreshTokenExpired => Status::Unauthorized,
|
RbError::AuthRefreshTokenExpired => Status::Unauthorized,
|
||||||
RbError::AuthInvalidRefreshToken => Status::Unauthorized,
|
RbError::AuthInvalidRefreshToken => Status::Unauthorized,
|
||||||
RbError::AuthDuplicateRefreshToken => Status::Unauthorized,
|
RbError::AuthDuplicateRefreshToken => Status::Unauthorized,
|
||||||
RbError::AuthMissingHeader => Status::BadRequest,
|
|
||||||
|
|
||||||
RbError::UMDuplicateUser => Status::Conflict,
|
RbError::UMDuplicateUser => Status::Conflict,
|
||||||
|
|
||||||
|
|
@ -62,7 +60,6 @@ impl RbError
|
||||||
RbError::AuthDuplicateRefreshToken => {
|
RbError::AuthDuplicateRefreshToken => {
|
||||||
"This refresh token has already been used. The user has been blocked."
|
"This refresh token has already been used. The user has been blocked."
|
||||||
}
|
}
|
||||||
RbError::AuthMissingHeader => "Missing Authorization header.",
|
|
||||||
|
|
||||||
RbError::UMDuplicateUser => "This user already exists.",
|
RbError::UMDuplicateUser => "This user already exists.",
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -4,11 +4,10 @@ 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, errors::RbError, RbConfig};
|
use crate::auth::jwt::Claims;
|
||||||
|
|
||||||
/// 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);
|
||||||
|
|
@ -22,7 +21,7 @@ impl<'r> FromRequest<'r> for Bearer<'r>
|
||||||
{
|
{
|
||||||
// If the header isn't present, just forward to the next route
|
// If the header isn't present, just forward to the next route
|
||||||
let header = match req.headers().get_one("Authorization") {
|
let header = match req.headers().get_one("Authorization") {
|
||||||
None => return Outcome::Failure((Status::BadRequest, Self::Error::AuthMissingHeader)),
|
None => return Outcome::Forward(()),
|
||||||
Some(val) => val,
|
Some(val) => val,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -33,7 +32,7 @@ impl<'r> FromRequest<'r> for Bearer<'r>
|
||||||
// Extract the jwt token from the header
|
// Extract the jwt token from the header
|
||||||
let auth_string = match header.get(7..) {
|
let auth_string = match header.get(7..) {
|
||||||
Some(s) => s,
|
Some(s) => s,
|
||||||
None => return Outcome::Failure((Status::Unauthorized, Self::Error::AuthUnauthorized)),
|
None => return Outcome::Forward(()),
|
||||||
};
|
};
|
||||||
|
|
||||||
Outcome::Success(Self(auth_string))
|
Outcome::Success(Self(auth_string))
|
||||||
|
|
@ -46,17 +45,23 @@ pub struct Jwt(Claims);
|
||||||
#[rocket::async_trait]
|
#[rocket::async_trait]
|
||||||
impl<'r> FromRequest<'r> for Jwt
|
impl<'r> FromRequest<'r> for Jwt
|
||||||
{
|
{
|
||||||
type Error = RbError;
|
type Error = crate::errors::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.")
|
|
||||||
)));
|
|
||||||
|
|
||||||
let key: Hmac<Sha256> = match Hmac::new_from_slice(&config.jwt.key.as_bytes()) {
|
// Get secret & key
|
||||||
|
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((
|
||||||
|
|
@ -113,7 +118,7 @@ impl<'r> FromRequest<'r> for Admin
|
||||||
if user.admin {
|
if user.admin {
|
||||||
Outcome::Success(Self(user))
|
Outcome::Success(Self(user))
|
||||||
} else {
|
} else {
|
||||||
Outcome::Failure((Status::Unauthorized, RbError::AuthUnauthorized))
|
Outcome::Forward(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
14
src/main.rs
14
src/main.rs
|
|
@ -12,12 +12,7 @@ use figment::{
|
||||||
providers::{Env, Format, Yaml},
|
providers::{Env, Format, Yaml},
|
||||||
Figment,
|
Figment,
|
||||||
};
|
};
|
||||||
use rocket::{
|
use rocket::{fairing::AdHoc, Build, Rocket};
|
||||||
fairing::AdHoc,
|
|
||||||
http::Status,
|
|
||||||
serde::json::{json, Value},
|
|
||||||
Build, Request, Rocket,
|
|
||||||
};
|
|
||||||
use rocket_sync_db_pools::database;
|
use rocket_sync_db_pools::database;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
|
@ -31,12 +26,6 @@ pub(crate) mod schema;
|
||||||
#[database("postgres_rb")]
|
#[database("postgres_rb")]
|
||||||
pub struct RbDbConn(diesel::PgConnection);
|
pub struct RbDbConn(diesel::PgConnection);
|
||||||
|
|
||||||
#[catch(default)]
|
|
||||||
fn default_catcher(status: Status, _: &Request) -> Value
|
|
||||||
{
|
|
||||||
json!({"status": status.code, "message": ""})
|
|
||||||
}
|
|
||||||
|
|
||||||
embed_migrations!();
|
embed_migrations!();
|
||||||
|
|
||||||
async fn run_db_migrations(rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>>
|
async fn run_db_migrations(rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>>
|
||||||
|
|
@ -99,7 +88,6 @@ fn rocket() -> _
|
||||||
))
|
))
|
||||||
.attach(AdHoc::try_on_ignite("Create admin user", create_admin_user))
|
.attach(AdHoc::try_on_ignite("Create admin user", create_admin_user))
|
||||||
.attach(AdHoc::config::<RbConfig>())
|
.attach(AdHoc::config::<RbConfig>())
|
||||||
.register("/", catchers![default_catcher])
|
|
||||||
.mount(
|
.mount(
|
||||||
"/api/auth",
|
"/api/auth",
|
||||||
routes![auth::already_logged_in, auth::login, auth::refresh_token,],
|
routes![auth::already_logged_in, auth::login, auth::refresh_token,],
|
||||||
|
|
|
||||||
|
|
@ -1,64 +0,0 @@
|
||||||
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