Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #[macro_use]
- extern crate actix_rt;
- #[macro_use]
- extern crate lazy_static;
- use actix_web::{
- dev::Payload,
- get,
- http::StatusCode,
- post,
- web::{self, HttpRequest, HttpResponse},
- App, Error as HttpError, FromRequest, HttpServer, Responder,
- };
- use serde::{Deserialize, Serialize};
- use std::{error::Error, future::Future, pin::Pin, task::Poll};
- use tokio::sync::Mutex;
- lazy_static! {
- static ref SECRET_PASSWORD: Mutex<Box<str>> = Mutex::new("secret".into());
- }
- pub struct Auth;
- impl FromRequest for Auth {
- type Error = HttpError;
- type Config = ();
- type Future = Box<Pin<Box<dyn Future<Output = Result<Self, Self::Error>>>>>;
- fn from_request(req: &HttpRequest, pl: &mut Payload) -> Self::Future {
- let headers = req.headers();
- match headers.get("Authorization") {
- Some(v) => {
- let owned = v.clone();
- Box::new(Box::pin(async move {
- let lock = SECRET_PASSWORD.lock().await;
- if &**lock == owned.to_str().unwrap() {
- Ok(Self)
- } else {
- Err(HttpError::from(
- HttpResponse::build(StatusCode::FORBIDDEN)
- .body("authorization incorrect"),
- ))
- }
- }))
- }
- None => Box::new(Box::pin(async {
- Err(HttpError::from(
- HttpResponse::build(StatusCode::FORBIDDEN).body("authorization required"),
- ))
- })),
- }
- }
- }
- #[get("/")]
- pub async fn index(_: Auth) -> impl Responder {
- HttpResponse::build(StatusCode::OK).body("hello")
- }
- #[derive(Deserialize)]
- pub struct ChangePass {
- pub pass: Box<str>,
- }
- #[post("changepass")]
- pub async fn change_pass(form: web::Json<ChangePass>) -> impl Responder {
- // lock
- let mut lock = SECRET_PASSWORD.lock().await;
- *lock = form.pass.to_owned();
- HttpResponse::build(StatusCode::CREATED)
- }
- #[actix_rt::main]
- async fn main() -> Result<(), Box<dyn Error>> {
- HttpServer::new(move || {
- App::new().service(web::scope("private").service(change_pass).service(index))
- })
- .bind("127.0.0.1:8080")?
- .workers(4)
- .run()
- .await?;
- Ok(())
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement