Просмотр исходного кода

Implement CORS origin handling and update app.js to use it

yazid138 1 день назад
Родитель
Сommit
8fc61253c0
2 измененных файлов с 19 добавлено и 1 удалено
  1. 3 1
      app.js
  2. 16 0
      utils/origin.js

+ 3 - 1
app.js

@@ -5,13 +5,15 @@ const logger = require('morgan')
 const cors = require('cors')
 const csrf = require('./middleware/csrf')
 const response = require('./utils/responseHandler')
+const {origin} = require('./utils/origin')
+
 const app = express()
 
 require('./config/db')()
 
 app.use(logger('dev'))
 app.use(express.json())
-app.use(cors({ origin: true, credentials: true }))
+app.use(cors({ origin: origin([]), credentials: true }))
 app.use(express.urlencoded({ extended: false }))
 app.use(cookieParser(process.env.SRU51))
 // app.use(csrf( ['GET', 'HEAD', 'OPTIONS'], ['/v1/auth/login', /\/v1\/auto\//i, /v2/i]))

+ 16 - 0
utils/origin.js

@@ -0,0 +1,16 @@
+exports.origin = (whitelist) => (origin, callback) => {
+  // Allow requests with no origin (mobile apps, postman, curl)
+  if (!origin) return callback(null, true)
+
+  // Allow exact domain
+  if (whitelist.includes(origin)) {
+    return callback(null, true)
+  }
+
+  // Allow localhost with any port
+  if (origin.startsWith('http://localhost')) {
+    return callback(null, true)
+  }
+
+  return callback(new Error('Not allowed by CORS'))
+}