userCreate::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 4
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 7
rs 10
1
<?php
2
/**
3
 * ==================================
4
 * Responsible PHP API
5
 * ==================================
6
 *
7
 * @link Git https://github.com/vince-scarpa/responsibleAPI.git
8
 *
9
 * @api Responible API
10
 * @package responsible\core\user
11
 *
12
 * @author Vince scarpa <[email protected]>
13
 *
14
 */
15
namespace responsible\core\user;
16
17
use responsible\core\auth;
18
use responsible\core\exception;
19
use responsible\core\keys;
20
use responsible\core\route;
21
22
class userCreate extends user
23
{
24
    /**
25
     * [$keys]
26
     * @var object
27
     */
28
    private $keys;
29
30
    /**
31
     * [$jwt]
32
     * @var object
33
     */
34
    private $jwt;
35
36
    /**
37
     * [$credentials]
38
     * @var array
39
     */
40
    protected $credentials;
41
42
    /**
43
     * [$KEY Sectret key]
44
     * @var string
45
     */
46
    private $KEY = '';
47
48
    /**
49
     * @param $credentials
50
     */
51
    public function __construct($credentials)
52
    {
53
        $this->credentials = $credentials;
54
        $this->timeNow();
55
56
        $this->keys = new keys\key;
57
        $this->jwt = new auth\jwt;
58
    }
59
60
    /**
61
     * [create - Create a user account]
62
     * @return array
63
     */
64
    public function createAccount()
65
    {
66
        if (!isset($this->getDefaults()['config']['MASTER_KEY'])) {
67
            (new exception\errorException)
68
                ->message('There was an error trying to retrieve the server master key. Please read the documentation on setting up a configuration file')
69
                ->error('NO_CONTENT');
70
        }
71
72
        $this->KEY = $this->keys->secretGenerate();
73
74
        $this->accountExists();
75
        $this->setAccountID($this->keys->accountIdGenerate());
76
77
        $payload = $this->createPayload();
78
79
        $encoded = $this->jwt
80
            ->key($this->getDefaults()['config']['MASTER_KEY'])
81
            ->setPayload($payload)
82
            ->encode($payload)
83
        ;
84
85
        if ($encoded) {
86
            return [
87
                'ACCOUNT' => $this->accountInsert(),
88
                'JWT' => $encoded,
89
                'SECRET' => $this->KEY,
90
            ];
91
        }
92
    }
93
94
    /**
95
     * [createPayload Create a new payload for the new account]
96
     * @return array
97
     */
98
    private function createPayload()
99
    {
100
        /**
101
         * [$payload Set the default payload]
102
         * @var array
103
         */
104
        $payload = [
105
            'iss' => (new route\router)->getIssuer(),
106
            'sub' => $this->getAccountID(),
107
            'iat' => $this->timeNow(),
108
            'nbf' => $this->timeNow(),
109
            'exp' => $this->timeNow() + $this->jwt->getExpires(),
110
        ];
111
112
        /**
113
         * [$jwtOptions JWT options may be set as Responsible option overrides]
114
         * @var array
115
         */
116
        if (false !== ($jwtOptions = $this->checkVal($this->options, 'jwt'))) {
117
            if (false !== ($exp = $this->checkVal($jwtOptions, 'expires'))) {
118
                $payload['exp'] = $exp;
119
            }
120
            if (false !== ($iat = $this->checkVal($jwtOptions, 'issuedAt'))) {
121
                $payload['iat'] = $iat;
122
            }
123
            if (false !== ($nbf = $this->checkVal($jwtOptions, 'notBeFor'))) {
124
                $payload['nbf'] = $nbf;
125
            }
126
        }
127
128
        return $payload;
129
    }
130
131
    /**
132
     * [accountExists description]
133
     * @return object
134
     */
135
    private function accountExists()
136
    {
137
        $account = $this->DB()
138
            ->row("
139
                SELECT uid
140
                FROM responsible_api_users
141
                WHERE
142
                    name = :name
143
                OR
144
                    mail = :mail
145
            ;",
146
                array(
147
                    'name' => $this->credentials['name'],
148
                    'mail' => $this->credentials['mail'],
149
                ),
150
                \PDO::FETCH_OBJ
151
            );
152
153
        if ($account) {
154
            (new exception\errorException)
155
                ->message('The email or username supplied already exists!')
156
                ->error('NO_CONTENT');
157
        }
158
159
        return $account;
160
    }
161
162
    /**
163
     * [accountInsert]
164
     * @return array
165
     */
166
    private function accountInsert()
167
    {
168
        $newAccount = $this->DB()
169
            ->query(
170
                "INSERT INTO responsible_api_users
171
                    (`uid`, `account_id`, `name`, `mail`, `created`, `access`, `status`, `secret`)
172
                VALUES
173
                    (NULL, :accntid, :name, :mail, :tmestmp, :access, '1', :secret)
174
            ;",
175
                array(
176
                    'accntid' => $this->getAccountID(),
177
                    'name' => $this->credentials['name'],
178
                    'mail' => $this->credentials['mail'],
179
                    'tmestmp' => $this->timeNow(),
180
                    'access' => $this->timeNow(),
181
                    'secret' => $this->KEY,
182
                )
183
            );
184
185
        $newTokenBucket = $this->DB()
186
            ->query(
187
                "INSERT INTO responsible_token_bucket
188
                    (`id`, `bucket`, `account_id`)
189
                VALUES
190
                    (NULL, '', :accntid)
191
                ;",
192
                array(
193
                    'accntid' => $this->getAccountID(),
194
                )
195
            );
196
197
        if ($newAccount && $newTokenBucket) {
198
            return $this->load($this->credentials['mail'], array('loadBy' => 'mail'));
199
        }
200
201
        (new exception\errorException)
202
            ->message('There was an error trying to create a new account! "accountInsert()" failed')
203
            ->error('ACCOUNT_ID');
204
    }
205
206
    /**
207
     * [setOptions Set the Responsible API options]
208
     * @param array $options
209
     */
210
    public function setOptions($options)
211
    {
212
        $this->options = $options;
213
        return $this;
214
    }
215
}
216