Completed
Push — master ( 226a49...bc28bf )
by Vitaly
04:42
created

Application::prepare()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 23
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 23
rs 9.0857
cc 2
eloc 13
nc 2
nop 0
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: nazarenko
5
 * Date: 20.10.2014
6
 * Time: 11:43
7
 */
8
namespace samsoncms\app\signin;
9
10
use samson\activerecord\dbQuery;
11
use samson\social\email\EmailStatus;
12
use samsonphp\event\Event;
13
use samsonframework\orm\QueryInterface;
14
use samson\social\email\Email;
15
16
/**
17
 * Generic class for user sign in
18
 * @author Olexandr Nazarenko <[email protected]>
19
 * @copyright 2014 SamsonOS
20
 */
21
class Application extends \samson\core\CompressableExternalModule
22
{
23
    /** @var string Identifier */
24
    public $id = 'cms-signin';
25
26
    /** @var Email Pointer to social email module */
27
    protected $social;
28
29
    /** @var QueryInterface Databvase query instance */
30
    protected $query;
31
32
    public function authorize($social)
33
    {
34
        if (m('cms')->isCMS()) {
35
            if ($social->id == 'socialemail') {
36
                if (!m('social')->authorized()) {
37
                    if (!m('socialemail')->cookieVerification()) {
38
                        if (!url()->is('cms-signin')) {
39
                            url()->redirect('/cms/signin');
40
                        }
41
                    } else {
42
                        url()->redirect('/cms/signin');
43
                    }
44
                } else {
45
                    if (url()->is('cms-signin')) {
46
                        url()->redirect('/cms');
47
                    }
48
                }
49
            }
50
        }
51
    }
52
53
    /**
54
     * Application constructor.
55
     *
56
     * @param string $path
57
     * @param null $vid
58
     * @param null $resources
59
     */
60
    public function  __construct($path, $vid = null, $resources = NULL )
0 ignored issues
show
Coding Style introduced by
Expected "function abc(...)"; found "function abc(...)"
Loading history...
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 2 found
Loading history...
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
Coding Style introduced by
Expected 0 spaces between argument "$resources" and closing bracket; 1 found
Loading history...
61
    {
62
        // Inject dependencies
63
        $this->social = m('socialemail');
0 ignored issues
show
Documentation Bug introduced by
It seems like m('socialemail') can also be of type object<samson\core\Module>. However, the property $social is declared as type object<samson\social\email\Email>. 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...
64
        $this->query = new dbQuery();
65
66
        parent::__construct($path, $vid, $resources);
67
    }
68
69
    //[PHPCOMPRESSOR(remove,start)]
70
    /** Module preparation */
71
    public function prepare()
72
    {
73
        // Create default user for first logins
74
        $adminUser = '[email protected]';
75
        $hashedEmailValue = $this->social->hash($adminUser);
76
77
        // Try to find generic user
78
        $admin = $this->query
79
            ->entity($this->social->dbTable)
80
            ->where($this->social->dbEmailField, $adminUser)
81
            ->first();
82
83
        // Create user record if missing
84
        if (!isset($admin)) {
85
             $admin = new $this->social->dbTable();
86
        }
87
88
        // Fill in user credentials according to config
89
        $admin[$this->social->dbEmailField] = $adminUser;
90
        $admin[$this->social->dbHashEmailField] = $hashedEmailValue;
91
        $admin[$this->social->dbHashPasswordField] = $hashedEmailValue;
92
        $admin->save();
93
    }
94
    //[PHPCOMPRESSOR(remove,end)]
95
96
    /** Check the user's authorization */
97
    public function __HANDLER()
98
    {
99
        $this->authorize($this->social);
100
    }
101
102
    /** Main sign in template */
103
    public function __base()
104
    {
105
        // Change template
106
        s()->template('www/signin/signin_template.vphp');
107
108
        // Render template with sign in form
109
        $this->html($this->view('www/signin/signin_form.vphp')->output())
110
            ->title(t('Авторизация', true));
111
    }
112
113
    /** User asynchronous sign in */
114
    public function __async_login()
0 ignored issues
show
Coding Style introduced by
Method name "Application::__async_login" is not in camel caps format
Loading history...
115
    {
116
        $user = null;
117
        $error = '';
118
119
        if (isset($_POST['email']) && isset($_POST['password'])) {
120
            $email = $this->social->hash($_POST['email']);
121
            $password = $this->social->hash($_POST['password']);
122
            $remember = isset($_POST['remember']) ? true : false;
123
124
            /** @var EmailStatus Perform email authorization */
125
            $auth = $this->social->authorizeWithEmail($email, $password, $remember, $user);
126
127
            if ($auth->code === EmailStatus::SUCCESS_EMAIL_AUTHORIZE) {
128
                // Fire login success event
129
                Event::fire('samson.cms.signin.login', array(&$user));
130
131
                return array('status' => '1');
132
            } else {
133
                $error .= $this->view('www/signin/signin_form.vphp')
134
                    ->errorClass('errorAuth')
135
                    ->userEmail("{$_POST['email']}")
136
                    ->focus('autofocus')
137
                    ->output();
138
139
                return array('status' => '0', 'html' => $error);
140
            }
141
        } else {
142
            $error .= $this->view('www/signin/signin_form')->errorClass('errorAuth')->output();
143
            return array('status' => '0', 'html' => $error);
144
        }
145
    }
146
147
    /** User logout */
148
    public function __logout()
149
    {
150
        $this->social->deauthorize();
151
152
        // Fire logout event
153
        Event::fire('samson.cms.signin.logout');
154
155
        url()->redirect('cms/signin');
156
    }
157
158
    /** Sending email with the correct address */
159
    public function __mail()
160
    {
161
        if (isset($_POST['email'])) {
162
            /** @var \samson\activerecord\user $user */
163
            $user = null;
164
            $result = '';
165
            if (dbQuery('user')->where('email', $_POST['email'])->first($user)) {
166
                $user->confirmed = $this->social->hash(generate_password(20) . time());
167
                $user->save();
168
                $message = $this->view('www/signin/email/pass_recovery')->code($user->confirmed)->output();
169
170
                mail_send($user->Email, '[email protected]', $message, t('Восстановление пароля!', true), 'SamsonCMS');
171
172
                $result .= $this->view('www/signin/pass_recovery_mailsend')->output();
173
                s()->template('www/signin/signin_template.vphp');
174
                $this->html($result)->title(t('Восстановление пароля', true));
175
            } else {
176
                url()->redirect();
177
            }
178
        } else {
179
            url()->redirect();
180
        }
181
    }
182
183
    /**
184
     * New password form.
185
     *
186
     * @param string $code Code password recovery
187
     */
188
    public function __confirm($code)
189
    {
190
        if (dbQuery('user')->where($this->social->dbConfirmField, $code)->first()) {
191
            $result = '';
192
            $result .= m()->view('www/signin/new_pass_form')->code($code)->output();
193
            s()->template('www/signin/signin_template.vphp');
194
            m()->html($result)->title(t('Восстановление пароля', true));
195
        } else {
196
            return A_FAILED;
197
        }
198
    }
199
200
    /**
201
     * Setting new password and sign in
202
     * @param string $code Code password recovery
203
     */
204
    public function __recovery($code)
205
    {
206
        if (isset($_POST['password']) && isset($_POST['confirm_password'])
207
            && $_POST['password'] == $_POST['confirm_password']
208
        ) {
209
            /** @var \samson\activerecord\user $user */
210
            $user = null;
211
            if (dbQuery('user')->confirmed($code)->first($user)) {
212
                $user->confirmed = 1;
213
                $user->md5_password = md5($_POST['password']);
214
                $user->Password = $_POST['password'];
215
                $user->save();
216
                if (m('socialemail')->authorizeWithEmail($user->md5_email, $user->md5_password, $user)
217
                        ->code == EmailStatus::SUCCESS_EMAIL_AUTHORIZE
218
                ) {
219
                    url()->redirect();
220
                }
221
            }
222
        } else {
223
            $result = '';
224
            $result .= m()->view('www/signin/pass_error')
225
                ->message(t('Вы ввели некорректный пароль либо пароли не совпадают', true))
226
                ->output();
227
            s()->template('www/signin/signin_template.vphp');
228
            m()->html($result)->title(t('Ошибка восстановление пароля', true));
229
        }
230
    }
231
}
232