mirror of
https://github.com/OSMA-D/osma-server.git
synced 2024-11-05 21:24:02 +03:00
feat: authorisation (OS-9)
This commit is contained in:
parent
b2379f2a43
commit
57735ede3f
2 changed files with 42 additions and 0 deletions
40
src/main.rs
40
src/main.rs
|
@ -19,6 +19,40 @@ pub struct AppState {
|
|||
core: core::Core,
|
||||
}
|
||||
|
||||
async fn jwt_validator(
|
||||
mut req: ServiceRequest,
|
||||
credentials: BearerAuth,
|
||||
) -> Result<ServiceRequest, (Error, ServiceRequest)> {
|
||||
let token = decode::<types::JwtInfo>(
|
||||
&credentials.token(),
|
||||
&DecodingKey::from_secret(
|
||||
env::var("JWT_SECRET")
|
||||
.expect("JWT_SECRET not found")
|
||||
.as_ref(),
|
||||
),
|
||||
&Validation::default(),
|
||||
);
|
||||
match token {
|
||||
Ok(token) => {
|
||||
req.attach(vec![token.claims.role]);
|
||||
req.headers_mut().insert(
|
||||
HeaderName::from_lowercase(b"osma-username").unwrap(),
|
||||
HeaderValue::from_str(&token.claims.name).unwrap(),
|
||||
);
|
||||
|
||||
Ok(req)
|
||||
}
|
||||
Err(_) => {
|
||||
req.attach(vec!["none".to_string()]);
|
||||
req.headers_mut().insert(
|
||||
HeaderName::from_lowercase(b"osma-username").unwrap(),
|
||||
HeaderValue::from_str("no").unwrap(),
|
||||
);
|
||||
Ok(req)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[actix_rt::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
dotenv().ok();
|
||||
|
@ -43,7 +77,13 @@ async fn main() -> std::io::Result<()> {
|
|||
core: core::Core::new(&db),
|
||||
}))
|
||||
.wrap(cors)
|
||||
.service(
|
||||
web::scope("/api")
|
||||
.wrap(HttpAuthentication::bearer(jwt_validator))
|
||||
.service(routes::apps)
|
||||
)
|
||||
.service(
|
||||
web::scope("/auth")
|
||||
.service(routes::signup)
|
||||
.service(routes::signin),
|
||||
})
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
use crate::types::*;
|
||||
use actix_web::{get, post, web, HttpRequest, HttpResponse, Responder};
|
||||
use actix_web_grants::proc_macro::{has_any_permission, has_permissions};
|
||||
|
||||
#[post("/signup")]
|
||||
pub async fn signup(app_data: web::Data<crate::AppState>, user: web::Json<User>) -> impl Responder {
|
||||
response(app_data.core.signup(&user).await)
|
||||
|
@ -15,6 +16,7 @@ pub async fn signin(
|
|||
}
|
||||
|
||||
#[get("/apps")]
|
||||
#[has_any_permission("user", "admin")]
|
||||
pub async fn apps(app_data: web::Data<crate::AppState>) -> impl Responder {
|
||||
HttpResponse::Ok().json(app_data.core.get_apps().await)
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue