Login script voor de scriptlib

Overzicht Reageren

Sponsored by: Vacatures door Monsterboard

SilverWolf NL

SilverWolf NL

06/01/2011 22:10:53
Quote Anchor link
Ik wil graag weten of dit goed genoeg zou zijn voor in de scriptlib. Het bestaat uit wat scripts die ik nog had liggen bij elkaar gestopt. Natuurlijk moeten er nog voorbeelden bij etc. maar ik zou graag wat commentaar hebben van jullie voordat ik het erop zet. Verder zijn er inderdaad dingen die misschien nu niet van pas komen (zoals de 'DBAL' als je het al zo kan noemen), maar dat komt dus omdat ik het uit een bestaand systeem gehaald heb.

Dat doet me eraan denken dat ik nog even de regexen moet checken, of die goed werken... Doe ik morgen wel, nu geen tijd meer ;)

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
<?PHP
if ( ! session_id () )
    session_start ();
session_regenerate_id ();

class DatabaseHandler
{

    private $_socket;

    private $_result;

    public $num_rows;

    public $affected_rows;

    public $insert_id;

    public function __construct ( $host, $user, $pass, $db )
    {

        $this->_socket = new MySQLi ( $host, $user, $pass, $db );
        if ( mysqli_connect_error () )
        {

            throw new DatabaseException ( 'MySQL connection error [' . $this->_socket->connect_errno . ']: "' . $this->_socket->connect_error . '"' );
        }
    }


    public function runQuery ( $query )
    {

        $this->_result = $this->_socket->query ( $query );
        if ( $this->_socket->error != '' )
        {

            throw new DatabaseException ( 'MySQL connection error [' . $this->_socket->errno . ']: "' . $this->_socket->error . '"' );
            return false;
        }

        else
        {
            if ( ! is_bool ( $this->_result ) )
                $this->num_rows = $this->_result->num_rows;
            $this->affected_rows = $this->_socket->affected_rows;
            $this->insert_id = $this->_socket->insert_id;
            return true;
        }
    }


    public function fetch_assoc ()
    {

        if ( ! ( $this->_result instanceof MySQLi_Result ) )
        {

            throw new DatabaseException ( 'Not a valid result in DatbaseHandler::$result' );
        }

        else
        {
            $this->_result->data_seek ( 0 );
            return $this->_result->fetch_all ( MYSQLI_ASSOC );
        }
    }


    public function fetch_single_assoc ( $row = 0 )
    {

        if ( $row != 0 )
            $this->_result->data_seek ( $row );
        return $this->_result->fetch_assoc ();
    }


    public function real_escape_string ( $data )
    {

        return $this->_socket->real_escape_string ( $data );
    }


    public function real_escape_array ( $data )
    {

        foreach ( $data as &$string )
            $string = $this->_socket->real_escape_string ( $string );
        return $data;
    }


    public function getError ()
    {

        return $this->_socket->error;
    }
}


class DatabaseException extends Exception
{}

class Logger
{

    private static $_instance;

    private $_file = 'php/errors.log';

    private $_fp;

    private function __construct ()
    {

        $this->_fp = fopen ( $this->_file, 'a' );
    }


    public static function getInstance ()
    {

        if ( ! isset ( self::$_instance ) )
            self::$_instance = new self ();
        return self::$_instance;
    }


    private function _write ( $str )
    {

        return fwrite ( $this->_fp, $str );
    }


    public function addException ( Exception $e )
    {

        $data = 'Errormessage: ' . $e->getMessage () . ', in: ' . $e->getFile () . ' on line: ' . $e->getLine () . PHP_EOL . 'Stack trace:' . PHP_EOL . $e->getTrace () . PHP_EOL . PHP_EOL . PHP_EOL;
        return $this->_write ( $data );
    }


    public function addString ( $string )
    {

        return $this->_write ( $string . PHP_EOL . PHP_EOL . PHP_EOL );
    }
}


class User
{

    protected $_fingerprint;

    protected $_ip;

    protected $_id;

    protected $_auth_level;

    protected $_email;

    protected $_db;

    public function __construct ( $id, $auth_level, $email )
    {

        $this->_id = intval ( $id );
        $this->_auth_level = intval ( $auth_level );
        $this->_email = $email;
        $this->_fingerprint = md5 ( $_SERVER["HTTP_USER_AGENT"] . $_SERVER["REMOTE_ADDR"] . $_SERVER["REMOTE_PORT"] );
    }


