arami21 commited on
Commit
674f578
·
verified ·
1 Parent(s): c132d47

Update src/main.rs

Browse files
Files changed (1) hide show
  1. src/main.rs +26 -73
src/main.rs CHANGED
@@ -1,9 +1,7 @@
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,77 +13,15 @@ use db::Supabase;
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,18 +29,36 @@ async fn get_guest(
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,14 +75,13 @@ async fn main() -> std::io::Result<()> {
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))
 
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
  use errors::MyError;
14
  use models::RsvpRequest;
15
 
16
+ const ALLOWED_ORIGIN: &str = &[
17
+ "https://arami21-space.github.io",
18
+ "http://localhost:5173",
19
  ];
20
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  async fn health() -> HttpResponse {
22
  HttpResponse::Ok().body("OK")
23
  }
24
 
 
25
  async fn get_guest(
26
  sb: web::Data<Supabase>,
27
  slug: web::Path<String>,
 
29
  Ok(HttpResponse::Ok().json(sb.get_guest(&slug).await?))
30
  }
31
 
32
+ // VALIDASI ORIGIN DI SERVER
33
+ fn check_origin(req: &HttpRequest) -> bool {
34
+ if let Some(origin) = req.headers().get("Origin") {
35
+ if let Ok(origin_str) = origin.to_str() {
36
+ return origin_str == ALLOWED_ORIGIN;
37
+ }
38
+ }
39
+ false
40
+ }
41
+
42
  async fn submit_rsvp(
43
+ req: HttpRequest,
44
  sb: web::Data<Supabase>,
45
  form: web::Json<RsvpRequest>,
46
  ) -> Result<HttpResponse, MyError> {
47
+ if !check_origin(&req) {
48
+ return Ok(HttpResponse::Forbidden().body("Origin tidak diizinkan"));
49
+ }
50
+
51
  Ok(HttpResponse::Ok().json(sb.submit_rsvp(form.into_inner()).await?))
52
  }
53
 
 
54
  async fn get_messages(
55
+ req: HttpRequest,
56
  sb: web::Data<Supabase>,
57
  ) -> Result<HttpResponse, MyError> {
58
+ if !check_origin(&req) {
59
+ return Ok(HttpResponse::Forbidden().body("Origin tidak diizinkan"));
60
+ }
61
+
62
  Ok(HttpResponse::Ok().json(sb.get_messages().await?))
63
  }
64
 
 
75
 
76
  HttpServer::new(move || {
77
  let cors = Cors::default()
78
+ .allowed_origin(ALLOWED_ORIGIN)
79
  .allowed_methods(vec!["HEAD","GET","POST"])
80
  .allowed_headers(vec!["Content-Type", "Authorization"])
81
  .max_age(3600);
82
 
83
  App::new()
84
  .wrap(cors)
 
85
  .app_data(web::Data::new(supabase.clone()))
86
  .route("/cek", web::get().to(health))
87
  .route("/health", web::head().to(health))