1 /** 2 * Модуль реализации Middleware авторизации BaseAuth 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.baseauth; 11 12 private 13 { 14 import std..string : strip; 15 import std.format : fmt = format; 16 17 import vibe.http.auth.basic_auth; 18 19 import dango.system.properties : getOrEnforce; 20 import dango.web.middleware; 21 } 22 23 24 /** 25 * Middleware позволяет реализовать аутентификацию baseauth 26 */ 27 class BaseAuthWebMiddleware : WebMiddleware 28 { 29 private 30 { 31 string _username; 32 string _password; 33 string _realm; 34 } 35 36 /** 37 * Main constructor 38 */ 39 this(string username, string password, string realm) @safe 40 { 41 this._username = username; 42 this._password = password; 43 this._realm = realm; 44 } 45 46 /** 47 * Обработка запроса 48 */ 49 void handleRequest(scope HTTPServerRequest req, scope HTTPServerResponse res, 50 HTTPServerRequestDelegate next) @safe 51 { 52 if (!checkBasicAuth(req, &passwordCheck)) 53 { 54 res.headers["WWW-Authenticate"] = fmt!"Basic realm=\"%s\""(_realm); 55 res.writeBody("Need authentication", 401); 56 return; 57 } 58 next(req, res); 59 } 60 61 /** 62 * Регистрация цепочек маршрутов middleware 63 */ 64 void registerHandlers(HTTPMethod method, string path, RegisterHandlerCallback dg) @safe 65 { 66 // nothing 67 } 68 69 70 private: 71 72 73 bool passwordCheck(string user, string passwd) @safe 74 { 75 return user.strip == _username && passwd.strip == _password; 76 } 77 } 78 79 80 /** 81 * Фабрика Middleware baseauth 82 */ 83 class BaseAuthWebMiddlewareFactory : WebMiddlewareFactory 84 { 85 WebMiddleware createComponent(DependencyContainer cont, UniConf config) @safe 86 { 87 string username = config.getOrEnforce!string("username", 88 "Not defined username parameter").strip; 89 string password = config.getOrEnforce!string("password", 90 "Not defined password parameter").strip; 91 string realm = config.getOrElse!string("realm", ""); 92 93 return new BaseAuthWebMiddleware(username, password, realm); 94 } 95 } 96