1 module vibeauth.mvc.controller;
2 
3 import std.string;
4 
5 import vibeauth.mvc.templatedata;
6 import vibeauth.configuration;
7 
8 import std.algorithm;
9 
10 import vibe.http.router;
11 import vibe.data.json;
12 
13 import vibeauth.users;
14 
15 /// Generic controller
16 interface IController {
17   /// Returns true if the request can be handled by the controller
18   bool canHandle(HTTPServerRequest);
19 
20   /// Handle the client request
21   void handle(HTTPServerRequest req, HTTPServerResponse res);
22 }
23 
24 /// A controller that can handle paths defined in the service configuration
25 abstract class PathController(string method, string configurationPath) : IController {
26   protected {
27     UserCollection userCollection;
28     ServiceConfiguration configuration;
29     string path;
30   }
31 
32   /// Create the object
33   this(UserCollection userCollection, ServiceConfiguration configuration) {
34     this.userCollection = userCollection;
35     this.configuration = configuration;
36 
37     mixin("path = configuration." ~ configurationPath ~ ";");
38   }
39 
40   /// Returns true if the request and path matches with the template values
41   bool canHandle(HTTPServerRequest req) {
42     mixin("auto method = HTTPMethod." ~ method ~ ";");
43     if(req.method != method) {
44       return false;
45     }
46     
47     if(path.canFind(":id")) {
48       if(!isUserPage(path, req.path)) {
49         return false;
50       }
51 
52       TemplateData data;
53       data.set(":id", path, req.path);
54 
55       try {
56         userCollection.byId(data.get(":id"));
57       } catch(UserNotFoundException) {
58         return false;
59       }
60 
61       req.context["userId"] = data.get(":id");
62     } else if(path != req.path) {
63       return false;
64     }
65 
66 
67     return true;
68   }
69 }