Passed
Pull Request — develop (#27)
by Michiel
06:19
created

Tiqr_UserStorage_Pdo::getDisplayName()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 4
Bugs 0 Features 0
Metric Value
eloc 4
c 4
b 0
f 0
dl 0
loc 7
ccs 4
cts 5
cp 0.8
rs 10
cc 2
nc 2
nop 1
crap 2.032
1
<?php
2
/**
3
 * This file is part of the tiqr project.
4
 * 
5
 * The tiqr project aims to provide an open implementation for 
6
 * authentication using mobile devices. It was initiated by 
7
 * SURFnet and developed by Egeniq.
8
 *
9
 * More information: http://www.tiqr.org
10
 *
11
 * @author Patrick Honing <[email protected]>
12
 * 
13
 * @package tiqr
14
 *
15
 * @license New BSD License - See LICENSE file for details.
16
 *
17
 * @copyright (C) 2010-2012 SURFnet BV
18
 * 
19
 * Create SQL table (MySQL):
20
 * CREATE TABLE `tiqruser` (`userid` varchar(10) PRIMARY KEY, `displayname` varchar(45),`blocked` int,`loginattempts` int,
21
 * `tmpblockattempts` int,`tmpblocktimestamp` varchar(45) default NULL,`notificationtype` varchar(10),`notificationaddress` varchar(45))
22
 * 
23
 */
24
25
use Psr\Log\LoggerInterface;
26
27
28
/**
29
 * This user storage implementation implements a user storage using PDO.
30
 * It is usable for any database with a PDO driver
31
 * 
32
 * @author Patrick Honing <[email protected]>
33
 */
34
class Tiqr_UserStorage_Pdo extends Tiqr_UserStorage_Abstract
35
{
36
    protected $handle = null;
37
    protected $tablename;
38
    
39
    /**
40
     * Create an instance
41
     * @param array $config
42
     * @param array $secretconfig
43
     */
44 2
    public function __construct($config, LoggerInterface $logger, $secretconfig = array())
45
    {
46 2
        parent::__construct($config, $logger, $secretconfig);
47 2
        $this->tablename = isset($config['table']) ? $config['table'] : 'tiqruser';
48
        try {
49 2
            $this->handle = new PDO($config['dsn'],$config['username'],$config['password']);
50
        } catch (PDOException $e) {
51
            $this->logger->error(
52
                sprintf('Unable to establish a PDO connection. Error message from PDO: %s', $e->getMessage())
53
            );
54
        }
55 2
    }
56
57 2
    public function createUser($userId, $displayName)
58
    {
59 2
        if ($this->userExists($userId)) {
60
            $sth = $this->handle->prepare("UPDATE ".$this->tablename." SET displayname = ? WHERE userid = ?");
61
        } else {
62 2
            $sth = $this->handle->prepare("INSERT INTO ".$this->tablename." (displayname,userid) VALUES (?,?)");
63
        }
64 2
        if ($sth->execute(array($displayName,$userId))){
65 2
            return $this->userExists($userId);
66
        }
67
        $this->logger->error('The user could not be saved in the user storage (PDO)');
68
    }
69
70
    /**
71
     * Be carefull! This method does not return an expected boolean value. Instead it returns:
72
     * - void (if user was not found)
73
     * - userid (if user was found)
74
     *
75
     * @param $userId
76
     * @return mixed
77
     */
78 2
    public function userExists($userId)
79
    {
80 2
        $sth = $this->handle->prepare("SELECT userid FROM ".$this->tablename." WHERE userid = ?");
81 2
        if ($sth->execute(array($userId))) {
82 2
            return $sth->fetchColumn();
83
        }
84
        $this->logger->error('Unable fot find user in user storage (PDO)');
85
    }
86
    
87 2
    public function getDisplayName($userId)
88
    {
89 2
        $sth = $this->handle->prepare("SELECT displayname FROM ".$this->tablename." WHERE userid = ?");
90 2
        if ($sth->execute(array($userId))) {
91 2
            return $sth->fetchColumn();
92
        }
93
        $this->logger->error('Retrieving the users display name failed in the user storage (PDO)');
94
    }
95
96 2
    public function getNotificationType($userId)
97
    {
98 2
        $sth = $this->handle->prepare("SELECT notificationtype FROM ".$this->tablename." WHERE userid = ?");
99 2
        if ($sth->execute(array($userId))) {
100 2
            return $sth->fetchColumn();
101
        }
102
        $this->logger->error('Unable to retrieve notification type from user storage (PDO)');
103
    }
104
    
105 2
    public function setNotificationType($userId, $type)
106
    {
107 2
        $sth = $this->handle->prepare("UPDATE ".$this->tablename." SET notificationtype = ? WHERE userid = ?");
108 2
        if (!$sth->execute(array($type,$userId))) {
109
            $this->logger->error('Unable to set the notification type in user storage for a given user (PDO)');
110
        }
111 2
    }
112
    
113 2
    public function getNotificationAddress($userId)
114
    {
115 2
        $sth = $this->handle->prepare("SELECT notificationaddress FROM ".$this->tablename." WHERE userid = ?");
116 2
        if ($sth->execute(array($userId))) {
117 2
            return $sth->fetchColumn();
118
        }
119
        $this->logger->error('Unable to retrieve notification address from user storage (PDO)');
120
    }
121
    
122
    public function setNotificationAddress($userId, $address)
123
    {
124
        $sth = $this->handle->prepare("UPDATE ".$this->tablename." SET notificationaddress = ?  WHERE userid = ?");
125
        if (!$sth->execute(array($address,$userId))) {
126
            $this->logger->error('Unable to set the notification address in user storage for a given user (PDO)');
127
        }
128
    }
129
    
130 2
    public function getLoginAttempts($userId)
131
    {
132 2
        $sth = $this->handle->prepare("SELECT loginattempts FROM ".$this->tablename." WHERE userid = ?");
133 2
        if ($sth->execute(array($userId))) {
134 2
            return $sth->fetchColumn();
135
        }
136
        $this->logger->error('Unable to retrieve login attempts from user storage (PDO)');
137
    }
138
    
139 2
    public function setLoginAttempts($userId, $amount)
140
    {
141 2
        $sth = $this->handle->prepare("UPDATE ".$this->tablename." SET loginattempts = ? WHERE userid = ?");
142 2
        if (!$sth->execute(array($amount,$userId))) {
143
            $this->logger->error('Unable to set login attempts in user storage for a given user (PDO)');
144
        }
145 2
    }
146
    
147 2
    public function isBlocked($userId, $duration)
148
    {
149 2
        if ($this->userExists($userId)) {
150 2
            $sth = $this->handle->prepare("SELECT blocked FROM ".$this->tablename." WHERE userid = ?");
151 2
            $sth->execute(array($userId));
152 2
            $blocked = ($sth->fetchColumn() == 1);
153 2
            $timestamp = $this->getTemporaryBlockTimestamp($userId);
154
            // if not blocked or block is expired, return false
155 2
            if (!$blocked || (false !== $timestamp && false != $duration && (strtotime($timestamp) + $duration * 60) < time())) {
156 2
                return false;
157
            }
158 2
            return true;
159
        } else {
160
            return false;
161
        }
162
    }
163
    
164 2
    public function setBlocked($userId, $blocked)
165
    {
166 2
        $sth = $this->handle->prepare("UPDATE ".$this->tablename." SET blocked = ? WHERE userid = ?");
167 2
        $isBlocked = ($blocked) ? "1" : "0";
168 2
        if (!$sth->execute([$isBlocked, $userId])) {
169
            $this->logger->error('Unable to block the user in the user storage (PDO)');
170
        }
171 2
    }
172
    
173 2
    public function setTemporaryBlockAttempts($userId, $amount) {
174 2
        $sth = $this->handle->prepare("UPDATE ".$this->tablename." SET tmpblockattempts = ? WHERE userid = ?");
175 2
        if (!$sth->execute(array($amount,$userId))) {
176
            $this->logger->error('Unable to set temp login attempts in user storage for a given user (PDO)');
177
        }
178 2
    }
179
180
    /**
181
     * @param $userId
182
     * @return int
183
     * @throws RuntimeException when the query fails, a runtime exception is raised. As continuing execution from that
184
     *                          point would either throw an error, or return 0
185
     */
186 2
    public function getTemporaryBlockAttempts($userId) {
187 2
        if ($this->userExists($userId)) {
188 2
            $sth = $this->handle->prepare("SELECT tmpblockattempts FROM ".$this->tablename." WHERE userid = ?");
189 2
            if (!$sth->execute(array($userId))) {
190
                throw new RuntimeException('Unable to get temp login attempts in user storage for a given user (PDO)');
191
            }
192 2
            return (int) $sth->fetchColumn();
193
        }
194
        return 0;
195
    }
196
    
197 2
    public function setTemporaryBlockTimestamp($userId, $timestamp)
198
    {
199 2
        $sth = $this->handle->prepare("UPDATE ".$this->tablename." SET tmpblocktimestamp = ? WHERE userid = ?");
200 2
        if (!$sth->execute(array($timestamp,$userId))) {
201
            $this->logger->error('Unable to update temp lock timestamp in user storage for a given user (PDO)');
202
        }
203 2
    }
204
            
205 2
    public function getTemporaryBlockTimestamp($userId)
206
    {
207 2
        if ($this->userExists($userId)) {
208 2
            $sth = $this->handle->prepare("SELECT tmpblocktimestamp FROM ".$this->tablename." WHERE userid = ?");
209 2
            $sth->execute(array($userId));
210 2
            $timestamp = $sth->fetchColumn(); 
211 2
            if (null !== $timestamp) {
212 2
                return $timestamp;
213
            } else {
214 2
                $this->logger->info('No temp lock timestamp found in user storage for a given user (PDO)');
215
            }
216
        }
217 2
        return false;
218
    }
219
    
220
}
221