@@ -2,6 +2,8 @@ package server
22
33import (
44 "net/http"
5+ "regexp"
6+ "strings"
57
68 "reverse-watch/api"
79 "reverse-watch/config"
@@ -10,6 +12,7 @@ import (
1012
1113 "github.com/go-chi/chi/v5"
1214 "github.com/go-chi/chi/v5/middleware"
15+ "github.com/go-chi/cors"
1316)
1417
1518type Server struct {
@@ -19,6 +22,33 @@ type Server struct {
1922func New (cfg config.Config , factory repository.Factory ) (* Server , error ) {
2023 r := chi .NewRouter ()
2124
25+ firefoxExtensionOrigin := regexp .MustCompile ("^moz-extension://[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" )
26+
27+ r .Use (cors .Handler (cors.Options {
28+ AllowOriginFunc : func (r * http.Request , origin string ) bool {
29+ for _ , allowedOrigin := range cfg .HTTP .AllowedOrigins {
30+ if allowedOrigin == origin {
31+ return true
32+ }
33+ }
34+
35+ if cfg .HTTP .AllowFirefoxExtensions {
36+ // Firefox extension IDs are randomly generated for each user.
37+ // Therefore, we're scoping requests made from Firefox extensions to specific endpoints only.
38+ if firefoxExtensionOrigin .MatchString (origin ) {
39+ if strings .HasPrefix (r .RequestURI , "/api/v1/users/" ) {
40+ return true
41+ }
42+ }
43+ }
44+ return false
45+ },
46+ AllowedMethods : []string {"GET" , "OPTIONS" },
47+ AllowedHeaders : []string {"Accept" , "Content-Type" },
48+ AllowCredentials : true ,
49+ MaxAge : 300 ,
50+ }))
51+
2252 r .Use (middleware .Recoverer )
2353 r .Use (middleware .RequestID )
2454 r .Use (middleware .RealIP )
0 commit comments