1 /**
2  * Модуль реализации Middleware аутентификации по токену
3  *
4  * Copyright: (c) 2015-2020, Milofon Project.
5  * License: Subject to the terms of the BSD 3-Clause License, as written in the included LICENSE.md file.
6  * Author: <m.galanin@milofon.pro> Maksim Galanin
7  * Date: 2020-04-30
8  */
9 
10 module dango.web.middlewares.tokenauth;
11 
12 private
13 {
14     import dango.system.properties : getOrEnforce;
15     import dango.web.middleware;
16 }
17 
18 
19 /**
20  * Middleware позволяет реализовать авторизацию по токену
21  */
22 class TokenAuthWebMiddleware : WebMiddleware
23 {
24     private string _token;
25 
26     /**
27      * Main container
28      */
29     this(string token) @safe
30     {
31         this._token = token;
32     }
33 
34     /**
35      * Обработка запроса
36      */
37     void handleRequest(scope HTTPServerRequest req, scope HTTPServerResponse res,
38             HTTPServerRequestDelegate next) @safe
39     {
40         auto token = "X-Auth-Token" in req.headers;
41         if (!token || *token != _token)
42         {
43             res.writeBody("Need authentication", 403);
44             return;
45         }
46 
47         next(req, res);
48     }
49 
50     /**
51      * Регистрация цепочек маршрутов middleware
52      */
53     void registerHandlers(HTTPMethod method, string path, RegisterHandlerCallback dg) @safe
54     {
55         // nothing
56     }
57 }
58 
59 
60 /**
61  * Фабрика Middleware tokenauth
62  */
63 class TokenAuthWebMiddlewareFactory : WebMiddlewareFactory
64 {
65     WebMiddleware createComponent(DependencyContainer cont, UniConf config) @safe
66     {
67         string token = config.getOrEnforce!string("token",
68                 "Token API is not defined");
69         return new TokenAuthWebMiddleware(token);
70     }
71 }
72