/
LoginHelper.php
74 lines (58 loc) · 2.04 KB
/
LoginHelper.php
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
<?php
namespace App\Model\Helper;
use App\Model\Gateway\StudentGateway;
use App\Model\Entity\Student;
use App\Model\Helper\Helper;
class LoginHelper
{
protected $studentGateway;
public function __construct(StudentGateway $studentGateway) {
$this->studentGateway = $studentGateway;
}
public function isLoggedIn()
{
if (isset($_COOKIE['id'])) {
$student = $this->studentGateway->getStudentByСolumn('id', $_COOKIE['id']);
if (isset($_COOKIE['token'])) {
if ($student->getHash() == $_COOKIE['hash']) {
return $student;
}
}
}
return false;
}
public function createCookies(Student $student)
{
$expires = 60 * 60 * 24 * 30 * 12 * 3;
setcookie('id', $student->getId(), time() + $expires, '/', null, null, true);
setcookie('hash', $student->getHash(), time() + $expires, '/', null, null, true);
setcookie('token', Helper::generateToken(), time() + $expires, '/', null, null, true);
}
public function deleteCookies()
{
setcookie('id', null, time()-1, '/');
setcookie('hash', null, time()-1, '/');
setcookie('token', null, time()-1, '/');
}
public function isPasswordValid(Student $student, $password) {
if ($student->getHash() == $this->hashPassword($password, $student->getSalt())) {
return true;
}
return false;
}
public static function setPassword(Student $student, $password)
{
$student->setSalt($this->generateSalt());
$student->setHash($this->hashPassword($password, $student->getSalt()));
}
protected function generateSalt()
{
$salt = substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.*-^%$#@!?%&%_=+<>[]{}0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.*-^%$#@!?%&%_=+<>[]{}'), 0, 44);
return $salt;
}
protected function hashPassword($password, $salt)
{
$hash = md5($password . $salt);
return $hash;
}
}