arami21 commited on
Commit
c132d47
·
verified ·
1 Parent(s): 3016e51

Update src/main.rs

Browse files
Files changed (1) hide show
  1. src/main.rs +74 -24
src/main.rs CHANGED
@@ -1,7 +1,9 @@
1
  use actix_cors::Cors;
2
- use actix_web::{web, App, HttpResponse, HttpServer, HttpRequest};
3
- use confik::{Configuration as _, EnvSource};
 
4
  use dotenvy::dotenv;
 
5
 
6
  mod config;
7
  mod db;
@@ -13,12 +15,77 @@ use db::Supabase;
13
  use errors::MyError;
14
  use models::RsvpRequest;
15
 
16
- const ALLOWED_ORIGIN: &str = "https://arami21-space.github.io";
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  async fn health() -> HttpResponse {
19
  HttpResponse::Ok().body("OK")
20
  }
21
 
 
22
  async fn get_guest(
23
  sb: web::Data<Supabase>,
24
  slug: web::Path<String>,
@@ -26,36 +93,18 @@ async fn get_guest(
26
  Ok(HttpResponse::Ok().json(sb.get_guest(&slug).await?))
27
  }
28
 
29
- // VALIDASI ORIGIN DI SERVER
30
- fn check_origin(req: &HttpRequest) -> bool {
31
- if let Some(origin) = req.headers().get("Origin") {
32
- if let Ok(origin_str) = origin.to_str() {
33
- return origin_str == ALLOWED_ORIGIN;
34
- }
35
- }
36
- false
37
- }
38
-
39
  async fn submit_rsvp(
40
- req: HttpRequest,
41
  sb: web::Data<Supabase>,
42
  form: web::Json<RsvpRequest>,
43
  ) -> Result<HttpResponse, MyError> {
44
- if !check_origin(&req) {
45
- return Ok(HttpResponse::Forbidden().body("Origin tidak diizinkan"));
46
- }
47
-
48
  Ok(HttpResponse::Ok().json(sb.submit_rsvp(form.into_inner()).await?))
49
  }
50
 
 
51
  async fn get_messages(
52
- req: HttpRequest,
53
  sb: web::Data<Supabase>,
54
  ) -> Result<HttpResponse, MyError> {
55
- if !check_origin(&req) {
56
- return Ok(HttpResponse::Forbidden().body("Origin tidak diizinkan"));
57
- }
58
-
59
  Ok(HttpResponse::Ok().json(sb.get_messages().await?))
60
  }
61
 
@@ -72,13 +121,14 @@ async fn main() -> std::io::Result<()> {
72
 
73
  HttpServer::new(move || {
74
  let cors = Cors::default()
75
- .allowed_origin(ALLOWED_ORIGIN)
76
  .allowed_methods(vec!["HEAD","GET","POST"])
77
  .allowed_headers(vec!["Content-Type", "Authorization"])
78
  .max_age(3600);
79
 
80
  App::new()
81
  .wrap(cors)
 
82
  .app_data(web::Data::new(supabase.clone()))
83
  .route("/cek", web::get().to(health))
84
  .route("/health", web::head().to(health))
 
1
  use actix_cors::Cors;
2
+ use actix_web::{web, App, HttpResponse, HttpServer, HttpRequest, Result, dev::ServiceRequest, dev::ServiceResponse, Error};
3
+ use actix_service::{Service, Transform};
4
+ use futures::future::{ok, Ready, LocalBoxFuture};
5
  use dotenvy::dotenv;
6
+ use confik::{Configuration as _, EnvSource};
7
 
8
  mod config;
9
  mod db;
 
15
  use errors::MyError;
16
  use models::RsvpRequest;
17
 
18
+ const ALLOWED_ORIGINS: &[&str] = &[
19
+ "https://arami21-space.github.io", // production
20
+ "http://localhost:5173", // dev
21
+ ];
22
+
23
+ /// Middleware global untuk cek Origin
24
+ pub struct OriginCheck;
25
+
26
+ impl<S, B> Transform<S, ServiceRequest> for OriginCheck
27
+ where
28
+ S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
29
+ S::Future: 'static,
30
+ {
31
+ type Response = ServiceResponse<B>;
32
+ type Error = Error;
33
+ type InitError = ();
34
+ type Transform = OriginCheckMiddleware<S>;
35
+ type Future = Ready<Result<Self::Transform, Self::InitError>>;
36
+
37
+ fn new_transform(&self, service: S) -> Self::Future {
38
+ ok(OriginCheckMiddleware { service })
39
+ }
40
+ }
41
+
42
+ pub struct OriginCheckMiddleware<S> {
43
+ service: S,
44
+ }
45
+
46
+ impl<S, B> Service<ServiceRequest> for OriginCheckMiddleware<S>
47
+ where
48
+ S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
49
+ S::Future: 'static,
50
+ {
51
+ type Response = ServiceResponse<B>;
52
+ type Error = Error;
53
+ type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
54
+
55
+ fn poll_ready(
56
+ &self,
57
+ ctx: &mut std::task::Context<'_>,
58
+ ) -> std::task::Poll<Result<(), Self::Error>> {
59
+ self.service.poll_ready(ctx)
60
+ }
61
+
62
+ fn call(&self, req: ServiceRequest) -> Self::Future {
63
+ let origin_allowed = req
64
+ .headers()
65
+ .get("Origin")
66
+ .and_then(|v| v.to_str().ok())
67
+ .map(|o| ALLOWED_ORIGINS.contains(&o))
68
+ .unwrap_or(false);
69
 
70
+ if !origin_allowed {
71
+ let resp = req.into_response(
72
+ HttpResponse::Forbidden()
73
+ .body("Origin tidak diizinkan")
74
+ );
75
+ return Box::pin(async { Ok(resp) });
76
+ }
77
+
78
+ let fut = self.service.call(req);
79
+ Box::pin(async move { fut.await })
80
+ }
81
+ }
82
+
83
+ /// Health check
84
  async fn health() -> HttpResponse {
85
  HttpResponse::Ok().body("OK")
86
  }
87
 
88
+ /// Ambil guest berdasarkan slug
89
  async fn get_guest(
90
  sb: web::Data<Supabase>,
91
  slug: web::Path<String>,
 
93
  Ok(HttpResponse::Ok().json(sb.get_guest(&slug).await?))
94
  }
95
 
96
+ /// Submit RSVP
 
 
 
 
 
 
 
 
 
97
  async fn submit_rsvp(
 
98
  sb: web::Data<Supabase>,
99
  form: web::Json<RsvpRequest>,
100
  ) -> Result<HttpResponse, MyError> {
 
 
 
 
101
  Ok(HttpResponse::Ok().json(sb.submit_rsvp(form.into_inner()).await?))
102
  }
103
 
104
+ /// Ambil semua messages
105
  async fn get_messages(
 
106
  sb: web::Data<Supabase>,
107
  ) -> Result<HttpResponse, MyError> {
 
 
 
 
108
  Ok(HttpResponse::Ok().json(sb.get_messages().await?))
109
  }
110
 
 
121
 
122
  HttpServer::new(move || {
123
  let cors = Cors::default()
124
+ .allowed_origin("https://arami21-space.github.io")
125
  .allowed_methods(vec!["HEAD","GET","POST"])
126
  .allowed_headers(vec!["Content-Type", "Authorization"])
127
  .max_age(3600);
128
 
129
  App::new()
130
  .wrap(cors)
131
+ .wrap(OriginCheck) // middleware global
132
  .app_data(web::Data::new(supabase.clone()))
133
  .route("/cek", web::get().to(health))
134
  .route("/health", web::head().to(health))