1 /**
2 * Copyright © DiamondMVC 2019
3 * License: MIT (https://github.com/DiamondMVC/Diamond/blob/master/LICENSE)
4 * Author: Jacob Jensen (bausshf)
5 */
6 module diamond.security.tokens.generictoken;
7 
8 import diamond.core.apptype;
9 
10 static if (isWeb)
11 {
12   import diamond.security.tokens.tokengenerator;
13 
14   /// Wrapper for a generic token generator.
15   final class GenericToken : TokenGenerator
16   {
17     import vibe.crypto.cryptorand;
18 
19     private:
20     /// The random generator for the generic token. TODO: Better RNG implementation ...
21     SHA1HashMixerRNG _randomGenerator;
22 
23     /// Creates a new generic token generator.
24     this()
25     {
26       super();
27 
28       _randomGenerator = new SHA1HashMixerRNG;
29     }
30 
31     public:
32     final:
33     /**
34     * Generates a token.
35     * Returns:
36     *   Returns the generated token.
37     */
38     override string generate()
39     {
40       import diamond.core.senc;
41 
42       ubyte[64] randomBuffer;
43       _randomGenerator.read(randomBuffer);
44 
45       return SENC.encode(randomBuffer);
46     }
47 
48     /**
49     * Generates a token. The input is ignored.
50     * Params:
51     *   input = Discarded for generic tokens.
52     * Returns:
53     *   Returns the generated token.
54     */
55     override string generate(string input)
56     {
57       return generate();
58     }
59 
60     /**
61     * Generates a token and passes it to the parent generator.
62     * Params:
63     *   parentGenerator = The parent generator to use with the generated token.
64     * Returns:
65     *   Returns the generated token.
66     */
67     override string generate(TokenGenerator parentGenerator)
68     {
69       import diamond.errors.checks;
70       enforce(parentGenerator, "Passed no parent generator.");
71 
72       return parentGenerator.generate(this.generate());
73     }
74   }
75 
76   /// The generic token instance for the current thread.
77   private GenericToken _genericToken;
78 
79   @property
80   {
81     /// Gets the generic token generator.
82     GenericToken genericToken()
83     {
84       if (!_genericToken)
85       {
86         _genericToken = new GenericToken;
87       }
88 
89       return _genericToken;
90     }
91   }
92 }