Merge pull request #130 from OktopUSP/cors_by_env

Get cors allowed origins from env file [ close #116 ]
This commit is contained in:
Leandro Antônio Farias Machado 2023-10-14 14:18:11 -03:00 committed by GitHub
commit a68b3c0b72
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 1120 additions and 8 deletions

View File

@ -10,3 +10,4 @@ BROKER_PASSWORD=""
BROKER_CLIENTID=""
BROKER_QOS=""
REST_API_PORT=""
REST_API_CORS="" # addresses must be separated by commas example: "http://localhost:3000,http://myapp.com"

View File

@ -3,13 +3,16 @@ package cors
import (
"github.com/rs/cors"
"net/http"
"os"
"strings"
"fmt"
)
func GetCorsConfig() cors.Cors {
allowedOrigins := getCorsEnvConfig()
fmt.Println(allowedOrigins)
return *cors.New(cors.Options{
AllowedOrigins: []string{
"http://localhost:3000",
},
AllowedOrigins: allowedOrigins,
AllowedMethods: []string{
http.MethodGet,
http.MethodPost,
@ -25,3 +28,11 @@ func GetCorsConfig() cors.Cors {
},
})
}
func getCorsEnvConfig() []string {
val, _ := os.LookupEnv("REST_API_CORS")
if val == "" {
return []string{"*"}
}
return strings.Split(val, ",")
}

View File

@ -0,0 +1,2 @@
CORS_ALLOWED_ORIGINS=""
# addresses must be separated by commas example: "http://localhost:3000,http://myapp.com"

View File

@ -1 +1,2 @@
node_modules/
.env.local

File diff suppressed because it is too large Load Diff

View File

@ -13,6 +13,7 @@
"dependencies": {
"@koa/cors": "^4.0.0",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"koa": "^2.14.2",
"socket.io": "^4.6.2"

View File

@ -1,13 +1,24 @@
const dotenv = require('dotenv')
dotenv.config();
dotenv.config({ path: `.env.local`, override: true });
const express = require('express');
const app = express();
const PORT = 5000;
const http = require('http').Server(app);
const cors = require('cors');
var allowedOrigins;
let allowedOriginsFromEnv = process.env.CORS_ALLOWED_ORIGINS.split(',')
if (allowedOriginsFromEnv.length > 1) {
allowedOrigins = allowedOriginsFromEnv
}else{
allowedOrigins = "*"
}
console.log("allowedOrigins:",allowedOrigins)
const io = require('socket.io')(http, {
cors: {
origin: "http://localhost:3000"
origin: allowedOrigins
}
});