Passed
Push — master ( bc3760...1cf7cf )
by Damien
06:39
created

AbstractUpsertController::actionGenerateOpenssl()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 34
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 19
dl 0
loc 34
rs 9.6333
c 0
b 0
f 0
cc 4
nc 6
nop 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: dsmrt
5
 * Date: 2/7/18
6
 * Time: 11:16 PM
7
 */
8
9
namespace flipbox\keychain\controllers;
10
11
use Craft;
12
use craft\web\Request;
13
use flipbox\keychain\controllers\cp\AbstractController;
14
use flipbox\keychain\controllers\cp\view\EditController;
15
use flipbox\keychain\KeyChain;
16
use flipbox\keychain\keypair\Byok;
17
use flipbox\keychain\keypair\OpenSSL;
18
use flipbox\keychain\records\KeyChainRecord;
19
20
abstract class AbstractUpsertController extends AbstractController
21
{
22
    /**
23
     * @return \yii\web\Response
24
     * @throws \yii\web\BadRequestHttpException
25
     */
26
    public function actionIndex()
27
    {
28
        $this->requireAdmin();
29
        $this->requirePostRequest();
30
31
        /** @var Request $request */
32
        $request = Craft::$app->request;
0 ignored issues
show
Documentation Bug introduced by
It seems like Craft::app->request can also be of type craft\console\Request. However, the property $request is declared as type craft\web\Request. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
33
        $id = $request->getBodyParam('identifier');
34
        if ($id) {
35
            /** @var KeyChainRecord $keypair */
36
            $keypair = KeyChainRecord::find()->where([
37
                'id' => $id,
38
            ])->one();
39
40
            if ($keypair->isEncrypted) {
41
                $keypair->getDecryptedKey();
42
            }
43
        } else {
44
            $keypair = (new Byok([
45
                'key'         => $request->getBodyParam('key'),
46
                'certificate' => $request->getBodyParam('certificate'),
47
                'description' => $request->getBodyParam('description'),
48
            ]))->create();
49
        }
50
51
        /**
52
         * Set is decrypted so we know that the key and cert value is raw.
53
         */
54
        $keypair->isDecrypted = true;
55
        Craft::configure($keypair, [
56
            'key'          => $request->getBodyParam('key'),
57
            'certificate'  => $request->getBodyParam('certificate'),
58
            'description'  => $request->getBodyParam('description'),
59
            'isEncrypted'  => $request->getBodyParam('isEncrypted'),
60
            'pluginHandle' => $request->getBodyParam('pluginHandle'),
61
        ]);
62
63
        /**
64
         * Make sure enabled as a value
65
         */
66
        if ($keypair->enabled === null) {
67
            $keypair->enabled = true;
68
        }
69
70
71
        if (KeyChain::getInstance()->getService()->save($keypair)) {
72
            Craft::$app->getSession()->setNotice(Craft::t('keychain', 'Key pair saved.'));
73
        } else {
74
            Craft::$app->getSession()->setError(Craft::t('keychain', 'Key pair didn\'t save.'));
75
            return $this->renderTemplate(
76
                EditController::TEMPLATE_INDEX,
77
                array_merge(
78
                    $this->getBaseVariables(),
79
                    [
80
                        'keypair' => $keypair,
81
                    ]
82
                )
83
            );
84
        }
85
86
        return $this->redirectToPostedUrl();
87
    }
88
89
    /**
90
     * @return \yii\web\Response
91
     * @throws \yii\web\BadRequestHttpException
92
     */
93
    public function actionOpenssl()
94
    {
95
        $this->requireAdmin();
96
        $this->requirePostRequest();
97
98
        /** @var Request $request */
99
        $request = Craft::$app->request;
0 ignored issues
show
Documentation Bug introduced by
It seems like Craft::app->request can also be of type craft\console\Request. However, the property $request is declared as type craft\web\Request. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
100
101
        $keychainRecord = (new OpenSSL([
102
            'description'            => $request->getBodyParam('description'),
103
            'countryName'            => $request->getBodyParam('countryName'),
104
            'stateOrProvinceName'    => $request->getBodyParam('stateOrProvinceName'),
105
            'localityName'           => $request->getBodyParam('localityName'),
106
            'organizationName'       => $request->getBodyParam('organizationName'),
107
            'organizationalUnitName' => $request->getBodyParam('organizationalUnitName'),
108
            'commonName'             => $request->getBodyParam('commonName'),
109
            'emailAddress'           => $request->getBodyParam('emailAddress'),
110
        ]))->create();
111
112
        Craft::configure($keychainRecord, [
113
            'enabled'      => $request->getBodyParam('enabled') ?: false,
114
            'isEncrypted'  => $request->getBodyParam('isEncrypted') ?: false,
115
            'pluginHandle' => $request->getBodyParam('plugin'),
116
        ]);
117
        $keychainRecord->isDecrypted = true;
118
119
        if (KeyChain::getInstance()->getService()->save($keychainRecord)) {
120
            Craft::$app->getSession()->setNotice(Craft::t('keychain', 'Key pair saved.'));
121
        } else {
122
            Craft::$app->getSession()->setError(Craft::t('keychain', 'Key pair didn\'t save.'));
123
            return $this->renderTemplate(
124
                EditController::TEMPLATE_INDEX,
125
                array_merge(
126
                    $this->getBaseVariables(),
127
                    [
128
                        'keypair' => $keychainRecord,
129
                    ]
130
                )
131
            );
132
        }
133
134
        return $this->redirectToPostedUrl();
135
    }
136
137
    /**
138
     * @return \yii\web\Response
139
     * @throws \yii\web\BadRequestHttpException
140
     * @throws \yii\web\ForbiddenHttpException
141
     */
142
    public function actionGenerateOpenssl()
143
    {
144
        $this->requireAdmin();
145
        $this->requirePostRequest();
146
        $config = [];
147
        if ($plugin = Craft::$app->request->getParam('plugin')) {
148
            $config = [
149
                'pluginHandle' => $plugin,
150
            ];
151
        }
152
153
        /** @var KeyChainRecord $keyPair */
154
        $keyPair = KeyChain::getInstance()->getService()->generateOpenssl($config);
155
156
        if (Craft::$app->request->isAjax) {
157
            return $this->asJson($keyPair->toArray());
158
        }
159
160
        if (! $keyPair->hasErrors()) {
161
            Craft::$app->getSession()->setNotice(Craft::t('keychain', 'Key pair saved.'));
162
        } else {
163
            Craft::$app->getSession()->setError(Craft::t('keychain', 'Key pair didn\'t save.'));
164
            return $this->renderTemplate(
165
                EditController::TEMPLATE_INDEX,
166
                array_merge(
167
                    $this->getBaseVariables(),
168
                    [
169
                        'keypair' => $keyPair,
170
                    ]
171
                )
172
            );
173
        }
174
175
        return $this->redirectToPostedUrl();
176
    }
177
178
179
    /**
180
     * @return \yii\web\Response
181
     * @throws \yii\web\BadRequestHttpException
182
     * @throws \yii\web\ForbiddenHttpException
183
     */
184
    public function actionChangeStatus()
185
    {
186
        $this->requireAdmin();
187
        $keypairId = Craft::$app->request->getRequiredBodyParam('identifier');
188
189
        $keychainRecord = KeyChainRecord::find()->where([
190
            'id' => $keypairId,
191
        ])->one();
192
193
        $keychainRecord->enabled = ! $keychainRecord->enabled;
194
195
        if (KeyChain::getInstance()->getService()->save($keychainRecord)) {
0 ignored issues
show
Bug introduced by
It seems like $keychainRecord can also be of type null and array; however, parameter $keyChainRecord of flipbox\keychain\services\KeyChainService::save() does only seem to accept flipbox\keychain\records\KeyChainRecord, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

195
        if (KeyChain::getInstance()->getService()->save(/** @scrutinizer ignore-type */ $keychainRecord)) {
Loading history...
196
            Craft::$app->getSession()->setNotice(Craft::t('keychain', 'Key pair saved.'));
197
        } else {
198
            Craft::$app->getSession()->setError(Craft::t('keychain', 'Key pair didn\'t save.'));
199
            return $this->renderTemplate(
200
                EditController::TEMPLATE_INDEX . '/openssl',
201
                array_merge(
202
                    $this->getBaseVariables(),
203
                    [
204
                        'keypair' => $keychainRecord,
205
                    ]
206
                )
207
            );
208
        }
209
210
        return $this->redirectToPostedUrl();
211
    }
212
213
    /**
214
     * @return \yii\web\Response
215
     * @throws \Throwable
216
     * @throws \yii\db\StaleObjectException
217
     * @throws \yii\web\BadRequestHttpException
218
     * @throws \yii\web\ForbiddenHttpException
219
     */
220
    public function actionDelete()
221
    {
222
        $this->requireAdmin();
223
        $keypairId = Craft::$app->request->getRequiredBodyParam('identifier');
224
225
        $keychainRecord = KeyChainRecord::find()->where([
226
            'id' => $keypairId,
227
        ])->one();
228
229
        if (false !== KeyChain::getInstance()->getService()->delete($keychainRecord)) {
0 ignored issues
show
Bug introduced by
It seems like $keychainRecord can also be of type null and array; however, parameter $keyChainRecord of flipbox\keychain\service...yChainService::delete() does only seem to accept flipbox\keychain\records\KeyChainRecord, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

229
        if (false !== KeyChain::getInstance()->getService()->delete(/** @scrutinizer ignore-type */ $keychainRecord)) {
Loading history...
230
            Craft::$app->getSession()->setNotice(Craft::t('keychain', 'Key pair deleted.'));
231
        } else {
232
            Craft::$app->getSession()->setError(Craft::t('keychain', 'Key pair didn\'t delete.'));
233
            return $this->renderTemplate(
234
                EditController::TEMPLATE_INDEX,
235
                array_merge(
236
                    $this->getBaseVariables(),
237
                    [
238
                        'keypair' => $keychainRecord,
239
                    ]
240
                )
241
            );
242
        }
243
244
        return $this->redirectToPostedUrl();
245
    }
246
}
247