Skip to content

Commit fb8faf2

Browse files
committed
add Cors supports
1 parent 09fdafa commit fb8faf2

File tree

5 files changed

+50
-29
lines changed

5 files changed

+50
-29
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ edition = "2018"
88
actix-web = "2.0.0"
99
actix-rt = "1.0.0"
1010
actix-service = "1.0.1"
11+
actix-cors = "0.2.0"
1112
log = "0.4.8"
1213
log4rs = "0.9.0"
1314
diesel_migrations = "1.4.0"

README.md

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ curl -X POST -H 'Content-Type: application/json' -i 'http://127.0.0.1:8000/api/a
105105
106106
### `POST /api/auth/login`: Logout
107107
```bash
108-
curl -X POST -H 'Content-Type: application/json' -H 'Authorization: bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NzcyNTc4NzksImV4cCI6MTU3Nzg2MjY3OSwidXNlciI6ImMiLCJsb2dpbl9zZXNzaW9uIjoiYzUxNWE3NTg3NGYzNGVjNGFmNDJmNWE2M2QxMDVjMGYifQ.B9w6FxFdypb5GCRMKXZ9CZWFxQLFjvmPSusMCtcE-Ac' -i 'http://127.0.0.1:8000/api/auth/logout'
108+
curl -X POST -H 'Content-Type: application/json' -H 'Authorization: bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpYXQiOjE1NzcyNTc4NzksImV4cCI6MTU3Nzg2MjY3OSwidXNlciI6ImMiLCJsb2dpbl9zZXNzaW9uIjoiYzUxNWE3NTg3NGYzNGVjNGFmNDJmNWE2M2QxMDVjMGYifQ.B9w6FxFdypb5GCRMKXZ9CZWFxQLFjvmPSusMCtcE-Ac' -i 'http://127.0.0.1:8000/api/auth/logout'
109109
```
110110
111111
### `GET /api/address-book`: Get all people information
@@ -294,3 +294,15 @@ curl -X POST -H 'Content-Type: application/json' -H 'Authorization: bearer eyJ0e
294294
"data": ""
295295
}
296296
```
297+
### brower OPTIONS curl request example
298+
```
299+
curl -X OPTIONS -i 'http://127.0.0.1:8000/api/login' -H "Origin: http://example.com" -H "Access-Control-Request-Method: POST"
300+
```
301+
- Response
302+
HTTP/1.1 200 OK
303+
content-length: 0
304+
access-control-max-age: 3600
305+
access-control-allow-methods: POST,DELETE,GET,PUT
306+
access-control-allow-origin: *
307+
access-control-allow-headers: authorization,content-type,accept
308+
date: Tue, 07 Jan 2020 15:17:48 GMT

src/api/account_controller.rs

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,12 +26,7 @@ pub async fn login(login_dto: web::Json<LoginDTO>, pool: web::Data<Pool>) -> Res
2626
}
2727

2828
// POST api/auth/logout
29-
<<<<<<< HEAD
30-
pub fn logout(req: HttpRequest, pool: web::Data<Pool>) -> impl Future<Item = HttpResponse, Error = Error> {
31-
debug!("{:?}",req);
32-
=======
3329
pub async fn logout(req: HttpRequest, pool: web::Data<Pool>) -> Result<HttpResponse> {
34-
>>>>>>> bbc4914b638c3950e229f029fdcb3eb0f9a8e7f6
3530
if let Some(authen_header) = req.headers().get(constants::AUTHORIZATION) {
3631
account_service::logout(authen_header, &pool);
3732
Ok(HttpResponse::Ok().json(ResponseBody::new(constants::MESSAGE_LOGOUT_SUCCESS, constants::EMPTY)))

src/main.rs

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ extern crate serde_derive;
1313
#[macro_use]
1414
extern crate serde_json;
1515
extern crate actix_rt;
16+
extern crate actix_cors;
1617
// extern crate env_logger;
1718
extern crate log4rs;
1819
extern crate serde;
@@ -35,11 +36,12 @@ mod schema;
3536
mod services;
3637
mod utils;
3738

38-
use actix_web::{HttpServer, App};
39+
use actix_web::{http, HttpServer, App};
3940
use actix_service::Service;
4041
use futures::FutureExt;
4142
use std::{io, env};
4243
use std::default::Default;
44+
use actix_cors::Cors;
4345

4446
#[actix_rt::main]
4547
async fn main() -> io::Result<()> {
@@ -57,6 +59,14 @@ async fn main() -> io::Result<()> {
5759

5860
HttpServer::new(move || {
5961
App::new()
62+
.wrap(Cors::new() // run order: **2**
63+
// .allowed_origin("http://127.0.0.1:8080")
64+
.send_wildcard()
65+
.allowed_methods(vec!["GET", "POST", "PUT", "DELETE"])
66+
.allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
67+
.allowed_header(http::header::CONTENT_TYPE)
68+
.max_age(3600)
69+
.finish())
6070
.data(pool.clone())
6171
.wrap(actix_web::middleware::Logger::default())
6272
.wrap(crate::middleware::authen_middleware::Authentication)

src/middleware/authen_middleware.rs

Lines changed: 25 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use crate::{config::db::Pool, constants, models::response::ResponseBody, utils::token_utils};
22
use actix_service::{Service, Transform};
33
use actix_web::{
4+
http::{Method},
45
dev::{ServiceRequest, ServiceResponse},
56
Error, HttpResponse,
67
};
@@ -64,36 +65,38 @@ where
6465
// debug!("{:?}",pl);
6566
// let req2 = ServiceRequest::from_parts(r, pl);
6667
// assert!(ServiceRequest::from_parts(r, pl).is_ok());
67-
for ignore_route in constants::IGNORE_ROUTES.iter() {
68-
debug!("route:{}",ignore_route);
69-
if req.path().starts_with(ignore_route) {
70-
authenticate_pass = true;
68+
if Method::OPTIONS == *req.method() {
69+
authenticate_pass = true;
70+
} else {
71+
for ignore_route in constants::IGNORE_ROUTES.iter() {
72+
debug!("route:{}",ignore_route);
73+
if req.path().starts_with(ignore_route) {
74+
authenticate_pass = true;
75+
}
7176
}
72-
}
7377

74-
if let Some(pool) = req.app_data::<Pool>() {
75-
info!("Connecting to database...");
76-
if let Some(authen_header) = req.headers_mut().get(constants::AUTHORIZATION) {
77-
info!("Parsing authorization header...");
78-
if let Ok(authen_str) = authen_header.to_str() {
79-
if authen_str.starts_with("bearer") || authen_str.starts_with("Bearer") {
80-
info!("Parsing token...");
81-
let token = authen_str[6..authen_str.len()].trim();
82-
if let Ok(token_data) = token_utils::decode_token(token.to_string()) {
83-
info!("Decoding token...");
84-
if token_utils::verify_token(&token_data, &pool).is_ok() {
85-
info!("Valid token");
86-
authenticate_pass = true;
87-
} else {
88-
error!("Invalid token");
78+
if let Some(pool) = req.app_data::<Pool>() {
79+
info!("Connecting to database...");
80+
if let Some(authen_header) = req.headers_mut().get(constants::AUTHORIZATION) {
81+
info!("Parsing authorization header...");
82+
if let Ok(authen_str) = authen_header.to_str() {
83+
if authen_str.starts_with("bearer") || authen_str.starts_with("Bearer") {
84+
info!("Parsing token...");
85+
let token = authen_str[6..authen_str.len()].trim();
86+
if let Ok(token_data) = token_utils::decode_token(token.to_string()) {
87+
info!("Decoding token...");
88+
if token_utils::verify_token(&token_data, &pool).is_ok() {
89+
info!("Valid token");
90+
authenticate_pass = true;
91+
} else {
92+
error!("Invalid token");
93+
}
8994
}
9095
}
9196
}
9297
}
9398
}
9499
}
95-
96-
error!("{}", constants::MESSAGE_PROCESS_TOKEN_ERROR);
97100
if authenticate_pass {
98101
let fut = self.service.call(req);
99102
Box::pin(async move {

0 commit comments

Comments
 (0)