Browse code

Updates

Benjamin Roth authored on01/06/2023 23:39:31
Showing7 changed files
... ...
@@ -8,3 +8,6 @@ services:
8 8
         resource: ../src
9 9
         exclude: ../src/{VossmedienDacoreBundle.php,ContaoManager,Entity,Migrations,Model,Resources,Tests,Widget}
10 10
 
11
+    dacore.generator.code_generator:
12
+        class: vossmedien\DacoreBundle\Generator\CodeGenerator
13
+        public: true
11 14
new file mode 100644
... ...
@@ -0,0 +1,15 @@
1
+<?php
2
+
3
+declare(strict_types=1);
4
+
5
+/*
6
+ * This file is part of dacore bundle for Contao.
7
+ *
8
+ * (c) Benjamin Roth
9
+ *
10
+ * @license commercial
11
+ */
12
+
13
+use vossmedien\DacoreBundle\Model\VrApiUserCounterModel;
14
+
15
+$GLOBALS['TL_MODELS']['tl_vr_api_user_counter'] = VrApiUserCounterModel::class;
0 16
new file mode 100644
... ...
@@ -0,0 +1,32 @@
1
+<?php
2
+
3
+declare(strict_types=1);
4
+
5
+/*
6
+ * This file is part of alox bundle for Contao.
7
+ *
8
+ * (c) Benjamin Roth
9
+ *
10
+ * @license commercial
11
+ */
12
+
13
+$GLOBALS['TL_DCA']['tl_vr_api_user_counter'] = [
14
+    'config' => [
15
+        'sql' => [
16
+            'keys' => [
17
+                'id' => 'primary',
18
+            ]
19
+        ]
20
+    ],
21
+    'fields' => [
22
+        'id' => [
23
+            'sql' => "int(10) unsigned NOT NULL auto_increment"
24
+        ],
25
+        'tstamp' => [
26
+            'sql' => "int(10) unsigned NOT NULL 0"
27
+        ],
28
+        'created' => [
29
+            'sql' => "int(10) unsigned NOT NULL 0"
30
+        ],
31
+    ]
32
+];
... ...
@@ -122,7 +122,7 @@ class Softgarden
122 122
             ]
123 123
         ];
124 124
 
125
-        $response = $this->sendRequest('jobs/' . $jobId . '/application',$options, 'POST');
125
+        $response = $this->sendRequest('jobs/' . $jobId . '/application',$options);
126 126
 
127 127
         if ($response->getStatusCode() == 200)
128 128
         {
... ...
@@ -156,7 +156,7 @@ class Softgarden
156 156
         return null;
157 157
     }
158 158
 
