Skip to content

Commit 375ed2d

Browse files
committed
Auto merge of #3306 - Turbo87:origin, r=JohnTitor
controllers::util: Clean up `verify_origin()` function This PR simplifies the code of the `verify_origin()` function by removing the additional `Vec` allocation. It also converts the function comment to a doc comment. r? `@jtgeibel`
2 parents e77c078 + c26e278 commit 375ed2d

File tree

1 file changed

+9
-13
lines changed

1 file changed

+9
-13
lines changed

src/controllers/util.rs

Lines changed: 9 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -30,25 +30,21 @@ impl AuthenticatedUser {
3030
}
3131
}
3232

33-
// The Origin header (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin)
34-
// is sent with CORS requests and POST requests, and indicates where the request comes from.
35-
// We don't want to accept authenticated requests that originated from other sites, so this
36-
// function returns an error if the Origin header doesn't match what we expect "this site" to
37-
// be: https://crates.io in production, or http://localhost:port/ in development.
33+
/// The Origin header (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Origin)
34+
/// is sent with CORS requests and POST requests, and indicates where the request comes from.
35+
/// We don't want to accept authenticated requests that originated from other sites, so this
36+
/// function returns an error if the Origin header doesn't match what we expect "this site" to
37+
/// be: https://crates.io in production, or http://localhost:port/ in development.
3838
fn verify_origin(req: &dyn RequestExt) -> AppResult<()> {
3939
let headers = req.headers();
40-
let allowed_origins = req
41-
.app()
42-
.config
43-
.allowed_origins
44-
.iter()
45-
.map(|s| &**s)
46-
.collect::<Vec<_>>();
40+
let allowed_origins = &req.app().config.allowed_origins;
4741

4842
let bad_origin = headers
4943
.get_all(header::ORIGIN)
5044
.iter()
51-
.find(|h| !allowed_origins.contains(&h.to_str().unwrap_or_default()));
45+
.filter_map(|value| value.to_str().ok())
46+
.find(|value| !allowed_origins.iter().any(|it| it == value));
47+
5248
if let Some(bad_origin) = bad_origin {
5349
let error_message = format!(
5450
"only same-origin requests can be authenticated. got {:?}",

0 commit comments

Comments
 (0)