You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
62 lines
2.4 KiB
62 lines
2.4 KiB
use actix_web::{HttpRequest, HttpResponse};
|
|
use actix_web::error::Result;
|
|
use actix_web::middleware::{Middleware, Started};
|
|
|
|
use crate::config::model::Config;
|
|
use crate::config::model::UserConfig;
|
|
use crate::server::router::AppState;
|
|
use crate::server::util;
|
|
|
|
fn valid_username_and_token_in_vec(username: &str, token: &str, users: Vec<&UserConfig>) -> bool {
|
|
for user in users {
|
|
if user.username == username && user.token == token {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
pub struct APIAuthUser;
|
|
|
|
pub struct APIAuthRootAndZone;
|
|
|
|
impl Middleware<AppState> for APIAuthUser {
|
|
fn start(&self, req: &HttpRequest<AppState>) -> Result<Started> {
|
|
let config: &Config = &req.state().config;
|
|
let username = util::get_username_from_request(req);
|
|
let token = util::get_token_from_request(req);
|
|
if username.is_none() || token.is_none() {
|
|
Ok(Started::Response(HttpResponse::Unauthorized().into()))
|
|
} else if config.is_valid_username_and_token(&username.unwrap(), &token.unwrap()) {
|
|
Ok(Started::Done)
|
|
} else {
|
|
Ok(Started::Response(HttpResponse::Unauthorized().into()))
|
|
}
|
|
}
|
|
}
|
|
|
|
impl Middleware<AppState> for APIAuthRootAndZone {
|
|
fn start(&self, req: &HttpRequest<AppState>) -> Result<Started> {
|
|
let config: &Config = &req.state().config;
|
|
let root = util::get_match_value(req, "root");
|
|
let zone = util::get_match_value(req, "zone");
|
|
if root.is_none() || zone.is_none() {
|
|
Ok(Started::Response(HttpResponse::BadRequest().into()))
|
|
} else {
|
|
match config.get_users_for_root_and_zone(&root.unwrap(), &zone.unwrap()) {
|
|
Some(users) => {
|
|
let username = util::get_username_from_request(req);
|
|
let token = util::get_token_from_request(req);
|
|
if username.is_none() || token.is_none() {
|
|
Ok(Started::Response(HttpResponse::BadRequest().into()))
|
|
} else if valid_username_and_token_in_vec(&username.unwrap(), &token.unwrap(), users) {
|
|
Ok(Started::Done)
|
|
} else {
|
|
Ok(Started::Response(HttpResponse::Unauthorized().into()))
|
|
}
|
|
}
|
|
None => Ok(Started::Response(HttpResponse::Unauthorized().into()))
|
|
}
|
|
}
|
|
}
|
|
}
|