1 module vibeauth.authenticators.BaseAuth; 2 3 import vibe.http.router; 4 import vibe.data.json; 5 import vibeauth.collections.usercollection; 6 import vibeauth.router.accesscontrol; 7 8 import std.algorithm.searching, std.base64, std..string, std.stdio; 9 10 /// The results that that an authenticator can return 11 enum AuthResult { 12 /// The request does not contain valid auth data 13 invalidToken, 14 15 /// The request does not contain the required data to perform the request 16 unauthorized, 17 18 /// The request can continue because the user has the necessesary rights 19 success 20 } 21 22 /// Base class for using authentication with vibe requests 23 abstract class BaseAuth { 24 25 protected UserCollection collection; 26 27 /// Instantiate the authenticator with an user collection 28 this(UserCollection collection) { 29 this.collection = collection; 30 } 31 32 /// Auth handler that will fail if a successfull auth was not performed. 33 /// This handler is usefull for routes that want to hide information to the 34 /// public. 35 void mandatoryAuth(HTTPServerRequest req, HTTPServerResponse res) { 36 setAccessControl(res); 37 38 if(mandatoryAuth(req) == AuthResult.unauthorized) { 39 respondUnauthorized(res); 40 } 41 42 if(mandatoryAuth(req) == AuthResult.invalidToken) { 43 respondInvalidToken(res); 44 } 45 } 46 47 /// Auth handler that fails only if the auth fields are present and are not valid. 48 /// This handler is usefull when a route should return different data when the user is 49 /// logged in 50 void permisiveAuth(HTTPServerRequest req, HTTPServerResponse res) { 51 setAccessControl(res); 52 53 if(permisiveAuth(req) == AuthResult.unauthorized) { 54 respondUnauthorized(res); 55 } 56 57 if(permisiveAuth(req) == AuthResult.invalidToken) { 58 respondInvalidToken(res); 59 } 60 } 61 62 abstract { 63 /// Auth handler that will fail if a successfull auth was not performed. 64 /// This handler is usefull for routes that want to hide information to the 65 /// public. 66 AuthResult mandatoryAuth(HTTPServerRequest req); 67 68 /// Auth handler that fails only if the auth fields are present and are not valid. 69 /// This handler is usefull when a route should return different data when the user is 70 /// logged in 71 AuthResult permisiveAuth(HTTPServerRequest req); 72 73 /// Set the response code and message to notify the client that it does not have 74 /// rights to make the request 75 void respondUnauthorized(HTTPServerResponse res); 76 77 /// Set the response code and message to notify the client that 78 /// there were a problem with the request 79 void respondInvalidToken(HTTPServerResponse res); 80 } 81 }