-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
58 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
55 changes: 55 additions & 0 deletions
55
src/main/scala/com/github/qubo/seed/routes/CorsHelper.scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package com.github.qubo.seed.routes | ||
|
||
|
||
import spray.http.HttpHeaders._ | ||
import spray.http.HttpMethods._ | ||
import spray.http._ | ||
import spray.routing._ | ||
import spray.util._ | ||
|
||
trait CorsHelper { | ||
this: HttpService => | ||
val MaxAge = 1728000 | ||
|
||
def p3p(value: String = """CP="CAO PSA OUR""""): Directive0 = | ||
mapHttpResponseHeaders(_ ++ List(RawHeader("P3P", value))) | ||
|
||
def cors(origins: Seq[String]): Directive0 = | ||
cors(SomeOrigins(origins.map(HttpOrigin(_)))) | ||
|
||
def cors(origin: String): Directive0 = | ||
if (origin == "*") { | ||
cors(AllOrigins) | ||
} else { | ||
cors(SomeOrigins(Seq(HttpOrigin(origin)))) | ||
} | ||
|
||
def cors(origins: AllowedOrigins): Directive0 = mapRequestContext { ctx => | ||
val originHeader = if (origins == AllOrigins) { | ||
ctx.request.headers.findByType[`Origin`] | ||
} else { | ||
None | ||
} | ||
val resOrigins = originHeader.map { case Origin(origin) => SomeOrigins(origin) }.getOrElse(origins) | ||
ctx.withRouteResponseHandling({ | ||
//It is an option request for a resource that responds to some other method | ||
case Rejected(x) if ctx.request.method.equals(HttpMethods.OPTIONS) => | ||
ctx.complete(HttpResponse().withHeaders( | ||
allowOriginHeader(resOrigins) ++ fixedCorsHeaders | ||
)) | ||
}).withHttpResponseHeadersMapped { headers => | ||
allowOriginHeader(resOrigins) ++ fixedCorsHeaders ++ headers | ||
} | ||
} & p3p() | ||
|
||
private def fixedCorsHeaders: List[HttpHeader] = | ||
List( | ||
`Access-Control-Allow-Methods`(GET, POST, PATCH, PUT, DELETE, OPTIONS), | ||
`Access-Control-Allow-Headers`("Content-Type,Accept-Language,Authorization"), | ||
`Access-Control-Allow-Credentials`(true), | ||
`Access-Control-Max-Age`(MaxAge) | ||
) | ||
|
||
private def allowOriginHeader(origins: AllowedOrigins): List[HttpHeader] = | ||
List(`Access-Control-Allow-Origin`(origins)) | ||
} |