3 * Copyright 2017 RIFT.IO Inc
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
20 * CSRF util for use across the api_server.
21 * @module framework/core/api_utils/csrf
22 * @author Kiran Kashalkar <kiran.kashalkar@riftio.com>
25 var constants
= require('./constants.js');
26 var utils
= require('./utils.js');
30 function configure(config
) {
31 target
= config
.target
;
34 function csrfCheck(req
, res
, next
) {
37 if (req
.headers
.origin
!= 'null') {
38 host
= utils
.getHostNameFromURL(req
.headers
.origin
);
39 } else if (req
.headers
.referer
) {
40 host
= utils
.getHostNameFromURL(req
.headers
.referer
);
42 var msg
= 'Request did not contain an origin or referer header. Request terminated.';
44 error
.statusCode
= constants
.HTTP_RESPONSE_CODES
.ERROR
.METHOD_NOT_ALLOWED
;
45 error
.errorMessage
= {
48 return utils
.sendErrorResponse(error
, res
);
51 if (!host
|| host
!= target
) {
52 var msg
= 'Request did not originate from authorized source (Potential CSRF attempt). Request terminated.';
54 error
.statusCode
= constants
.HTTP_RESPONSE_CODES
.ERROR
.METHOD_NOT_ALLOWED
;
55 error
.errorMessage
= {
58 return utils
.sendErrorResponse(error
, res
);