    public function setDatabaseHandler ( DatabaseHandler $db )
    {

        $this->_db = $db;
    }


    public function validate ()
    {

        if ( $this->_fingerprint != md5 ( $_SERVER["HTTP_USER_AGENT"] . $_SERVER["REMOTE_ADDR"] . $_SERVER["REMOTE_PORT"] ) )
        {

            $this->_id = 0;
            $this->_auth_level = 0;
            return false;
        }

        else
        {
            return true;
        }
    }


    public function register ( $username, $pass1, $pass2, $email, $auth_level )
    {

        if ( ! ( $this->_db instanceof DatabaseHandler ) )
        {

            throw new Exception ( 'No database given to User-object' );
        }

        else
        {
            $username = $this->_db->real_escape_string ( $username );
            $email = $this->_db->real_escape_string ( $email );
            $auth_level = intval ( $auth_level );
            if ( ! preg_match ( '/^[a-zA-Z][a-zA-Z\_\.\-]{2,}$/is', $username ) )
            {

                return - 1;
            }

            elseif ( $pass1 !== $pass2 )
            {

                return - 2;
            }

            elseif ( ! preg_match ( '/^[^@]@[^@].[a-zA-Z.]{2,5}$/is', $email ) )
            {

                return - 3;
            }

            else
            {
                if ( ! $this->_db->runQuery ( "SELECT id FROM users WHERE username='" . $username . "'" ) )
                {

                    throw new Exception ( 'Couldn\'t get the userdata for username validation' );
                }

                elseif ( $this->_db->num_rows == 1 )
                {

                    return - 4;
                }

                else
                {
                    $password = sha1 ( $password );
                    if ( $this->_db->runQuery ( "INSERT INTO users(username,password,email,authlevel) VALUES('" . $username . "','" . $password . "','" . $email . "'," . $auth_level . ")" ) )
                    {

                        $this->_id = $this->_db->insert_id;
                        $this->_email = $email;
                        $this->_auth_level = $auth_level;
                        Authentication::getInstance ()->setCurrentUser ( $this );
                        return true;
                    }

                    else
                    {
                        return false;
                    }
                }
            }
        }
    }


    public function updateEmail ( $email )
    {

        if ( ! ( $this->_db instanceof DatabaseHandler ) )
        {

            throw new Exception ( 'No database given to User-object' );
        }

        else
        {
            $email = $this->_db->real_escape_array ( $email );
            if ( ! preg_match ( '/^[^@]@[^@].[a-zA-Z\.]{2,3}$/is' ) )
            {

                return - 1;
            }

            else
            {
                if ( ! $this->_db->runQuery ( "UPDATE users SET email='" . $_POST['email'] . "' WHERE id=" . $this->_id ) )
                {

                    throw new Exception ( 'Couldn\'t update the userdata' );
                }

                else
                {
                    if ( $this->_db->affected_rows == 1 )
                    {

                        $this->_email = $email;
                        Authentication::getInstance ()->setCurrentUser ( $this );
                        return true;
                    }

                    else
                    {
                        return false;
                    }
                }
            }
        }
    }


    public function updatePass ( $pass1, $pass2 )
    {

        if ( ! ( $this->_db instanceof DatabaseHandler ) )
        {

            throw new Exception ( 'No database given to User-object' );
        }

        else
        {
            if ( $pass1 !== $pass2 )
            {

                return - 1;
            }

            else
            {
                $password = sha1 ( $pass1 );
                if ( ! $this->_db->runQuery ( "UPDATE users SET password='" . $password . "' WHERE id=" . $this->_id ) )
                {

                    throw new Exception ( 'Couldn\'t update the userdata' );
                }

                else
                {
                    return $this->_db->affected_rows;
                }
            }
        }
    }


    public function updateAuthLevel ( $auth_level, $id )
    {

        if ( ! ( $this->_db instanceof DatabaseHandler ) )
        {

            throw new Exception ( 'No database given to User-object' );
        }

        else
        {
            $id = intval ( $id );
            $auth_level = intval ( $auth_level );
            if ( ! $this->_db->runQuery ( "UPDATE users SET authlevel='" . $auth_level . "' WHERE id=" . $id ) )
            {

                throw new Exception ( 'Couldn\'t update the userdata' );
            }

            else
            {
                if ( $id == $this->_id )
                {

                    if ( $this->_db->affected_rows == 1 )
                    {

                        $this->_auth_level = $auth_level;
                        Authentication::getInstance ()->setCurrentUser ( $this );
                        return true;
                    }

                    else
                    {
                        return false;
                    }
                }

                else
                {
                    return $this->_db->affected_rows;
                }
            }
        }
    }


