FOSSology  3.2.0rc1
Open Source License Compliance by Open Source Software
AuthHelper.php
Go to the documentation of this file.
1 <?php
2 /***************************************************************
3  * Copyright (C) 2018 Siemens AG
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * version 2 as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License along
15  * with this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  ***************************************************************/
18 
27 namespace Fossology\UI\Api\Helper;
28 
34 
40 {
45  private $session;
50  private $userDao;
55  private $dbHelper;
56 
64  public function __construct(UserDao $userDao, Session $session,
65  DbHelper $dbhelper)
66  {
67  $this->userDao = $userDao;
68  $this->session = $session;
69  $this->dbHelper = $dbhelper;
70  if (!$this->session->isStarted()) {
71  $this->session->setName('Login');
72  $this->session->start();
73  }
74  }
75 
86  public function checkUsernameAndPassword($userName, $password)
87  {
88  $authPlugin = $GLOBALS["container"]->get("helper.restHelper")->getPlugin('auth');
89  return $authPlugin->checkUsernameAndPassword($userName, $password);
90  }
91 
101  public function verifyAuthToken($authHeader, &$userId, &$tokenScope)
102  {
103  $jwtTokenMatch = null;
104  $headerValid = preg_match(
105  "/^bearer (([a-zA-Z0-9\-\_\+\/\=]+)\.([a-zA-Z0-9\-\_\+\/\=]+)\.([a-zA-Z0-9\-\_\+\/\=]+))$/i",
106  $authHeader, $jwtTokenMatch);
107  $returnValue = true;
108  if (! $headerValid) {
109  $returnValue = new Info(400, "Authorization header is malformed or empty.",
110  InfoType::ERROR);
111  } else {
112  $jwtToken = $jwtTokenMatch[1];
113  $jwtTokenPayload = $jwtTokenMatch[3];
114  $jwtTokenPayloadDecoded = JWT::jsonDecode(
115  JWT::urlsafeB64Decode($jwtTokenPayload));
116 
117  if ($jwtTokenPayloadDecoded->{'jti'} === null) {
118  return new Info(403, "Invalid token sent.", InfoType::ERROR);
119  }
120  $jwtJti = $jwtTokenPayloadDecoded->{'jti'};
121  $jwtJti = base64_decode($jwtJti, true);
122  list ($tokenId, $userId) = explode(".", $jwtJti);
123 
124  $dbRows = $this->dbHelper->getTokenKey($tokenId);
125  $isTokenActive = $this->isTokenActive($dbRows, $tokenId);
126  if (empty($dbRows)) {
127  $returnValue = new Info(403, "Invalid token sent.", InfoType::ERROR);
128  } elseif ($isTokenActive !== true) {
129  $returnValue = $isTokenActive;
130  } else {
131  try {
132  $jwtTokenDecoded = JWT::decode($jwtToken, $dbRows["token_key"], ['HS256']);
133  $tokenScope = $jwtTokenDecoded->{'scope'};
134  } catch (\UnexpectedValueException $e) {
135  $returnValue = new Info(403, $e->getMessage(), InfoType::ERROR);
136  }
137  }
138  }
139  return $returnValue;
140  }
141 
148  private function isDateExpired($date)
149  {
150  return strtotime("today") > strtotime($date);
151  }
152 
161  public function isTokenActive($valuesFromDb, $tokenId)
162  {
163  $isPayloadValid = true;
164  if ($valuesFromDb['active'] == "f") {
165  $isPayloadValid = new Info(403, "Token expired.", InfoType::ERROR);
166  } elseif ($this->isDateExpired($valuesFromDb['expire_on']) &&
167  $valuesFromDb['active'] == "t") {
168  $this->dbHelper->invalidateToken($tokenId);
169  $isPayloadValid = new Info(403, "Token expired.", InfoType::ERROR);
170  }
171  return $isPayloadValid;
172  }
173 
178  public function getSession()
179  {
180  return $this->session;
181  }
182 
191  public function updateUserSession($userId, $scope, $groupName = null)
192  {
193  $authPlugin = $GLOBALS["container"]->get("helper.restHelper")->getPlugin('auth');
194  $user = $this->userDao->getUserByPk($userId);
195  $row = $this->userDao->getUserAndDefaultGroupByUserName($user["user_name"]);
196  if ($groupName !== null) {
197  $row['group_fk'] = $this->userDao->getGroupIdByName($groupName);
198  $row['group_name'] = $groupName;
199  }
200  $authPlugin->updateSession($row);
201  $this->getSession()->set('token_scope', $scope);
202  }
203 
214  public function generateJwtToken($expire, $created, $jti, $scope, $key)
215  {
216  $newJwtToken = [
217  "exp" => strtotime($expire . " +1 day -1 second"), // To allow day level granularity
218  "nbf" => strtotime($created),
219  "jti" => base64_encode($jti),
220  "scope" => $scope
221  ];
222  return JWT::encode($newJwtToken, $key, 'HS256');
223  }
224 
231  public function getMaxTokenValidity()
232  {
233  return $this->dbHelper->getMaxTokenValidity();
234  }
235 
244  public function userHasGroupAccess($userId, $groupName)
245  {
246  $isGroupExisting = $this->isGroupExisting($groupName);
247  if ($isGroupExisting === true) {
248  $groupMap = $this->userDao->getUserGroupMap($userId);
249  $userHasGroupAccess = in_array($groupName, $groupMap, true);
250  } else {
251  return $isGroupExisting;
252  }
253 
254  if (!$userHasGroupAccess) {
255  $userHasGroupAccess = new Info(403, "User has no access to " . $groupName . " group", InfoType::ERROR);
256  }
257  return $userHasGroupAccess;
258  }
259 
267  public function isGroupExisting($groupName)
268  {
269  if (! empty($this->userDao->getGroupIdByName($groupName))) {
270  return true;
271  } else {
272  return new Info(403, "Provided group:" . $groupName . " does not exist", InfoType::ERROR);
273  }
274  }
275 }
updateUserSession($userId, $scope, $groupName=null)
Update the session using updateSession().
Definition: AuthHelper.php:191
verifyAuthToken($authHeader, &$userId, &$tokenScope)
Definition: AuthHelper.php:101
isGroupExisting($groupName)
Verify if given Group name exists.
Definition: AuthHelper.php:267
generateJwtToken($expire, $created, $jti, $scope, $key)
Definition: AuthHelper.php:214
REST api helper classes.
Provides helper methods for REST api.
Definition: AuthHelper.php:39
__construct(UserDao $userDao, Session $session, DbHelper $dbhelper)
Definition: AuthHelper.php:64
userHasGroupAccess($userId, $groupName)
Verify if given User Id has access to given Group name.
Definition: AuthHelper.php:244
Info model to contain general error and return values.
Definition: Info.php:29
Provides helper methods to access database for REST api.
Definition: DbHelper.php:43
isTokenActive($valuesFromDb, $tokenId)
Definition: AuthHelper.php:161
checkUsernameAndPassword($userName, $password)
Check the username and password against the database.
Definition: AuthHelper.php:86