parent
ac1d221f38
commit
ffc057c2c5
@ -0,0 +1,12 @@
|
||||
import {env, HTTPMethod} from '@extollo/lib'
|
||||
|
||||
export default {
|
||||
enable: env('ENABLE_CORS', false),
|
||||
allow: {
|
||||
origins: [
|
||||
'https://garrettmills.dev',
|
||||
'https://glmdev.tech',
|
||||
] as string[],
|
||||
methods: ['post', 'get', 'options'] as HTTPMethod[],
|
||||
},
|
||||
}
|
@ -0,0 +1,48 @@
|
||||
import {Middleware, Injectable, Inject, Config, HTTPMethod, Response, HTTPStatus, http, Logging} from '@extollo/lib'
|
||||
|
||||
/**
|
||||
* CORS Middleware
|
||||
* --------------------------------------------
|
||||
* Put some description here.
|
||||
*/
|
||||
@Injectable()
|
||||
export class CORS extends Middleware {
|
||||
@Inject()
|
||||
protected readonly config!: Config
|
||||
|
||||
@Inject()
|
||||
protected readonly logging!: Logging
|
||||
|
||||
public async apply() {
|
||||
this.logging.debug('CORS Middleware')
|
||||
if ( !this.config.get('cors.enable', false) ) {
|
||||
this.logging.debug('Will not send CORS headers: CORS is disabled.')
|
||||
return
|
||||
}
|
||||
|
||||
const response: Response = this.request.response
|
||||
response.setHeader('Access-Control-Allow-Headers', '*')
|
||||
|
||||
if ( this.config.get('server.debug', false) ) {
|
||||
response.setHeader('Access-Control-Allow-Origin', '*')
|
||||
response.setHeader('Access-Control-Allow-Methods', '*')
|
||||
|
||||
if ( this.request.method === 'options' ) {
|
||||
return http(HTTPStatus.NO_CONTENT)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
const origins = this.config.get('cors.allow.origins', []) as string[]
|
||||
response.setHeader('Access-Control-Allow-Origin', origins.join(','))
|
||||
|
||||
const methods = this.config.get('cors.allow.methods') as HTTPMethod[]
|
||||
response.setHeader('Access-Control-Allow-Methods', methods.map(x => x.toUpperCase()).join(','))
|
||||
|
||||
if ( this.request.method === 'options' ) {
|
||||
response.setStatus(HTTPStatus.NO_CONTENT)
|
||||
return ''
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in new issue