1 /** 2 * Общий модуль для работы с HTTP контроллерами 3 * 4 * Copyright: (c) 2015-2017, Milofon Project. 5 * License: Subject to the terms of the BSD license, as written in the included LICENSE.txt file. 6 * Authors: Maksim Galanin 7 */ 8 module dango.controller.core; 9 10 11 public 12 { 13 import vibe.http.router : URLRouter; 14 import vibe.http.common : HTTPMethod; 15 import vibe.http.server : HTTPServerRequestHandler; 16 17 import proped : Properties; 18 } 19 20 private 21 { 22 import vibe.http.server : HTTPServerRequest, HTTPServerResponse, 23 HTTPServerRequestDelegate; 24 } 25 26 27 /** 28 * Интерфейс для контроллера 29 */ 30 interface Controller 31 { 32 /** 33 * Инициализация контроллера 34 * Params: 35 * 36 * config = Конфигурация контроллера 37 */ 38 void initialize(Properties config); 39 40 /** 41 * Регистрация маршрутов контроллера 42 * Params: 43 * 44 * router = Маршрутизатор 45 */ 46 void registerRoutes(URLRouter router); 47 48 49 /** 50 * Возвращает активность контроллера 51 */ 52 bool enabled() @property; 53 } 54 55 56 57 void handleCors(HTTPServerRequest req, HTTPServerResponse res) @safe 58 { 59 if (req.method == HTTPMethod.OPTIONS) 60 return; 61 62 if (auto origin = "Origin" in req.headers) 63 { 64 res.headers["Access-Control-Allow-Origin"] = *origin; 65 res.headers["Access-Control-Allow-Credentials"] = "true"; 66 } 67 } 68 69 70 71 HTTPServerRequestDelegate createOptionCORSHandler() @safe 72 { 73 void handler(HTTPServerRequest req, HTTPServerResponse res) @safe 74 { 75 auto origin = "Origin" in req.headers; 76 if (origin is null) 77 return; 78 79 auto method = "Access-Control-Request-Method" in req.headers; 80 if (method is null) 81 return; 82 83 res.headers["Access-Control-Allow-Origin"] = *origin; 84 res.headers["Access-Control-Allow-Credentials"] = "true"; 85 res.headers["Access-Control-Max-Age"] = "1728000"; 86 res.headers["Access-Control-Allow-Methods"] = *method; 87 88 if (auto headers = "Access-Control-Request-Headers" in req.headers) 89 res.headers["Access-Control-Allow-Headers"] = *headers; 90 91 res.writeBody(""); 92 } 93 94 return &handler; 95 }