    public function getAuthLevel ()
    {

        return $this->_auth_level;
    }


    public function getID ()
    {

        return $this->_id;
    }


    public function unsetDatabaseHandler ()
    {

        $this->_db = null;
    }
}


class Authentication
{

    private static $_instance;

    private $_db;

    private $_user;

    public static function getInstance ()
    {

        if ( empty ( self::$_instance ) )
            self::$_instance = new self ();
        return self::$_instance;
    }


    private function __construct ()
    {

        $this->_loadUserData ();
    }


    public function setDatabaseHandler ( DatabaseHandler $db )
    {

        $this->_db = $db;
    }


    public function login ( $username, $password )
    {

        if ( ! ( $this->_db instanceof DatabaseHandler ) )
        {

            throw new Exception ( 'No database given to Authentication-object' );
        }

        else
        {
            $username = $this->_db->real_escape_string ( $username );
            $password = sha1 ( $password );
            if ( $this->_db->runQuery ( "SELECT id, authlevel, email FROM users WHERE username='" . $username . " AND password='" . $password . "'" ) )
            {

                if ( $this->_db->num_rows == 1 )
                {

                    $data = $this->_db->fetch_single_assoc ();
                    $this->_user = new User ( $data['id'], $data['auth_level'], $data['email'] );
                    $this->_saveUserData ();
                    return true;
                }

                else
                {
                    return false;
                }
            }

            else
            {
                throw new Exception ( 'Couldn\'t get data from Users in Authentication::login()' );
            }
        }
    }


    public function logout ()
    {

        $this->_removeUserData ();
    }


    public function setCurrentUser ( User $user )
    {

        $this->_user = $user;
        $this->_user->unsetDatabaseHandler ();
        $this->_saveUserData ();
    }


    public function getCurrentUser ()
    {

        return $this->_user;
    }


    private function _saveUserData ()
    {

        $_SESSION['userdata'] = serialize ( $this->_user );
    }


    private function _loadUserData ()
    {

        if ( ! empty ( $_SESSION['userdata'] ) )
        {

            $user = unserialize ( (string) $_SESSION['userdata'] );
            if ( ! $user->validate () )
            {

                $this->_user = new User ( 0, 0 );
            }
        }

        $this->_user = $user;
    }


    private function _removeUserData ()
    {

        $_SESSION['userdata'] = serialize ( new User ( 0, 0 ) );
    }
}

?>
Gewijzigd op 07/01/2011 12:04:49 door SilverWolf NL
 
PHP hulp

PHP hulp

01/10/2022 12:45:10
 
Pim -

Pim -

06/01/2011 22:28:18
Quote Anchor link
Ik zou bij DatabaseHandler::__construct() of de inloggegegevens, of het MySQLi object meegeven ipv daar constanten voor te gebruiken.

Bij fetch_assoc() kan je mysqli_result::fetch_all() gebruiken.

Bij fetch_single_assoc() kan je het volgende doen:
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
<?php
if($row != 0) $this->result->data_seek ( $row );
?>


Wees consistent met de underscore prefix bij private/protected vars.

Maak Logger::__construct($fileName).

Waarom een UserException? Gebruik exception waar je wat aan hebt...

Scheid User en UserHandler in
- User (een gewone gebruiker, dus email hierin, ook registratie)
- Authenication (login, authorisatie, getCurrentUser() )
- Evt kan je nog een aparte Authorization class maken (die beheert wat gebruikers wel en niet mogen)

Verder netjes
 
SilverWolf NL

SilverWolf NL

07/01/2011 12:06:35
Quote Anchor link
Ik heb even een paar updates gedaan, maar zit nu op school. Ga die Authorization-class nog maken, maar ik moet even kijken wanneer ik nog tijd heb. Wat Pim voor de rest heeft gezegd heb ik al aangepast, iemand anders nog opmerkingen?

PS: omdat ik niet weer 300+ regels code ga plaatsen, heb ik de beginpost aangepast; zie die dus voor wat het nu is.
 



Overzicht Reageren

 
 

Om de gebruiksvriendelijkheid van onze website en diensten te optimaliseren maken wij gebruik van cookies. Deze cookies gebruiken wij voor functionaliteiten, analytische gegevens en marketing doeleinden. U vindt meer informatie in onze privacy statement.