159
-    public function getApplication($applicationId, $token_type, $access_token)
159
+    public function getApplication(string $applicationId, $token_type, $access_token)
160 160
     {
161 161
         // bewerber@dacore.api / Aebekai2ail4coum
162 162
         $options = [
... ...
@@ -172,12 +172,66 @@ class Softgarden
172 172
         {
173 173
             $content = json_decode($response->getContent());
174 174
 
175
-            return count($content) < 2 ? array_shift($content) : $content;
175
+            return $content;
176 176
         }
177 177
 
178 178
         return null;
179 179
     }
180 180
 
181
+    public function deleteApplication(string $applicationId, $token_type, $access_token)
182
+    {
183
+        // bewerber@dacore.api / Aebekai2ail4coum
184
+        $options = [
185
+            'headers' => [
186
+                'Authorization: ' . $token_type . ' ' . $access_token,
187
+                'Content-Type: application/json'
188
+            ]
189
+        ];
190
+
191
+        $response = $this->sendRequest('applications/' . $applicationId,$options,'DELETE');
192
+
193
+        if ($response->getStatusCode() == 204)
194
+        {
195
+            return true;
196
+        }
197
+
198
+        return false;
199
+    }
200
+
201
+    public function createApplicantUser(string $username,string $password,?string $email=null)
202
+    {
203
+        if ($email === null)
204
+        {
205
+            $email = $username;
206
+        }
207
+
208
+        $options = [
209
+            'auth_basic' => $this->getBasicAuthorization(),
210
+            'headers' => [
211
+                'Content-Type: application/json'
212
+            ],
213
+            'body' => json_encode([
214
+                'salutation' => 0,
215
+                'firstname' => 'Dacore',
216
+                'lastname' => 'Bewerber',
217
+                'username' => $username,
218
+                'password' => $password,
219
+                'email' => $email,
220
+                'locale' => 'de',
221
+                'dataPrivacyAccepted' => true
222
+            ])
223
+        ];
224
+
225
+        $response = $this->sendRequest('applicants',$options,'POST');
226
+
227
+        if ($response->getStatusCode() == 204)
228
+        {
229
+            return true;
230
+        }
231
+
232
+        return false;
233
+    }
234
+
181 235
     public function getUserAccessToken($username, $password)
182 236
     {
183 237
         // bewerber@dacore.api / Aebekai2ail4coum
... ...
@@ -12,6 +12,7 @@ declare(strict_types=1);
12 12
 
13 13
 namespace vossmedien\DacoreBundle\Controller\Frontend\Module;
14 14
 
15
+use Contao\Controller;
15 16
 use Contao\CoreBundle\Controller\FrontendModule\AbstractFrontendModuleController;
16 17
 use Contao\CoreBundle\ServiceAnnotation\FrontendModule;
17 18
 use Contao\ModuleModel;
... ...
@@ -19,8 +20,11 @@ use Contao\PageModel;
19 20
 use Contao\Template;
20 21
 use Haste\Form\Form;
21 22
 use Symfony\Component\HttpFoundation\Request;
23
+use Symfony\Component\HttpFoundation\RequestStack;
22 24
 use Symfony\Component\HttpFoundation\Response;
23 25
 use vossmedien\DacoreBundle\API\Softgarden;
26
+use vossmedien\DacoreBundle\Generator\CodeGenerator;
27
+use vossmedien\DacoreBundle\Model\VrApiUserCounterModel;
24 28
 
25 29
 /**
26 30
  * @FrontendModule(JobApplicationFormController::TYPE, category="miscellaneous")
... ...
@@ -34,15 +38,46 @@ class JobApplicationFormController extends AbstractFrontendModuleController
34 38
      */
35 39
     protected $api;
36 40
 
37
-    public function __construct(Softgarden $api)
41
+    /**
42
+     * @var RequestStack
43
+     */
44
+    protected $requestStack;
45
+
46
+    public function __construct(Softgarden $api, RequestStack $requestStack)
38 47
     {
39 48
         $this->api = $api;
49
+        $this->requestStack = $requestStack;
40 50
     }
41 51
 
42 52
 
43 53
     protected function getResponse(Template $template, ModuleModel $model, Request $request): ?Response
44 54
     {
45
-        if (($userToken = $this->api->getUserAccessToken('bewerber@dacore.api','Aebekai2ail4coum')) === null)
55
+        $session = $this->requestStack->getSession();
56
+        $arrApiUser = [];
57
+
58
+
59
+        if (!$session->has('vr_api_user'))
60
+        {
61
+            $time = time();
62
+
63
+            $NewApiUser = new VrApiUserCounterModel();
64
+            $NewApiUser->setRow(['tstamp'=>$time,'created'=>$time]);
65
+            $NewApiUser->save()->refresh();
66
+
67
+            $arrApiUser = [
68
+                'username' => 'bewerber' . $NewApiUser->id . '@dacore.api',
69
+                'password' => $this->generatePassword()
70
+            ];
71
+
72
+            if ($this->api->createApplicantUser($arrApiUser['username'],$arrApiUser['password']))
73
+            {
74
+                $session->set('vr_api_user',$arrApiUser);
75
+            }
76
+        } else {
77
+            $arrApiUser = $session->get('vr_api_user');
78
+        }
79
+
80
+        if (($userToken = $this->api->getUserAccessToken($arrApiUser['username'],$arrApiUser['password'])) === null)
46 81
         {
47 82
             return new Response();
48 83
         }
... ...
@@ -55,7 +90,7 @@ class JobApplicationFormController extends AbstractFrontendModuleController
55 90
         }
56 91
 
57 92
         $application = $this->api->getApplication($applicationId,$userToken->token_type,$userToken->access_token);
58
-
93
+dump($application);
59 94
         if ($application !== null && isset($application->applicationEditable) && !$application->applicationEditable)
60 95
         {
61 96
             return new Response('Already applied');
... ...
@@ -81,4 +116,21 @@ class JobApplicationFormController extends AbstractFrontendModuleController
81 116
         return $template->getResponse();
82 117
     }
83 118
 
119
+    protected function generatePassword()
120
+    {
121
+        $digits    = array_flip(range('0', '9'));
122
+        $lowercase = array_flip(range('a', 'z'));
123
+        $uppercase = array_flip(range('A', 'Z'));
124
+        $special   = array_flip(str_split('!@#$%^&*()_+=-}{[}]\|;:<>?/'));
125
+        $combined  = array_merge($digits, $lowercase, $uppercase, $special);
126
+
127
+        $password  = str_shuffle(array_rand($digits) .
128
+            array_rand($lowercase) .
129
+            array_rand($uppercase) .
130
+            array_rand($special) .
131
+            implode(array_rand($combined, 8)));
132
+
133
+        return $password;
134
+    }
135
+
84 136
 }
85 137
new file mode 100644
... ...
@@ -0,0 +1,124 @@
1
+<?php
2
+
3
+declare(strict_types=1);
4
+
5
+/*
6
+ * This file is part of dacore bundle for Contao.
7
+ *
8
+ * (c) Benjamin Roth
9
+ *
10
+ * @license commercial
11
+ */
12
+
13
+namespace vossmedien\DacoreBundle\Generator;
14
+
15
+class CodeGenerator
16
+{
17
+    /**
18
+     * Seed presets
19
+     */
20
+    public const SEED_NUMERIC = 1;
21
+    public const SEED_LETTERS_LOWER = 2;
22
+    public const SEED_LETTERS_UPPER = 4;
23
+    public const SEED_SYMBOLS = 8;
24
+
25
+    public const SEED_READABLE = 5;
26
+    public const SEED_LETTERS_MIXED = 6;
27
+    public const SEED_SECURE = 15;
28
+
29
+
30
+    /**
31
+     * Generate a code
32
+     *
33
+     * @param array $arrOptions
34
+     * @return string
35
+     */
36
+    public function generate($arrOptions = [])
37
+    {
38
+        $arrOptions = array_merge
39
+        (
40
+            array
41
+            (
42
+                'length'      => 12, // ToDo: Retrieve default length from global settings
43
+                'seed_preset' => self::SEED_SECURE,
44
+                'custom_seed' => null,
45
+                'prefix'      => '',
46
+                'suffix'      => '',
47
+            ),$arrOptions
48
+        );
49
+
50
+
51
+        if (intval($arrOptions['length']) < 5)
52
+        {
53
+            throw new \InvalidArgumentException('The length option has to be at least 5.');
54
+        }
55
+
56
+        // Seed presets
57
+        $numbers     = [1,2,3,4,5,6,7,8,9];
58
+        $lowercase   = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
59
+        $uppercase   = ['A','B','C','D','E','F','G','H','J','K','L','M','N','P','Q','R','S','T','U','V','W','X','Y','Z'];
60
+        $symbols     = ['°','!','§','$','%','&','/','(',')','=','?','*','+','~','#','-','_','.',':',';','>','<','|','[',']','{','}','\\'];
61
+
62
+        $seed = [];
63
+        $code = '';
64
+
65
+        // Use custom seed
66
+        if ($arrOptions['custom_seed'] !== null)
67
+        {
68
+            if (is_array($arrOptions['custom_seed']))
69
+            {
70
+                $seed = $arrOptions['custom_seed'];
71
+            } elseif (is_string($arrOptions['custom_seed']))
72
+            {
73
+                $seed = str_split($arrOptions['custom_seed'],1);
74
+            } else {
75
+                throw new \InvalidArgumentException('The custom_seed option needs to be an array or string.');
76
+            }
77
+        } else
78
+        {
79
+            // Add numbers to seed
80
+            if ($arrOptions['seed_preset'] & self::SEED_NUMERIC)
81
+            {
82
+                $seed = array_merge($seed, $numbers, $numbers); // add numbers twice to increase their occurrence in generated code
83
+            }
84
+
85
+            // Add lowercase letters to seed
86
+            if ($arrOptions['seed_preset'] & self::SEED_LETTERS_LOWER)
87
+            {
88
+                $seed = array_merge($seed, $lowercase);
89
+            }
90
+
91
+            // Add uppercase letters to seed
92
+            if ($arrOptions['seed_preset'] & self::SEED_LETTERS_UPPER)
93
+            {
94
+                $seed = array_merge($seed, $uppercase);
95
+            }
96
+
97
+            // Add symbols to seed
98
+            if ($arrOptions['seed_preset'] & self::SEED_SYMBOLS)
99
+            {
100
+                $seed = array_merge($seed, $symbols);
101
+            }
102
+        }
103
+
104
+        // Generate random code string
105
+        for ($i = 0; $i < intval($arrOptions['length']); $i++) {
106
+            $code .= substr(strval($seed[mt_rand(0, count($seed) - 1)]),0,1);
107
+        }
108
+
109
+        // Add optional prefix
110
+        if ($arrOptions['prefix'])
111
+        {
112
+            $code = $arrOptions['prefix'].$code;
113
+        }
114
+
115
+        // Add optional suffix
116
+        if ($arrOptions['suffix'])
117
+        {
118
+            $code = $arrOptions['suffix'].$code;
119
+        }
120
+
121
+        return $code;
122
+    }
123
+
124
+}
0 125
new file mode 100644
... ...
@@ -0,0 +1,55 @@
1
+<?php
2
+
3
+declare(strict_types=1);
4
+
5
+/*
6
+ * This file is part of dacore bundle for Contao.
7
+ *
8
+ * (c) Benjamin Roth
9
+ *
10
+ * @license commercial
11
+ */
12
+
13
+namespace vossmedien\DacoreBundle\Model;
14
+
15
+use Contao\Model;
16
+use Contao\Model\Collection;
17
+
18
+/**
19
+ * Reads and writes image sizes
20
+ *
21
+ * @property string|integer      $id
22
+ * @property string|integer      $tstamp
23
+ * @property string              $title
24
+ * @property string              $modal_title
25
+ * @property string|integer      $delay
26
+ * @property string|boolean      $show_once
27
+ * @property string|integer      $start
28
+ * @property string|integer      $stop
29
+ *
30
+ * @method static VrApiUserCounterModel|null findById($id, array $opt=array())
31
+ * @method static VrApiUserCounterModel|null findByPk($id, array $opt=array())
32
+ * @method static VrApiUserCounterModel|null findOneBy($col, $val, array $opt=array())
33
+ * @method static VrApiUserCounterModel|null findOneByTstamp($val, array $opt=array())
34
+ * @method static VrApiUserCounterModel|null findOneByCreated($val, array $opt=array())
35
+ *
36
+ * @method static Collection|VrApiUserCounterModel[]|VrApiUserCounterModel|null findByTstamp($val, array $opt=array())
37
+ * @method static Collection|VrApiUserCounterModel[]|VrApiUserCounterModel|null findByCreated($val, array $opt=array())
38
+ * @method static Collection|VrApiUserCounterModel[]|VrApiUserCounterModel|null findMultipleByIds($val, array $opt=array())
39
+ * @method static Collection|VrApiUserCounterModel[]|VrApiUserCounterModel|null findBy($col, $val, array $opt=array())
40
+ * @method static Collection|VrApiUserCounterModel[]|VrApiUserCounterModel|null findAll(array $opt=array())
41
+ *
42
+ * @method static integer countById($id, array $opt=array())
43
+ * @method static integer countByTstamp($val, array $opt=array())
44
+ * @method static integer countByCreated($val, array $opt=array())
45
+ */
46
+class VrApiUserCounterModel extends Model
47
+{
48
+	/**
49
+	 * Table name
50
+	 * @var string
51
+	 */
52
+	protected static $strTable = 'tl_vr_api_user_counter';
53
+}
54
+
55
+class_alias(VrApiUserCounterModel::class, 'VrApiUserCounterModel');