Changeset 1446
- Timestamp:
- 02/11/10 17:34:27 (3 years ago)
- Location:
- branches/newtoken
- Files:
-
- 2 added
- 26 modified
-
CHANGELOG (modified) (1 diff)
-
wifidog/admin/generic_object_admin.php (modified) (5 diffs)
-
wifidog/admin/user_gen.php (added)
-
wifidog/auth/index.php (modified) (2 diffs)
-
wifidog/classes/AbstractDb.php (modified) (1 diff)
-
wifidog/classes/Authenticator.php (modified) (1 diff)
-
wifidog/classes/Connection.php (added)
-
wifidog/classes/ContentTypeFilter.php (modified) (1 diff)
-
wifidog/classes/HotspotGraph.php (modified) (1 diff)
-
wifidog/classes/HotspotGraphElement.php (modified) (2 diffs)
-
wifidog/classes/Mail.php (modified) (1 diff)
-
wifidog/classes/MainUI.php (modified) (1 diff)
-
wifidog/classes/Network.php (modified) (7 diffs)
-
wifidog/classes/Node.php (modified) (4 diffs)
-
wifidog/classes/NodeGroup.php (modified) (2 diffs)
-
wifidog/classes/Role.php (modified) (1 diff)
-
wifidog/classes/SmartyWifidog.php (modified) (1 diff)
-
wifidog/classes/Token.php (modified) (4 diffs)
-
wifidog/classes/TokenTemplate.php (modified) (13 diffs)
-
wifidog/classes/User.php (modified) (3 diffs)
-
wifidog/include/common.php (modified) (1 diff)
-
wifidog/include/schema_validate.php (modified) (2 diffs)
-
wifidog/login/index.php (modified) (5 diffs)
-
wifidog/signup.php (modified) (1 diff)
-
wifidog/templates/classes/MainUI_ToolContent.tpl (modified) (1 diff)
-
wifidog/ws/classes/Exceptions/WSException.php (modified) (1 diff)
-
wifidog/ws/classes/WifidogWS/V1.php (modified) (18 diffs)
-
wifidog/ws/index.php (modified) (2 diffs)
Legend:
- Unmodified
- Added
- Removed
-
branches/newtoken/CHANGELOG
r1436 r1446 1 1 # $Id$ 2 2 3 2009-12-17 3 2010-01-28 Geneviève Bastien <gbastien@versatic.net> 4 * Modification to the web service to include authentication 5 * Added function generateConnectionTokenNoSession in User.php for the web service to generate tokens 6 * Fixed #691, content for login page, introduced in [1435] 7 8 2010-01-21 Geneviève Bastien <gbastien@versatic.net> 9 * Permission error when deleting user role (#689) 10 * Patch by Steven Kurylo to remove white spaces from authenticator arguments (#612) 11 * Search for stakeholders has now same case-sensitivity as the user's network (#662) 12 * Corrected (#613) patch by Hélène Gauthier 13 14 2009-12-17 Geneviève Bastien <gbastien@versatic.net> 4 15 * Code refactoring: Network, NodeGroup, Node inherit from HotspotGraphElement (#677) 5 16 6 2009-12-08 17 2009-12-08 Geneviève Bastien <gbastien@versatic.net> 7 18 * Added the concept of node group and hierarchy (in a not too clean way to start with, I will refactor the code before adding new functionalities to nodes and groups) (#246) 8 19 * Login and signup and logout script now receive the mac address as parameter (#675) -
branches/newtoken/wifidog/admin/generic_object_admin.php
r1424 r1446 74 74 $supportsPreview = true; 75 75 $supportsDeletion = true; 76 $readOnly = false; 76 77 /* 77 78 * Check for the object class to use … … 357 358 case "ContentTypeFilter" : 358 359 case "ProfileTemplate" : 360 case "Connection": 361 case "TokenTemplate": 359 362 $supportsPreview = false; 360 363 break; … … 367 370 switch ($_REQUEST['object_class']) { 368 371 case "User" : 372 case "Connection": 369 373 $supportsDeletion = false; 370 374 break; … … 379 383 break; 380 384 } 385 386 // Process deletion abilities 387 switch ($_REQUEST['object_class']) { 388 case "Connection": 389 $readOnly = true; 390 break; 391 392 default : 393 break; 394 } 395 381 396 382 397 if (!$object) { … … 396 411 $html .= $object->getAdminUI(); 397 412 $html .= "<div class='generic_object_admin_edit'>"; 398 $html .= "<input type='hidden' name='action' value='save'>"; 399 $html .= "<input type='submit' class='submit' name='save_submit' value='" . _("Save") . " " . get_class($object) . "'>"; 413 if (!$readOnly) { 414 $html .= "<input type='hidden' name='action' value='save'>"; 415 $html .= "<input type='submit' class='submit' name='save_submit' value='" . _("Save") . " " . get_class($object) . "'>"; 416 } 400 417 401 418 if ($supportsDeletion) { -
branches/newtoken/wifidog/auth/index.php
r1419 r1446 52 52 require_once('classes/Network.php'); 53 53 require_once('classes/User.php'); 54 require_once('classes/Connection.php'); 54 55 $db = AbstractDb::getObject(); 55 56 $auth_response = ACCOUNT_STATUS_DENIED; … … 60 61 { 61 62 $token = $db->escapeString($_REQUEST['token']); 62 $dbRetval = $db->execSqlUniqueRes("SELECT CURRENT_TIMESTAMP, *, CASE WHEN ((CURRENT_TIMESTAMP - reg_date) > networks.validation_grace_time) THEN true ELSE false END AS validation_grace_time_expired FROM connections JOIN tokens USING (token_id) JOIN users ON (users.user_id=connections.user_id) JOIN networks ON (users.account_origin = networks.network_id) WHERE connections.token_id='$token'", $info, false); 63 try { 64 $connection = Connection::getObject($token); 65 $info = $connection->getRow(); 66 } catch (Exception $e) { 67 $auth_message .= "| Error: couldn't retrieve the requested token: $token because of a SQL error. "; 68 $auth_response = ACCOUNT_STATUS_ERROR; 69 } 70 /* $dbRetval = $db->execSqlUniqueRes("SELECT CURRENT_TIMESTAMP, *, CASE WHEN ((CURRENT_TIMESTAMP - reg_date) > networks.validation_grace_time) THEN true ELSE false END AS validation_grace_time_expired 71 FROM connections 72 JOIN tokens USING (token_id) 73 JOIN users ON (users.user_id=connections.user_id) 74 JOIN networks ON (users.account_origin = networks.network_id) 75 WHERE connections.token_id='$token' ORDER BY conn_id DESC LIMIT 1", $info, false); 76 63 77 if($dbRetval==false){ 64 78 $auth_message .= "| Error: couldn't retrieve the requested token: $token because of a SQL error. "; 65 79 $auth_response = ACCOUNT_STATUS_ERROR; 66 } 80 }*/ 67 81 } 68 82 else { -
branches/newtoken/wifidog/classes/AbstractDb.php
r1445 r1446 357 357 { 358 358 // WARNING : magic quotes must be off 359 if (is_null($string))360 return "null";361 359 return pg_escape_string($string); 362 360 } -
branches/newtoken/wifidog/classes/Authenticator.php
r1445 r1446 358 358 // Stop traffic counters update 359 359 $conn_id = $db->escapeString($conn_id); 360 $sql = "UPDATE connections SET timestamp_out=CURRENT_TIMESTAMP WHERE conn_id='{$conn_id}';\n";360 $sql = "UPDATE connections SET timestamp_out=CURRENT_TIMESTAMP, logout_reason=" . LOGOUT_REASON_USER_LOGOUT . " WHERE conn_id='{$conn_id}';\n"; 361 361 $sql .= "UPDATE tokens SET token_status='".TOKEN_USED."' FROM connections WHERE connections.token_id=tokens.token_id AND conn_id='{$conn_id}';\n"; 362 362 -
branches/newtoken/wifidog/classes/ContentTypeFilter.php
r1421 r1446 288 288 289 289 !empty($userData['preSelectedId'])?$selectedId=$userData['preSelectedId']:$selectedId=null; 290 !empty($userData['additionalWhere'])?$additional_where=$userData['additionalWhere']:$additional_where= null;290 !empty($userData['additionalWhere'])?$additional_where=$userData['additionalWhere']:$additional_where=''; 291 291 292 292 $additional_where = $db->escapeString($additional_where); -
branches/newtoken/wifidog/classes/HotspotGraph.php
r1436 r1446 56 56 { 57 57 58 /** 59 * Adds a relation to the hotspot graph 60 * @param parentId the id of the parent 61 * @param childId the id of the child 62 */ 63 public static function addRelation($parentId, $childId) { 64 $db = AbstractDb :: getObject(); 65 $parentIdStr = $db->escapeString($parentId); 66 $childIdStr = $db->escapeString($childId); 67 $sql = "INSERT INTO hotspot_graph (child_element_id, parent_element_id) VALUES ('{$childIdStr}', '{$parentIdStr}');"; 68 $db->execSqlUpdate($sql, false); 69 } 70 58 71 /** 59 72 * Gets recursively all parents of the given object -
branches/newtoken/wifidog/classes/HotspotGraphElement.php
r1436 r1446 116 116 * @access public 117 117 */ 118 public static function createNewObject($element_id, $element_type )118 public static function createNewObject($element_id, $element_type, $parent_element = null) 119 119 { 120 120 $db = AbstractDb::getObject(); … … 130 130 } 131 131 $object = self::getObject($element_id, $element_type); 132 133 if (!is_null($parent_element)) { 134 if (method_exists($parent_element, 'getHgeId')) { 135 $parentid = $parent_element->getHgeId(); 136 $childid = $object->getHgeId(); 137 HotspotGraph::addRelation($parentid, $childid); 138 } 139 } 140 132 141 return $object; 133 142 } -
branches/newtoken/wifidog/classes/Mail.php
r1424 r1446 368 368 */ 369 369 public function send() { 370 $phpmailerPath = 'lib/PHPMailer_v2.0.0/'; 370 $dir = new DirectoryIterator('lib'); 371 foreach ($dir as $fileinfo) { 372 if ($fileinfo->isDir() && (substr($fileinfo->getFilename(), 0, 9) == 'PHPMailer')) { 373 $phpmailerPath = 'lib/' . $fileinfo->getFilename() . '/'; 374 } 375 } 371 376 require_once ($phpmailerPath.'class.phpmailer.php'); 372 377 require_once ($phpmailerPath.'class.smtp.php'); -
branches/newtoken/wifidog/classes/MainUI.php
r1435 r1446 329 329 // Get all network content and node "everywhere" content 330 330 $content_rows = null; 331 $network_id = $db->escapeString(Network :: getCurrentNetwork()->getId());332 $sql_network = "(SELECT content_id, display_area, display_order, subscribe_timestamp FROM network_has_content WHERE network_id='$network_id' AND display_page='everywhere') ";333 331 $node = Node :: getCurrentNode(); 334 $sql_node = null;332 // Get all the parent objects of the node 335 333 if ($node) { 336 // Get all node content 337 $node_id = $db->escapeString($node->getId()); 338 $sql_node = "UNION (SELECT content_id, display_area, display_order, subscribe_timestamp FROM node_has_content WHERE node_id='$node_id' AND display_page='everywhere')"; 339 } 340 $sql = "SELECT * FROM ($sql_network $sql_node) AS content_everywhere ORDER BY display_area, display_order, subscribe_timestamp DESC"; 341 334 $parents = HotspotGraph::getAllParents($node); 335 } else { 336 $parents = array(Network :: getCurrentNetwork()->getHgeId()); 337 } 338 339 $first = $db->escapeString(array_shift($parents)); 340 $sql_from = "(SELECT content_id, display_area, display_order, subscribe_timestamp 341 FROM hotspot_graph_element_has_content hgehc 342 WHERE hotspot_graph_element_id='$first' AND display_page='everywhere')"; 343 344 // Get the contents for all elements parents of and including the node, but exclude user subscribed content if user is known 345 foreach($parents as $parentid) { 346 $parent_id = $db->escapeString($parentid); 347 $sql_from .= " UNION (SELECT content_id, display_area, display_order, subscribe_timestamp 348 FROM hotspot_graph_element_has_content hgehc 349 WHERE hotspot_graph_element_id='$parent_id' AND display_page='everywhere')"; 350 } 351 $sql = "SELECT * FROM ($sql_from) AS content_everywhere ORDER BY display_area, display_order, subscribe_timestamp DESC"; 342 352 $db->execSql($sql, $content_rows, false); 343 353 if ($content_rows) { -
branches/newtoken/wifidog/classes/Network.php
r1436 r1446 56 56 require_once('classes/Security.php'); 57 57 require_once('classes/HotspotGraphElement.php'); 58 require_once('classes/TokenTemplate.php'); 59 58 60 59 61 /** … … 688 690 } 689 691 } 692 $params = array_map('trim',$params); 690 693 return call_user_func_array(array (new ReflectionClass($this->_row['network_authenticator_class']), 'newInstance'), $params); 691 694 … … 1694 1697 * Content management 1695 1698 */ 1696 /* $title = _("Network content");1697 $name = "network_".$this->_id."_content";1698 $data = Content::getLinkedContentUI($name, "network_has_content", "network_id", $this->_id, $display_page = "portal");1699 $html .= InterfaceElements::generateAdminSectionContainer("network_content", $title, $data);*/1700 1699 1701 1700 $html .= parent::getContentAdminUI(); … … 1928 1927 $html .= InterfaceElements::generateAdminSectionContainer("network_profile_templates", $title, $data); 1929 1928 1929 // Token templates 1930 $title = _("Network token templates"); 1931 $name = "network_".$this->_id."_token_templates"; 1932 $data = TokenTemplate::getTemplatesForNetworkUI($name, $this); 1933 $html .= InterfaceElements::generateAdminSectionContainer("network_token_templates", $title, $data); 1934 1930 1935 // objects hierarchy 1931 1936 $html .= parent::getGraphAdminUI($this); … … 1950 1955 // Content management 1951 1956 parent::processContentAdminUI(); 1952 /* $name = "network_".$this->_id."_content";1953 Content :: processLinkedContentUI($name, 'network_has_content', 'network_id', $this->_id);*/1954 1957 1955 1958 // name … … 2069 2072 ProfileTemplate :: processLinkedProfileTemplateUI($name, 'network_has_profile_templates', 'network_id', $this->_id); 2070 2073 2074 // Token templates 2075 $name = "network_".$this->_id."_token_templates"; 2076 TokenTemplate :: processTemplatesForNetworkUI($name, $this); 2077 2071 2078 parent::processGraphAdminUI($errMsg, $this); 2072 2079 if(!empty($errMsg)) { … … 2082 2089 } 2083 2090 } 2084 2085 /**2086 * Add network-wide content to this network2087 *2088 * @param object Content object2089 *2090 * @return void2091 *2092 * @access public2093 */2094 /* public function addContent(Content $content)2095 {2096 $db = AbstractDb::getObject();2097 2098 $content_id = $db->escapeString($content->getId());2099 $sql = "INSERT INTO network_has_content (network_id, content_id) VALUES ('$this->_id','$content_id')";2100 $db->execSqlUpdate($sql, false);2101 }*/2102 2103 /**2104 * Remove network-wide content from this network2105 *2106 * @param object Content object2107 *2108 * @return void2109 *2110 * @access public2111 */2112 /* public function removeContent(Content $content)2113 {2114 $db = AbstractDb::getObject();2115 2116 $content_id = $db->escapeString($content->getId());2117 $sql = "DELETE FROM network_has_content WHERE network_id='$this->_id' AND content_id='$content_id'";2118 $db->execSqlUpdate($sql, false);2119 }*/2120 2121 2091 2122 2092 /** -
branches/newtoken/wifidog/classes/Node.php
r1436 r1446 281 281 } 282 282 283 HotspotGraphElement::createNewObject($node_id, 'Node' );283 HotspotGraphElement::createNewObject($node_id, 'Node', $network); 284 284 285 285 $object = self::getObject($node_id); … … 1185 1185 1186 1186 //Node content 1187 /*$_html_content = array(); 1188 $_title = _("Node content"); 1189 $_data = Content::getLinkedContentUI("node_" . $node_id . "_content", "node_has_content", "node_id", $this->id, "portal"); 1190 $html .= InterfaceElements::generateAdminSectionContainer("node_content", $_title, $_data);*/ 1187 1191 1188 $html .= parent::getContentAdminUI(); 1192 1189 … … 1407 1404 // Content processing 1408 1405 parent::processContentAdminUI(); 1409 /*$name = "node_{$node_id}_content";1410 Content::processLinkedContentUI($name, 'node_has_content', 'node_id', $this->id);*/1411 1406 1412 1407 // Name … … 1589 1584 } 1590 1585 1591 /** Add content to this node */1592 /* public function addContent(Content $content)1593 {1594 $db = AbstractDb::getObject();1595 $content_id = $db->escapeString($content->getId());1596 $sql = "INSERT INTO node_has_content (node_id, content_id) VALUES ('$this->id','$content_id')";1597 $db->execSqlUpdate($sql, false);1598 exit;1599 }*/1600 1601 /** Remove content from this node */1602 /* public function removeContent(Content $content)1603 {1604 $db = AbstractDb::getObject();1605 $content_id = $db->escapeString($content->getId());1606 $sql = "DELETE FROM node_has_content WHERE node_id='$this->id' AND content_id='$content_id'";1607 $db->execSqlUpdate($sql, false);1608 }*/1609 1610 1586 /** 1611 1587 * The list of the 5 most recent users who have logged into this node in the past week, -
branches/newtoken/wifidog/classes/NodeGroup.php
r1436 r1446 170 170 } 171 171 172 HotspotGraphElement::createNewObject($node_group_id, 'NodeGroup' );172 HotspotGraphElement::createNewObject($node_group_id, 'NodeGroup', $network); 173 173 174 174 $object = self::getObject($node_group_id); … … 538 538 } 539 539 540 /** Add content to this node */541 /* public function addContent(Content $content)542 {543 $db = AbstractDb::getObject();544 $content_id = $db->escapeString($content->getId());545 $sql = "INSERT INTO node_has_content (node_id, content_id) VALUES ('$this->id','$content_id')";546 $db->execSqlUpdate($sql, false);547 exit;548 }*/549 550 /** Remove content from this node */551 /* public function removeContent(Content $content)552 {553 $db = AbstractDb::getObject();554 $content_id = $db->escapeString($content->getId());555 $sql = "DELETE FROM node_has_content WHERE node_id='$this->id' AND content_id='$content_id'";556 $db->execSqlUpdate($sql, false);557 }*/558 559 560 540 /** Reloads the object from the database. Should normally be called after a set operation */ 561 541 protected function refresh() -
branches/newtoken/wifidog/classes/Role.php
r1421 r1446 485 485 486 486 $retval = false; 487 if (Security::hasPermission( 'SERVER_PERM_EDIT_ROLES', Server::getServer())) {487 if (Security::hasPermission(Permission::P('SERVER_PERM_EDIT_ROLES'), Server::getServer())) { 488 488 $db = AbstractDb::getObject(); 489 489 $id = $db->escapeString($this->getId()); -
branches/newtoken/wifidog/classes/SmartyWifidog.php
r1421 r1446 189 189 Node::assignSmartyValues($this); 190 190 User::assignSmartyValues($this); 191 Token::assignSmartyValues($this); 191 192 return parent::fetch($resource_name, $cache_id, $compile_id, $display); 192 193 } -
branches/newtoken/wifidog/classes/Token.php
r1445 r1446 55 55 class Token 56 56 { 57 public static function generateConnectionToken($mac, $network, $user) { 57 /** 58 * Generate a new access token for the connection 59 * 60 * @param string $mac The mac address of the computer connecting 61 * 62 * @param string $network The network the person is connecting to 63 * 64 * @param string $node The node from which the connection originates 65 * 66 * TODO: eventually, the user should not be necessary for userless authentication. But much 67 * of the code would need to be changed in order to support this kind of authentication. 68 * @param string $user The user authenticating 69 * 70 * @param string $node_ip=null The ip address from which the connection originates 71 * 72 * @return tokenid | false 73 * 74 */ 75 public static function generateConnectionToken($mac, $network, $node, $user, $node_ip = null) { 58 76 $retval = false; 59 77 if ($user->isUserValid()) { 60 78 $db = AbstractDb::getObject(); 61 $session = Session::getObject(); 62 79 63 80 // Delete unused connection token 64 81 65 82 $token = self :: generateToken(); 66 if ( $_SERVER['REMOTE_ADDR']) {83 if (is_null($node_ip) && $_SERVER['REMOTE_ADDR']) { 67 84 $node_ip = $db->escapeString($_SERVER['REMOTE_ADDR']); 68 85 } 69 86 70 if ($ session && $node_ip && $session->get(SESS_NODE_ID_VAR)) {87 if ($node_ip && $node) { 71 88 //echo "$session && $node_ip && {$session->get(SESS_NODE_ID_VAR)}"; 72 $node_id = $db->escapeString($ session->get(SESS_NODE_ID_VAR));73 $abuseControlFault = User::isAbuseControlViolated($user, $mac, Node::getObject($node_id));89 $node_id = $db->escapeString($node->getId()); 90 $abuseControlFault = User::isAbuseControlViolated($user, $mac, $node); 74 91 if($abuseControlFault) { 75 92 throw new Exception ($abuseControlFault); … … 82 99 $sql = "DELETE FROM connections USING tokens "."WHERE tokens.token_id=connections.token_id AND token_status='".TOKEN_UNUSED."' AND user_id = '".$user->getId()."';\n"; 83 100 $db->execSqlUpdate($sql, false); 84 // TODO: Try to find a reusable token before creating a brand new one!85 101 86 102 // Check if we have any token templates 87 // TODO: token templates should be from a specific template and there should always be a template88 103 $templates = TokenTemplate::getTemplatesForNetwork($network); 89 104 if (count($templates) == 0) { 90 105 // No templates found 91 // create and return new token - we don't enforce token limits 106 // create and return new token - we don't enforce token limits, this is for backward compatibility 92 107 $token = self :: generateToken(); 93 108 $sql = "INSERT INTO tokens (token_owner, token_issuer, token_id, token_status) VALUES ('" . $user->getId() . "', '" . $user->getId() . "', '$token', '" . TOKEN_UNUSED . "');\n"; … … 144 159 $max_incoming_data_value = (!is_null($template->getMaxIncomingData())?$template->getMaxIncomingData():"null"); 145 160 $max_outgoing_data_value = (!is_null($template->getMaxOutgoingData())?$template->getMaxOutgoingData():"null"); 146 if (!is_null($template->getMaxUsageDuration())) 161 162 if (!is_null($template->getMaxConnectionDuration())) 163 $expiry_date = "CURRENT_TIMESTAMP + '" . $template->getMaxConnectionDuration() . "'"; 164 elseif (!is_null($template->getMaxUsageDuration())) 147 165 $expiry_date = "CURRENT_TIMESTAMP + '" . $template->getMaxUsageDuration() . "'"; 148 166 elseif (!is_null($template->getMaxWallClockDuration())) … … 164 182 } 165 183 } 166 184 self::setCurrentToken($retval); 167 185 return $retval; 168 186 } 169 187 170 /**171 * Generate a new access token for the specified user172 *173 * @param string $validated_user The user to generate a token for174 *175 * @param string $creator The user generating the token176 *177 * @param string $token_template_id The token template that the token should be associated with.178 * If templates aren't used then this the auth process will create179 * tokens automatically and we don't need to create tokens elsewhere.180 *181 * @param string $token_lot=null Optional. The token lot the token is part of.182 *183 * @return tokenid184 *185 */186 public static function generateTokenForUser($validated_user, $creator, $token_template_id, $token_lot = null) {187 $db = AbstractDb::getObject();188 $token = self::generateToken();189 190 $db->execSqlUpdate("INSERT INTO tokens (token_owner, token_issuer, token_id, token_template_id, token_status) VALUES ('" . $validated_user->getId() . "', '" . $creator->getId() . "', '$token', '" . $token_template_id . "', '" . TOKEN_UNUSED . "');");191 192 return $token;193 }194 195 188 public static function generateToken() { 196 189 return md5(uniqid(rand(), 1)); 190 } 191 192 /** 193 * Instantiate the current user 194 * 195 * @return mixed A User object, or null if there was an error 196 197 */ 198 public static function getCurrentToken() { 199 require_once ('classes/Session.php'); 200 $session = Session::getObject(); 201 $sessTokenId = $session->get('SESS_TOKEN_ID'); 202 203 /* if(!empty($sessCurrentUserId)){ 204 try { 205 $user = self :: getObject($sessCurrentUserId); 206 //$user = new User($session->get(SESS_USER_ID_VAR)); 207 } catch (Exception $e) { 208 $session->set(SESS_TOKEN_ID, null); 209 } 210 }*/ 211 return $sessTokenId; 212 } 213 214 /** 215 * Associates the user passed in parameter with the session 216 * 217 * This should NOT be called by anything except the Authenticators 218 * 219 * @param object $user User a user object, or null 220 * 221 * @return bool True if everything went well setting the session 222 223 */ 224 public static function setCurrentToken($tokenId) { 225 226 try { 227 $session = Session::getObject(); 228 $session->set('SESS_TOKEN_ID', $tokenId); 229 return true; 230 } catch (Exception $e) { 231 return false; 232 } 233 } 234 235 /** Set Smarty template values. Standardization routine. 236 * // TODO: implement this*/ 237 public static function assignSmartyValues($smarty) { 238 239 $tokenId = Token :: getCurrentToken(); 240 241 /** 242 * Define user security levels for the template 243 * 244 * These values are used in the default template of WiFoDog but could be 245 * used in a customized template to restrict certain links to specific 246 * user access levels. Note however that they will all be deprecateb by the 247 * new roles system. 248 */ 249 $smarty->assign('hasConnection', !empty($tokenId) ? true : false); 250 $smarty->assign('tokenId', $tokenId); 251 /*$smarty->assign('userIsValid', $user && !$user->isSplashOnlyUser() ? true : false); 252 $smarty->assign('userDEPRECATEDisSuperAdmin', $user && $user->DEPRECATEDisSuperAdmin()); 253 254 if (isset ($_REQUEST['debug_request']) && ($user && $user->DEPRECATEDisSuperAdmin())) { 255 // Tell Smarty everything it needs to know 256 $smarty->assign('debugRequested', true); 257 $smarty->assign('debugOutput', print_r($_REQUEST, true)); 258 }*/ 197 259 } 198 260 } -
branches/newtoken/wifidog/classes/TokenTemplate.php
r1445 r1446 48 48 require_once('classes/Token.php'); 49 49 50 // Token templates context constants 51 define('TT_CONTEXT_USER_ALLOWED', 1); 52 define('TT_CONTEXT_USER_VALIDATING', 2); 53 define('TT_CONTEXT_USER_FORGOT_PASSWORD', 3); 54 define('TT_CONTEXT_GUEST', 4); 55 define('TT_CONTEXT_SPLASH_ONLY', 5); 56 57 50 58 /** 51 59 * Abstract a token template … … 77 85 } 78 86 79 static function createNewObject() { 80 echo "<h1>Use TokenTemplate::createTokenTemplate() instead</h1>"; 87 static function createNewObject($tt_id = null, $network = null, $context = null) { 88 89 $db = AbstractDb::getObject(); 90 if (empty ($tt_id)) { 91 $tt_id = get_guid(); 92 } 93 $tt_id = $db->escapeString($tt_id); 94 if (is_null($network)) { 95 $netwok = Network::getDefaultNetwork(); 96 } 97 $network_id = $db->escapeString($network->getId()); 98 99 if (is_null($context)) { 100 $contexts = self::getContexts(); 101 $context = TT_CONTEXT_USER_ALLOWED; 102 } 103 104 105 $sql = "INSERT INTO token_templates (token_template_id, token_template_network, token_template_context) 106 VALUES ('$tt_id', '$network_id', '$context')"; 107 108 if (!$db->execSqlUpdate($sql, false)) { 109 throw new Exception(_('Unable to insert the new token template in the database!')); 110 } 111 $object = self::getObject($tt_id); 112 return $object; 81 113 } 82 114 … … 120 152 } 121 153 122 /** Create a new User in the database 123 * @param $id The id to be given to the new user 124 * @return the newly created User object, or null if there was an error 125 * TODO: implement this 126 */ 127 static function createTokenTemplate($id, $username, Network $network, $email, $password) { 128 /* $db = AbstractDb::getObject(); 129 130 $object = null; 131 $id_str = $db->escapeString($id); 132 $username_str = $db->escapeString($username); 133 $account_origin_str = $db->escapeString($account_origin->getId()); 134 $email_str = $db->escapeString($email); 135 136 $password_hash = $db->escapeString(User :: passwordHash($password)); 137 $status = ACCOUNT_STATUS_VALIDATION; 138 $token = User :: generateToken(); 139 140 $db->execSqlUpdate("INSERT INTO users (user_id,username, account_origin,email,pass,account_status,validation_token,reg_date) VALUES ('$id_str','$username_str','$account_origin_str','$email_str','$password_hash','$status','$token',CURRENT_TIMESTAMP)"); 141 142 $object = self::getObject($id); 143 return $object;*/ 154 155 static function getContexts() { 156 return array(TT_CONTEXT_USER_ALLOWED => "Authenticated user", 157 TT_CONTEXT_USER_VALIDATING => "Validating user", 158 TT_CONTEXT_USER_FORGOT_PASSWORD => "User forgot password", 159 TT_CONTEXT_GUEST => "Guest user (from another network)", 160 TT_CONTEXT_SPLASH_ONLY => "Splash-only user", ); 161 144 162 } 145 163 … … 235 253 } 236 254 237 function getCreationDate() {238 return $this->_row['token_template_creation_date'];239 }240 241 public function setCreationDate($value) {242 // Init values243 $retVal = true;244 245 if ($value != $this->getCreationDate()) {246 $db = AbstractDb::getObject();247 $value = $db->escapeString($value);248 $retVal = $db->execSqlUpdate("UPDATE token_templates SET creation_date = '{$value}' WHERE token_template_id = '{$this->getId()}'", false);249 $this->refresh();250 }251 return $retVal;252 }253 254 255 function getMaxIncomingData() { 255 256 return $this->_row['token_max_incoming_data']; … … 313 314 if ($value != $this->getMaxConnectionDuration()) { 314 315 $db = AbstractDb::getObject(); 315 $value = $db->escapeString($value);316 $retVal = $db->execSqlUpdate("UPDATE token_templates SET token_max_connection_duration = '{$value}'WHERE token_template_id = '{$this->getId()}'", false);316 $value = ($value != ''?"'".$db->escapeString($value)."'": 'null'); 317 $retVal = $db->execSqlUpdate("UPDATE token_templates SET token_max_connection_duration = {$value} WHERE token_template_id = '{$this->getId()}'", false); 317 318 $this->refresh(); 318 319 } … … 330 331 if ($value != $this->getMaxUsageDuration()) { 331 332 $db = AbstractDb::getObject(); 332 $value = $db->escapeString($value);333 $value = ($value != ''?"'".$db->escapeString($value)."'": 'null'); 333 334 $retVal = $db->execSqlUpdate("UPDATE token_templates SET token_max_usage_duration = '{$value}' WHERE token_template_id = '{$this->getId()}'", false); 334 335 $this->refresh(); … … 338 339 339 340 function getMaxWallClockDuration() { 340 return $this->_row['token_max_ usage_duration'];341 return $this->_row['token_max_wall_clock_duration']; 341 342 } 342 343 … … 347 348 if ($value != $this->getMaxWallClockDuration()) { 348 349 $db = AbstractDb::getObject(); 349 $value = $db->escapeString($value);350 $retVal = $db->execSqlUpdate("UPDATE token_templates SET token_max_ usage_duration = '{$value}' WHERE token_template_id = '{$this->getId()}'", false);350 $value = ($value != ''?"'".$db->escapeString($value)."'": 'null'); 351 $retVal = $db->execSqlUpdate("UPDATE token_templates SET token_max_wall_clock_duration = '{$value}' WHERE token_template_id = '{$this->getId()}'", false); 351 352 $this->refresh(); 352 353 } … … 363 364 if ($value != $this->getMaxAge()) { 364 365 $db = AbstractDb::getObject(); 366 $value = ($value != ''?"'".$db->escapeString($value)."'": 'null'); 367 $retVal = $db->execSqlUpdate("UPDATE token_templates SET token_max_age = '{$value}' WHERE token_template_id = '{$this->getId()}'", false); 368 $this->refresh(); 369 } 370 return $retVal; 371 } 372 373 function getContext() { 374 return $this->_row['token_template_context']; 375 } 376 377 public function setContext($value) { 378 $retVal = true; 379 380 if ($value != $this->getContext()) { 381 $db = AbstractDb::getObject(); 365 382 $value = $db->escapeString($value); 366 $retVal = $db->execSqlUpdate("UPDATE token_templates SET token_max_age = '{$value}' WHERE token_template_id = '{$this->getId()}'", false); 383 $retVal = $db->execSqlUpdate("UPDATE token_templates SET token_template_context = '{$value}' WHERE token_template_id = '{$this->getId()}'", false); 384 $this->refresh(); 385 } 386 return $retVal; 387 } 388 389 function getDescription() { 390 return $this->_row['token_template_description']; 391 } 392 393 public function setDescription($value) { 394 $retVal = true; 395 396 if ($value != $this->getDescription()) { 397 $db = AbstractDb::getObject(); 398 $value = $db->escapeString($value); 399 $retVal = $db->execSqlUpdate("UPDATE token_templates SET token_template_description = '{$value}' WHERE token_template_id = '{$this->getId()}'", false); 367 400 $this->refresh(); 368 401 } … … 386 419 return $retVal; 387 420 } 421 388 422 389 423 public static function generateToken() { … … 443 477 return $html; 444 478 } 445 446 /** Get the selected user, IF one was selected and is valid 447 * @param $user_prefix A identifier provided by the programmer to recognise it's generated form 448 * @param &$errMsg An error message will be appended to this is the username is not empty, but the user doesn't exist. 449 * @return the User object, or null if the user is invalid or none was selected 450 * TODO: implement this 479 480 /** 481 * Get an interface to add/edit token templates linked to a network 482 * 483 * @param string $user_prefix A identifier provided by the 484 * programmer to recognise it's 485 * generated HTML form 486 * @param Network $network The network to get the ui for 487 * @return string HTML markup 488 451 489 */ 452 static function processSelectUserUI($user_prefix, &$errMsg) { 453 /*$object = null; 454 try { 455 $network = Network :: processSelectUI($user_prefix); 456 $name = "select_user_{$user_prefix}_username"; 457 if (!empty ($_REQUEST[$name])) { 458 $username = $_REQUEST[$name]; 459 return self :: getUserByUsernameOrEmail($username, $errMsg); 460 } else 461 return null; 462 } catch (Exception $e) { 463 return null; 464 }*/ 465 } 466 467 // TODO: implement this 490 public static function getTemplatesForNetworkUI($user_prefix, $network) { 491 492 $db = AbstractDb :: getObject(); 493 494 $networktemplates = self::getTemplatesForNetwork($network); 495 $object_id = $db->escapeString($network->getId()); 496 497 // Get the list of all contexts to see which are taken 498 $contexts = self::getContexts(); 499 $html = "<table class='token_template_management'>\n"; 500 $html .= "<th>" . _('Context') . '</th><th>' . _('Actions') . '</th>' . "\n"; 501 502 503 foreach ($networktemplates as $template) { 504 505 $html .= "<tr class='token_template'>\n"; 506 /* Display page */ 507 $html .= "<td>" . $contexts[$template->getContext()] . "</td>\n"; 508 $html .= "<td>"; 509 $name = $object_id . "_tt_" . $template->getId() . "_" . $template->getContext() . "_edit"; 510 $html .= "<input type='button' class='submit' name='$name' value='" . _("Edit") . "' onClick='window.open(\"" . GENERIC_OBJECT_ADMIN_ABS_HREF . "?object_class=TokenTemplate&action=edit&object_id=" . $template->getId() . "\");'>\n"; 511 $html .= "</td>\n"; 512 $html .= "</tr>\n"; 513 unset($contexts[$template->getContext()]); 514 } 515 516 // Add new token for remaining context 517 if (!empty($contexts)) { 518 $choices = array(); 519 $i = 0; 520 foreach ($contexts as $key => $value) { 521 $choices[$i][0] = $key; 522 $choices[$i][1] = $value; 523 $i++; 524 } 525 $html .= "<tr>"; 526 $html .= "<td>" . FormSelectGenerator::generateFromArray($choices, null, $user_prefix, 'tt_add', false) . "</td>\n"; 527 $name = $object_id . "_tt_add"; 528 $html .= "<td><input type='submit' class='submit' name='$name' value='" . _("Add") . "'></td>\n"; 529 $html .= "</tr>\n"; 530 531 } 532 $html .= "</table>\n"; 533 534 return $html; 535 } 536 537 /** 538 * processes the interface to add / edit token templates 539 * 540 * @param string $user_prefix A identifier provided by the 541 * programmer to recognise it's 542 * generated HTML form 543 * @param Network $network The network to get the ui for 544 * @return string HTML markup 545 546 */ 547 public static function processTemplatesForNetworkUI($user_prefix, $network) { 548 549 $db = AbstractDb :: getObject(); 550 551 $networktemplates = self::getTemplatesForNetwork($network); 552 $object_id = $db->escapeString($network->getId()); 553 554 // Get the list of all contexts to see which are taken 555 $contexts = self::getContexts(); 556 557 $name = $object_id . "_tt_add"; 558 if (!empty($_REQUEST[$name])) { 559 $context = FormSelectGenerator::getResult($user_prefix, 'tt_add'); 560 self::createNewObject(null, $network, $context); 561 } 562 563 } 564 468 565 public function getAdminUI() { 566 Security::requirePermission(Permission::P('NETWORK_PERM_EDIT_NETWORK_CONFIG'), $this->getNetwork()); 567 require_once('classes/InterfaceElements.php'); 568 // Init values 569 $html = ''; 570 469 571 /* 470 $db = AbstractDb::getObject(); 471 $currentUser = self :: getCurrentUser(); 472 $userPreferencesItems = array(); 473 $finalHtml = ''; 474 if(Security::hasPermission(Permission::P('NETWORK_PERM_VIEW_STATISTICS'), $this->getNetwork())) { 475 // Statistics 476 $content = "<a href='".BASE_SSL_PATH."admin/stats.php?Statistics=".$this->getNetwork()->getId()."&distinguish_users_by=user_id&stats_selected_users=".$this->getUsername()."&UserReport=on&user_id=".$this->getId()."&action=generate'>"._("Get user statistics")."</a>\n"; 477 $administrationItems[] = InterfaceElements::genSectionItem($content); 478 479 // Account status 480 $title = _("Account Status"); 481 $help = _("Note that Error is for internal use only"); 482 $name = "user_" . $this->getId() . "_accountstatus"; 483 global $account_status_to_text; 484 $content = FormSelectGenerator::generateFromKeyLabelArray($account_status_to_text, $this->getAccountStatus(), $name, null, false); 485 $administrationItems[] = InterfaceElements::genSectionItem($content, $title, $help); 486 487 $finalHtml .= InterfaceElements::genSection($administrationItems, _("Administrative options")); 488 } 489 490 if (($this == $currentUser && !$this->isSplashOnlyUser() )|| Security::hasPermission(Permission::P('NETWORK_PERM_EDIT_ANY_USER'), $this->getNetwork())) { 491 // Username 492 $title = _("Username"); 493 $name = "user_" . $this->getId() . "_username"; 494 $content = "<input type='text' name='$name' value='" . htmlentities($this->getUsername()) . "' size=30><br/>\n"; 495 $content .= _("Be careful when changing this: it's the username you use to log in!"); 496 $userPreferencesItems[] = InterfaceElements::genSectionItem($content, $title); 497 498 499 // Email 500 $title = _("Email"); 501 $name = "email_" . $this->getId() . "_email"; 502 $content = "<input type='text' name='$name' disabled='disabled' value='" . htmlentities($this->getEmail()) . "' size=30><br/>\n"; 503 $content .= _("If you wish to change this address, please Email Support!"); 504 $userPreferencesItems[] = InterfaceElements::genSectionItem($content, $title); 505 506 507 508 // Change password 509 $changePasswordItems=array(); 510 if($this == $currentUser) {//Don't enter the old password if changing password for another user 511 $title = _("Your current password"); 512 $name = "user_" . $this->getId() . "_oldpassword"; 513 $content = "<input type='password' name='$name' size='20'>\n"; 514 $changePasswordItems[] = InterfaceElements::genSectionItem($content, $title); 515 } 516 517 $title = _("Your new password"); 518 $name = "user_" . $this->getId() . "_newpassword"; 519 $content = "<input type='password' name='$name' size='20'>\n"; 520 $changePasswordItems[] = InterfaceElements::genSectionItem($content, $title); 521 522 $title = _("Your new password (again)"); 523 $name = "user_" . $this->getId() . "_newpassword_again"; 524 $content = "<input type='password' name='$name' size='20'>\n"; 525 $changePasswordItems[] = InterfaceElements::genSectionItem($content, $title); 526 527 $userPreferencesItems[] = InterfaceElements::genSection($changePasswordItems, _("Change my password")); 528 529 $finalHtml .= InterfaceElements::genSection($userPreferencesItems, _("User preferences"), false, false, get_class($this)); 530 531 //N.B: For now, let pretend we have only one profile per use... 532 $profiles = $this->getAllProfiles(); 533 $current_profile = null; 534 if(!empty($profiles)) { 535 $current_profile = $profiles[0]; 536 } 537 538 if($current_profile != null) { 539 $finalHtml .= $current_profile->getAdminUI(); 540 $name = "user_" . $this->getId() . "_delete_profile_".$current_profile->getId(); 541 $value = _("Completely delete my public profile"); 542 $finalHtml .= "<div class='admin_element_tools'>"; 543 $finalHtml .= '<input type="submit" class="submit" name="' . $name . '" value="' . $value . '">'; 544 $finalHtml .= "</div>"; 545 } 546 else { // Get the list of profile templates for the users' network 547 $profile_templates = ProfileTemplate::getAllProfileTemplates($this->getNetwork()); 548 if(!empty($profile_templates)) { 549 $name = "user_" . $this->getId() . "_add_profile"; 550 $value = _("Create my public profile"); 551 $finalHtml .= "<div class='admin_element_tools'>"; 552 $finalHtml .= '<input type="submit" class="submit" name="' . $name . '" value="' . $value . '">'; 553 $finalHtml .= "</div>"; 554 } 555 } 556 } 557 558 return $finalHtml;*/ 559 } 560 561 // TODO Implement this 572 * Verify if an error message was registered before outputting the form 573 */ 574 if (isset($this->errorMsg)) { 575 $html .= "<div class='errormsg'>" . $this->errorMsg . "</div>"; 576 } 577 $tt_id = $this->getId(); 578 579 /* 580 * Begin with admin interface 581 */ 582 $html .= "<fieldset class='admin_container ".get_class($this)."'>\n"; 583 $html .= "<legend>"._("Token template")."</legend>\n"; 584 $html .= "<ul class='admin_element_list'>\n"; 585 586 /* 587 * Template information 588 */ 589 $html_tt_information = array(); 590 591 // template id 592 $title = _("Token Template Id"); 593 $data = htmlspecialchars($tt_id, ENT_QUOTES); 594 $html_tt_information[] = InterfaceElements::generateAdminSectionContainer("tt_id", $title, $data); 595 596 // template context 597 $title = _("Token Template Context"); 598 $contexts = self::getContexts(); 599 $data = htmlspecialchars(_($contexts[$this->getContext()]), ENT_QUOTES); 600 $html_tt_information[] = InterfaceElements::generateAdminSectionContainer("tt_context", $title, $data); 601 602 // template description 603 $_title = _("Description"); 604 $name = "tt_" . $tt_id . "_description"; 605 $data = "<textarea name='$name' cols=80 rows=5 id='tt_description_textarea'>\n".$this->getDescription()."\n</textarea>\n"; 606 $html_tt_information[] = InterfaceElements::generateAdminSectionContainer("tt_description", $_title, $data); 607 608 // is reusable 609 $title = _("Template reusable"); 610 $help = _("Are tokens generated from this template reusable?"); 611 $data = InterfaceElements::generateInputCheckbox("tt_" . $tt_id . "_reusable", "", _("Yes"), $this->getIsReusable(), "tt_reusable_radio"); 612 $html_tt_information[] = InterfaceElements::generateAdminSectionContainer("tt_reusable", $title, $data, $help); 613 614 // Build section 615 $html .= InterfaceElements::generateAdminSectionContainer("tt_information", _("Information about the token template"), implode(null, $html_tt_information)); 616 617 618 /* 619 * TT's data information 620 */ 621 $html_tt_data_properties = array(); 622 623 // max incoming data 624 $title = _("Max incoming data"); 625 $help = _("The maximum number of bytes of data this token can receive"); 626 $data = InterfaceElements::generateInputText("tt_" . $tt_id . "_max_incoming", $this->getMaxIncomingData(), "tt_max_incoming_input"); 627 $html_tt_data_properties[] = InterfaceElements::generateAdminSectionContainer("tt_max_incoming", $title, $data, $help); 628 629 // max outoing data 630 $title = _("Max outgoing data"); 631 $help = _("The maximum number of bytes of data this token can send"); 632 $data = InterfaceElements::generateInputText("tt_" . $tt_id . "_max_outgoing", $this->getMaxOutgoingData(), "tt_max_outgoing_input"); 633 $html_tt_data_properties[] = InterfaceElements::generateAdminSectionContainer("tt_max_outgoing", $title, $data, $help); 634 635 // max total data 636 $title = _("Max total data"); 637 $help = _("The maximum total number of bytes this token can send and receive"); 638 $data = InterfaceElements::generateInputText("tt_" . $tt_id . "_max_total_data", $this->getMaxTotalData(), "tt_max_total_data_input"); 639 $html_tt_data_properties[] = InterfaceElements::generateAdminSectionContainer("tt_max_data", $title, $data, $help); 640 641 // Build section 642 $html .= InterfaceElements::generateAdminSectionContainer("tt_data", _("Data limits"), implode(null, $html_tt_data_properties)); 643 644 645 /* 646 * TT's data information 647 */ 648 $html_tt_duration_properties = array(); 649 650 // max incoming data 651 $title = _("Max connection duration"); 652 $help = _("The length of a single connection."); 653 $data = InterfaceElements::generateInputText("tt_" . $tt_id . "_max_conn_duration", $this->getMaxConnectionDuration(), "tt_max_conn_duration_input"); 654 $html_tt_duration_properties[] = InterfaceElements::generateAdminSectionContainer("tt_max_conn_duration", $title, $data, $help); 655 656 // max outoing data 657 $title = _("Max usage"); 658 $help = _("The maximum time a user can be online (counting only when used). Allows access by the hour."); 659 $data = InterfaceElements::generateInputText("tt_" . $tt_id . "_max_usage", $this->getMaxUsageDuration(), "tt_max_usage_input"); 660 $html_tt_duration_properties[] = InterfaceElements::generateAdminSectionContainer("tt_max_usage", $title, $data, $help); 661 662 // max total data 663 $title = _("Max wall clock duration"); 664 $help = _("The maximum amount of time a token can be used, starting count when first used. Allows weekly, daily tokens."); 665 $data = InterfaceElements::generateInputText("tt_" . $tt_id . "_max_wc_duration", $this->getMaxWallClockDuration(), "tt_max_wc_duration_input"); 666 $html_tt_duration_properties[] = InterfaceElements::generateAdminSectionContainer("tt_max_wc_duration", $title, $data, $help); 667 668 // max total data 669 $title = _("Max age"); 670 $help = _("The maximum age before a token expires, starting count when issued."); 671 $data = InterfaceElements::generateInputText("tt_" . $tt_id . "_max_age", $this->getMaxAge(), "tt_max_age_input"); 672 $html_tt_duration_properties[] = InterfaceElements::generateAdminSectionContainer("tt_max_age", $title, $data, $help); 673 674 // Build section 675 $html .= InterfaceElements::generateAdminSectionContainer("tt_duration", _("Duration limits"), implode(null, $html_tt_duration_properties), 676 _("For these values, any postgresql interval is acceptable, for example '1 day', '1 month', '3 week'")); 677 678 return $html; 679 } 680 562 681 public function processAdminUI() { 563 /* $db = AbstractDb::getObject(); 564 $currentUser = self :: getCurrentUser(); 565 if (Security::hasPermission(Permission::P('NETWORK_PERM_EDIT_ANY_USER'), $this->getNetwork())) { 566 // Account status 567 $name = "user_" . $this->getId() . "_accountstatus"; 568 $status = FormSelectGenerator::getResult($name, null); 569 $this->setAccountStatus($status); 570 } 571 572 if ($this == $currentUser || Security::requirePermission(Permission::P('NETWORK_PERM_EDIT_ANY_USER'), $this->getNetwork())) { 573 // Username 574 $name = "user_" . $this->getId() . "_username"; 575 $this->setUsername($_REQUEST[$name]); 576 577 // Change password 578 $nameOldpassword = "user_" . $this->getId() . "_oldpassword"; 579 $nameNewpassword = "user_" . $this->getId() . "_newpassword"; 580 $nameNewpasswordAgain = "user_" . $this->getId() . "_newpassword_again"; 581 if($_REQUEST[$nameNewpassword]!=null){ 582 if ($this == $currentUser && $this->getPasswordHash() != User::passwordHash($_REQUEST[$nameOldpassword])) { 583 throw new Exception(_("Wrong password.")); 584 } 585 if ($_REQUEST[$nameNewpassword] != $_REQUEST[$nameNewpasswordAgain]){ 586 throw new Exception(_("Passwords do not match.")); 587 } 588 $this->setPassword($_REQUEST[$nameNewpassword]); 589 } 590 591 // Pretend there is only one 592 $profiles = $this->getAllProfiles(); 593 if(!empty($profiles)) { 594 $current_profile = $profiles[0]; 595 if($current_profile != null) { 596 $current_profile->processAdminUI(); 597 $name = "user_" . $this->getId() . "_delete_profile_".$current_profile->getId(); 598 if(!empty($_REQUEST[$name])) { 599 $errmsg=null; 600 $current_profile->delete($errmsg); 601 } 602 } 603 } 604 else { 605 $name = "user_" . $this->getId() . "_add_profile"; 606 if(!empty($_REQUEST[$name])) { 607 // Get the list of profile templates for the users' network 608 $profile_templates = ProfileTemplate::getAllProfileTemplates($this->getNetwork()); 609 if(!empty($profile_templates)) { 610 // Create a blank profile and link it to the user 611 $current_profile = Profile::createNewObject(null, $profile_templates[0]); 612 $this->addProfile($current_profile); 613 } 614 } 615 616 } 617 618 }*/ 682 Security::requirePermission(Permission::P('NETWORK_PERM_EDIT_NETWORK_CONFIG'), $this->getNetwork()); 683 $tt_id = $this->getId(); 684 685 // template description 686 $name = "tt_" . $tt_id . "_description"; 687 $this->setDescription($_REQUEST[$name]); 688 689 // is reusable 690 $name = "tt_" . $tt_id . "_reusable"; 691 $this->setIsReusable(empty ($_REQUEST[$name]) ? false : true); 692 693 // max incoming data 694 $name = "tt_" . $tt_id . "_max_incoming"; 695 $this->setMaxIncomingData($_REQUEST[$name]); 696 697 // max outoing data 698 $name = "tt_" . $tt_id . "_max_outgoing"; 699 $this->setMaxOutgoingData($_REQUEST[$name]); 700 701 // max total data 702 $name = "tt_" . $tt_id . "_max_total_data"; 703 $this->setMaxTotalData($_REQUEST[$name]); 704 705 // max incoming data 706 $name = "tt_" . $tt_id . "_max_conn_duration"; 707 $this->setMaxConnectionDuration($_REQUEST[$name]); 708 709 // max outoing data 710 $name = "tt_" . $tt_id . "_max_usage"; 711 $this->setMaxUsageDuration($_REQUEST[$name]); 712 713 // max total data 714 $name = "tt_" . $tt_id . "_max_wc_duration"; 715 $this->setMaxWallClockDuration($_REQUEST[$name]); 716 717 // max total data 718 $name = "tt_" . $tt_id . "_max_age"; 719 $this->setMaxAge($_REQUEST[$name]); 720 619 721 } 620 722 … … 626 728 */ 627 729 public function canGenerateForUser($user, $mac) { 628 return true; 730 // First make sure the user has the right status for this template 731 $retval = true; 732 if ($user instanceof User) { 733 switch($this->getContext()) { 734 case TT_CONTEXT_USER_ALLOWED: 735 $retval = ($user->getAccountStatus() == ACCOUNT_STATUS_ALLOWED); 736 break; 737 case TT_CONTEXT_USER_VALIDATING: 738 $retval = ($user->getAccountStatus() == ACCOUNT_STATUS_VALIDATION); 739 break; 740 case TT_CONTEXT_USER_FORGOT_PASSWORD: 741 742 break; 743 case TT_CONTEXT_GUEST: 744 $retval = ($user->getNetwork()->getId() != Network::getCurrentNetwork()->getId()); 745 break; 746 case TT_CONTEXT_SPLASH_ONLY: 747 $retval = ($user->isSplashOnlyUser()); 748 break; 749 default: 750 $retval = false; 751 } 752 753 } 754 return $retval; 629 755 /* $retval = false; 630 756 // A new token can be generated if … … 687 813 } 688 814 689 /** Set Smarty template values. Standardization routine.690 * // TODO: implement this*/691 public static function assignSmartyValues($smarty, $user = null) {692 /*if (!$user)693 $user = User :: getCurrentUser();694 $session = Session :: getObject();695 $smarty->assign('userOriginallyRequestedURL', $session ? $session->get(SESS_ORIGINAL_URL_VAR) : '');696 $smarty->assign('userId', $user ? $user->getId() : '');697 $smarty->assign('userName', $user ? $user->getUsername() : '');*/698 /**699 * Define user security levels for the template700 *701 * These values are used in the default template of WiFoDog but could be702 * used in a customized template to restrict certain links to specific703 * user access levels. Note however that they will all be deprecateb by the704 * new roles system.705 */706 /*$smarty->assign('userIsValid', $user && !$user->isSplashOnlyUser() ? true : false);707 $smarty->assign('userDEPRECATEDisSuperAdmin', $user && $user->DEPRECATEDisSuperAdmin());708 709 if (isset ($_REQUEST['debug_request']) && ($user && $user->DEPRECATEDisSuperAdmin())) {710 // Tell Smarty everything it needs to know711 $smarty->assign('debugRequested', true);712 $smarty->assign('debugOutput', print_r($_REQUEST, true));713 }*/714 }715 815 } 716 816 -
branches/newtoken/wifidog/classes/User.php
r1445 r1446 172 172 return $object; 173 173 } 174 175 /** Instantiate a user object 176 * @param $username The username of the user 177 * @param $account_origin Network: The account origin 178 * @param &$errMsg An error message will be appended to this if the username is not empty, but the user doesn't exist. 179 * @return a User object, or null if there was an error 180 */ 181 public static function getUserByUsernameOrEmailAndOrigin($usernameOrEmail, Network $account_origin, &$errMsg = null) { 182 $db = AbstractDb::getObject(); 183 $object = null; 184 185 $username_str = $db->escapeString($usernameOrEmail); 186 $comparison = ($account_origin->getUsernamesCaseSensitive()? '=': 'ILike'); 187 $account_origin_str = $db->escapeString($account_origin->getId()); 188 $db->execSqlUniqueRes("SELECT user_id FROM users WHERE (username {$comparison} '$username_str' OR email ILike '$username_str') AND account_origin = '$account_origin_str'", $user_info, false); 189 190 if ($user_info != null) { 191 $object = self::getObject($user_info['user_id']); 192 } 193 else if (!empty($usernameOrEmail)) { 194 $errMsg .= sprintf(_("There is no user with username or email %s"),$usernameOrEmail); 195 } 196 return $object; 197 } 174 198 175 199 /** Instantiate a user object … … 653 677 $node_id = $db->escapeString($session->get(SESS_NODE_ID_VAR)); 654 678 $abuseControlFault = User::isAbuseControlViolated($this, $mac, Node::getObject($node_id)); 679 if($abuseControlFault) { 680 throw new Exception ($abuseControlFault); 681 } 682 $mac = (is_null($mac)?'': $db->escapeString($mac)); 683 /* 684 * Delete all unused tokens for this user, so we don't fill the database 685 * with them 686 */ 687 $sql = "DELETE FROM connections USING tokens "."WHERE tokens.token_id=connections.token_id AND token_status='".TOKEN_UNUSED."' AND user_id = '".$this->getId()."';\n"; 688 // TODO: Try to find a reusable token before creating a brand new one! 689 690 $sql .= "INSERT INTO tokens (token_owner, token_issuer, token_id, token_status) VALUES ('" . $this->getId() . "', '" . $this->getId() . "', '$token', '" . TOKEN_UNUSED . "');\n"; 691 $sql .= "INSERT INTO connections (user_id, token_id, timestamp_in, node_id, node_ip, last_updated, user_mac) VALUES ('" . $this->getId() . "', '$token', CURRENT_TIMESTAMP, '$node_id', '$node_ip', CURRENT_TIMESTAMP, '$mac')"; 692 $db->execSqlUpdate($sql, false); 693 $retval = $token; 694 } 695 else { 696 $retval = false; 697 } 698 } 699 else { 700 $retval = false; 701 } 702 return $retval; 703 } 704 705 /** Generate a token in the connection table so the user can actually use the internet 706 @return true on success, false on failure 707 */ 708 function generateConnectionTokenNoSession($node, $node_ip = null, $mac = null ) { 709 if ($this->isUserValid()) { 710 $db = AbstractDb::getObject(); 711 712 $token = self :: generateToken(); 713 if ($node_ip && $node) { 714 //echo "$session && $node_ip && {$session->get(SESS_NODE_ID_VAR)}"; 715 $node_id = $node->getId(); 716 $abuseControlFault = User::isAbuseControlViolated($this, $mac, $node); 655 717 if($abuseControlFault) { 656 718 throw new Exception ($abuseControlFault); … … 857 919 if (!empty ($_REQUEST[$name])) { 858 920 $username = $_REQUEST[$name]; 859 return self :: getUserByUsernameOrEmail ($username, $errMsg);921 return self :: getUserByUsernameOrEmailAndOrigin($username, $network, $errMsg); 860 922 } else 861 923 return null; -
branches/newtoken/wifidog/include/common.php
r1428 r1446 156 156 define('LOGOUT_REASON_GARBAGE_COLLECTED', 3); 157 157 define('LOGOUT_REASON_UNKNOWN', 0); 158 define('LOGOUT_REASON_USER_LOGOUT', 1); 159 158 160 /* End of Other constants */ 159 161 -
branches/newtoken/wifidog/include/schema_validate.php
r1445 r1446 1529 1529 printUpdateVersion($new_schema_version); 1530 1530 $sql .= "\n\nUPDATE schema_info SET value='$new_schema_version' WHERE tag='schema_version';\n"; 1531 $sql .= "ALTER TABLE token_templates ADD COLUMN token_template_context integer;\n"; 1532 $sql .= "ALTER TABLE token_templates ALTER COLUMN token_template_context SET DEFAULT NULL;\n"; 1533 $sql .= "ALTER TABLE token_templates ADD COLUMN token_template_description text;\n"; 1534 $sql .= "ALTER TABLE token_templates ALTER COLUMN token_template_description SET DEFAULT NULL;\n"; 1531 1535 1532 1536 //$networks = Network::getAllNetworks(); … … 1535 1539 foreach ($networks as $network) { 1536 1540 $new_guid = get_guid(); 1537 $sql .= "INSERT INTO token_templates(token_template_id, token_template_network ) values('{$new_guid}', '{$network['network_id']}');\n ";1541 $sql .= "INSERT INTO token_templates(token_template_id, token_template_network, token_template_context, token_template_description) values('{$new_guid}', '{$network['network_id']}', 1, 'Created when the database schema was updated');\n "; 1538 1542 } 1543 1539 1544 } 1540 1545 -
branches/newtoken/wifidog/login/index.php
r1445 r1446 197 197 $user = $network->getSplashOnlyUser(); 198 198 //$token = $user->generateConnectionToken($mac); 199 $token = Token::generateConnectionToken($mac, $network, $ user);199 $token = Token::generateConnectionToken($mac, $network, $node, $user); 200 200 User::setCurrentUser($user); 201 201 header("Location: http://" . $gw_address . ":" . $gw_port . "/wifidog/auth?token=" . $token); … … 222 222 // Login from a gateway, redirect to the gateway to activate the token 223 223 // $token = $user->generateConnectionToken($mac); 224 $token = Token::generateConnectionToken($mac, $network, $ user);224 $token = Token::generateConnectionToken($mac, $network, $node, $user); 225 225 if(!$token) 226 226 { … … 280 280 $html .= "<h1>"._("I'm having difficulties:")."</h1>\n"; 281 281 $html .= "<ul>\n"; 282 $html .= "<li><a href='".BASE_URL_PATH."lost_username.php '>"._("I Forgot my username")."</a></li>\n";283 $html .= "<li><a href='".BASE_URL_PATH."lost_password.php '>"._("I Forgot my password")."</a></li>\n";284 $html .= "<li><a href='".BASE_URL_PATH."resend_validation.php '>"._("Re-send the validation email")."</a></li>\n";282 $html .= "<li><a href='".BASE_URL_PATH."lost_username.php?" . $_SERVER['QUERY_STRING']. "'>"._("I Forgot my username")."</a></li>\n"; 283 $html .= "<li><a href='".BASE_URL_PATH."lost_password.php?" . $_SERVER['QUERY_STRING']. "'>"._("I Forgot my password")."</a></li>\n"; 284 $html .= "<li><a href='".BASE_URL_PATH."resend_validation.php?" . $_SERVER['QUERY_STRING']. "'>"._("Re-send the validation email")."</a></li>\n"; 285 285 $html .= "</ul>\n"; 286 286 $html .= "</div>\n"; … … 309 309 310 310 // Get all network content and node "login" content 311 $content_rows = null; 312 $network_id = $network->getId(); 313 $sql_network = "(SELECT content_id, display_area, display_order, subscribe_timestamp FROM network_has_content WHERE network_id='$network_id' AND display_page='login') "; 314 $sql_node = null; 311 // Get all the parent objects of the node 315 312 if ($node) { 316 // Get all node content 317 $node_id = $db->escapeString($node->getId()); 318 $sql_node = "UNION (SELECT content_id, display_area, display_order, subscribe_timestamp FROM node_has_content WHERE node_id='$node_id' AND display_page='login')"; 319 } 320 $sql = "SELECT * FROM ($sql_network $sql_node) AS content_everywhere ORDER BY display_area, display_order, subscribe_timestamp DESC"; 321 313 $parents = HotspotGraph::getAllParents($node); 314 } else { 315 $parents = array($network->getHgeId()); 316 } 317 318 $first = $db->escapeString(array_shift($parents)); 319 $sql_from = "(SELECT content_id, display_area, display_order, subscribe_timestamp 320 FROM hotspot_graph_element_has_content 321 WHERE hotspot_graph_element_id='$first' AND display_page='login')"; 322 323 // Get the contents for all elements parents of and including the node, but exclude user subscribed content if user is known 324 foreach($parents as $parentid) { 325 $parent_id = $db->escapeString($parentid); 326 $sql_from .= " UNION (SELECT content_id, display_area, display_order, subscribe_timestamp 327 FROM hotspot_graph_element_has_content hgehc 328 WHERE hotspot_graph_element_id='$parent_id' AND display_page='login')"; 329 } 330 $sql = "SELECT * FROM ($sql_from) AS content_everywhere ORDER BY display_area, display_order, subscribe_timestamp DESC"; 322 331 $db->execSql($sql, $content_rows, false); 323 332 if ($content_rows) { … … 329 338 } 330 339 } 340 $showMoreLink = false; 341 331 342 332 343 /* -
branches/newtoken/wifidog/signup.php
r1435 r1446 233 233 // Make sure the user IDs match 234 234 if(($created_user->getId() == $authenticated_user->getId())) { 235 $token = $created_user->generateConnectionToken($mac); 235 $node = Node::getObjectByGatewayId($gw_id); 236 $network = $node->getNetwork(); 237 $token = Token::generateConnectionToken($mac, $network, $node, $created_user); 236 238 237 239 $redirURL = "http://" . $gw_address . ":" . $gw_port . "/wifidog/auth?token=" . $token; -
branches/newtoken/wifidog/templates/classes/MainUI_ToolContent.tpl
r1308 r1446 55 55 <div>{"Logged in as"|_}: {$userListUI}</div> 56 56 <a id="preferences_link" href="{$base_ssl_path}admin/generic_object_admin.php?object_id={$userId}&object_class=User&action=edit"><img src="{$common_images_url}profile.gif"> {"Profile / Settings"|_}</a> 57 {if $hasConnection}<a id="preferences_link" href="{$base_ssl_path}admin/generic_object_admin.php?object_id={$tokenId}&object_class=Connection&action=edit"><img src="{$common_images_url}profile.gif"> {"Connection information"|_}</a>{/if} 57 58 <a id="logout_link" href="{$base_ssl_path}login/?logout=true{$logoutParameters}"><img src="{$common_images_url}logout.gif"> {"Logout"|_}</a> 58 59 {else} -
branches/newtoken/wifidog/ws/classes/Exceptions/WSException.php
r1427 r1446 50 50 class WSException extends Exception 51 51 { 52 CONST INVALID_PARAMETER = 8801; 53 CONST GENERIC_EXCEPTION = 8800; 54 CONST PROCESS_ERROR = 8802; 55 52 56 // Redefine the exception so message isn't optional 53 public function __construct($message, $code = 0) {57 public function __construct($message, $code = 8800) { 54 58 // some code 55 59 -
branches/newtoken/wifidog/ws/classes/WifidogWS/V1.php
r1427 r1446 43 43 * Web service V1 class 44 44 * 45 * Actions are: 45 * mandatory parameters: 46 * action: get|list|auth 47 * 48 * Each action has its own set of parameters: 49 * 46 50 * get: get some information concerning a given object, identified by its id 51 * parameters: object_class The class of the object to get 52 * object_id The id of the object 53 * fields The list of fields to fetch (absent: all the allowed fields) 54 * id_type (o) Not used yet 55 * 47 56 * list: get some informations concerning a list of objects 48 * auth: verify the users credential. 57 * parameters: object_class The class of objects to list 58 * fields The fields to list for each object 59 * parent_class (o) The class of the parent object (for the nodes of a network, the class would be network) 60 * parent_id (o) The id of the parent object 61 * 62 * auth: verify the users credential. And in part authenticate the user 63 * parameters: username The username to authenticate 64 * password The password 65 * gw_id (o) The gateway id if the request comes from a gateway 66 * gw_address (o) The gateway address as sent in the original request from gateway 67 * gw_port (o) The gateway port as sent from the original request from gateway 68 * from_ip (o) The ip of the user, as can be got from the $_SERVER['REMOTE_ADDR'] variable 69 * mac (o) The user mac as sent in the original request from gateway 49 70 * NOTE: This action DOES NOT authenticate the user on the gateway and hence, DOES NOT grant access to the internet. 50 71 * There is an authentication protocol that needs to be respected (http://dev.wifidog.org/wiki/doc/developer/WiFiDogProtocol_V1) 51 * An authentication token must be generated and the response redirects to the gateway's auth server that redirects to the portal page72 * However, this action will return the url that should be used as a next step of this protocol, so the calling system may do what it must 52 73 * 53 74 * @package WiFiDogAuthServer … … 125 146 } 126 147 148 protected function mapFields($objectClass, $infields = array()) { 149 $fields = array() ; 150 foreach($infields as $field) { 151 if (isset(self::$_allowedFields[$objectClass][$field])) 152 $fields[] = self::$_allowedFields[$objectClass][$field]; 153 else 154 $fields[] = "$field.forbidden"; 155 } 156 return $fields; 157 } 158 127 159 /** 128 160 * This function executes the action requested by the web service … … 132 164 protected function executeAction() { 133 165 if (!isset($this->_action)) { 134 throw new WSException("No action was specified. Please use GET parameter 'action=list|get|auth' to specify an action" );166 throw new WSException("No action was specified. Please use GET parameter 'action=list|get|auth' to specify an action", WSException::INVALID_PARAMETER); 135 167 } 136 168 switch($this->_action) { … … 151 183 case 'auth': 152 184 $gw_id = (isset($this->_params['gw_id']) ? $this->_params['gw_id']:null); 153 $gw_ip = (isset($this->_params['gw_ip']) ? $this->_params['gw_ip']:null); 185 $gw_address = (isset($this->_params['gw_address']) ? $this->_params['gw_address']:null); 186 $gw_port = (isset($this->_params['gw_port']) ? $this->_params['gw_port']:null); 187 $mac = (isset($this->_params['mac']) ? $this->_params['mac']:null); 188 $from = (isset($this->_params['from_ip']) ? $this->_params['from_ip']:null); 154 189 $username = (isset($this->_params['username']) ? $this->_params['username']:''); 155 190 $password = (isset($this->_params['password']) ? $this->_params['password']:''); 156 $this->executeAuth($username, $password, $gw_id, $gw_ ip);191 $this->executeAuth($username, $password, $gw_id, $gw_address, $mac, $gw_port, $from); 157 192 break; 158 193 default: 159 throw new WSException("Action {$this->_action} is not defined. Please use GET parameter 'action=list|get|auth' to specify an action" );194 throw new WSException("Action {$this->_action} is not defined. Please use GET parameter 'action=list|get|auth' to specify an action", WSException::INVALID_PARAMETER); 160 195 break; 161 196 } … … 171 206 * @return unknown_type 172 207 */ 173 protected function executeAuth($username = null, $password = null, $gw_id = null, $gw_ip = null ) {208 protected function executeAuth($username = null, $password = null, $gw_id = null, $gw_ip = null, $mac = null, $gw_port = null, $from = null) { 174 209 $this->_outputArr['auth'] = 0; 175 210 … … 180 215 181 216 if (!is_null($gw_id)) { 182 if (is_null($gw_ip) ) {183 throw new WSException("Missing information on the gateway. Must specify parameter 'gw_ip' if there is a gateway id.");217 if (is_null($gw_ip) || is_null($gw_port) || is_null($from)) { 218 throw new WSException("Missing information on the gateway. You must specify parameter 'gw_address' AND 'gw_port' AND 'from_ip' if the parameter 'gw_id' is specified.", WSException::INVALID_PARAMETER); 184 219 } 185 220 $node = Node::getObjectByGatewayId($gw_id); … … 187 222 $network = $node->getNetwork(); 188 223 } else { 189 throw new WSException("Node identified by $gw_id cannot be found" );224 throw new WSException("Node identified by $gw_id cannot be found", WSException::PROCESS_ERROR); 190 225 } 191 226 } else { … … 198 233 * If this is a splash-only node, then the user is automatically authenticated 199 234 */ 235 $token = null; 200 236 if (!empty($node) && $node->isSplashOnly()) { 201 237 $this->_outputArr['auth'] = 1; 202 238 $user = $network->getSplashOnlyUser(); 239 $token = Token::generateConnectionToken($mac, $network, $node, $user, $from); 240 if (!$token) throw new WSException("User authenticated but cannot generate connection token.", WSException::PROCESS_ERROR); 203 241 } else { 204 242 // Authenticate the user on the requested network … … 209 247 } else { 210 248 $this->_outputArr['auth'] = 1; 211 } 249 if (!is_null($node)) { 250 $token = Token::generateConnectionToken($mac, $network, $node, $user, $from); 251 252 if (!$token) throw new WSException("User authenticated but cannot generate connection token.", WSException::PROCESS_ERROR); 253 } 254 } 255 } 256 if ($this->_outputArr['auth'] == 1 && !is_null($token)) { 257 $this->_outputArr['forwardTo'] = "http://" . $gw_ip . ":" . $gw_port . "/wifidog/auth?token=" . $token; 212 258 } 213 259 } … … 222 268 protected function executeGet($objectClass, $objectId, $fields = array(), $idtype = null) { 223 269 if (is_null($objectClass)) { 224 throw new WSException("Missing parameter 'object_class' in the request." );270 throw new WSException("Missing parameter 'object_class' in the request.", WSException::INVALID_PARAMETER); 225 271 } 226 272 if (is_null($objectId)) { 227 throw new WSException("Missing parameter 'object_id' in the request." );273 throw new WSException("Missing parameter 'object_id' in the request.", WSException::INVALID_PARAMETER); 228 274 } 229 275 if (!in_array($objectClass,self::$_allowedObjectClass)) { 230 throw new WSException("Wrong object class '{$objectClass}' requested. Possible values are " . implode(', ', self::$_allowedObjectClass) );276 throw new WSException("Wrong object class '{$objectClass}' requested. Possible values are " . implode(', ', self::$_allowedObjectClass), WSException::INVALID_PARAMETER); 231 277 } 232 278 … … 247 293 // IF the object still is not found, then return an error 248 294 if (is_null($object)) { 249 throw new WSException("Object of class {$objectClass} with id {$objectId} not found" );295 throw new WSException("Object of class {$objectClass} with id {$objectId} not found", WSException::PROCESS_ERROR); 250 296 } 251 297 298 $fields = $this->mapFields($objectClass, $fields); 252 299 if (empty($fields)) { 253 300 $fields = array_keys(self::$_allowedFields[$objectClass]); … … 255 302 $allowedFields = self::$_allowedFields[$objectClass]; 256 303 304 $this->_outputArr = self::filterRet($object, $fields); 305 /* 257 306 foreach($fields as $field) { 258 307 if (isset($allowedFields[ucfirst(strtolower($field))])) { … … 268 317 } 269 318 } 270 319 */ 271 320 272 321 } … … 282 331 protected function executeList($objectClass, $fields = array(), $parentClass = null, $parentId = null) { 283 332 if (is_null($objectClass)) { 284 throw new WSException("Missing parameter 'object_class' in the request." );333 throw new WSException("Missing parameter 'object_class' in the request.", WSException::INVALID_PARAMETER); 285 334 } 286 335 if (!in_array($objectClass,self::$_allowedObjectClass)) { 287 throw new WSException("Wrong object class '{$objectClass}' requested. Possible values are " . implode(', ', self::$_allowedObjectClass) );336 throw new WSException("Wrong object class '{$objectClass}' requested. Possible values are " . implode(', ', self::$_allowedObjectClass), WSException::INVALID_PARAMETER); 288 337 } 289 338 … … 294 343 if (!is_null($parentId)) { 295 344 if (!in_array($parentClass,self::$_allowedObjectClass)) { 296 throw new WSException("Wrong parent class '{$parentClass}' specified. Possible values are " . implode(', ', self::$_allowedObjectClass) );345 throw new WSException("Wrong parent class '{$parentClass}' specified. Possible values are " . implode(', ', self::$_allowedObjectClass), WSException::INVALID_PARAMETER); 297 346 } 298 347 include_once('classes/'.$parentClass.'.php'); 299 348 $parentObject = call_user_func($parentClass.'::getObject', $parentId); 300 349 } else { 301 throw new WSException("If parent class is specified, must specify 'parent_id'" );350 throw new WSException("If parent class is specified, must specify 'parent_id'", WSException::INVALID_PARAMETER); 302 351 } 303 352 } … … 308 357 } 309 358 } 359 $fields = $this->mapFields($objectClass, $fields); 310 360 if (empty($fields)) { 311 361 $fields = self::$_allowedFields[$objectClass]; 312 } 362 } 313 363 314 364 $this->_outputArr = self::filterRet($objectList, $fields); … … 326 376 } 327 377 $filtered = array(); 378 328 379 foreach($retVals as $key => $value) { 329 380 // If the return is one object we filter, return only the allowed fields … … 339 390 $retFields = array(); 340 391 foreach ($fields as $field) { 341 $methodName = 'get'.$field; 342 if (method_exists($value, $methodName)) { 343 $retFields[$field] = self::filterRet($value->$methodName()); 344 } else { 345 $retFields[$field] = 'unknown'; 346 } 392 $forbiddenfield = explode(".", $field); 393 if (! (count($forbiddenfield) == 2)) { 394 $methodName = 'get'.$field; 395 if (method_exists($value, $methodName)) { 396 397 $retFields[$field] = self::filterRet($value->$methodName()); 398 } else { 399 $retFields[$field] = 'unknown'; 400 } 401 } else 402 $retFields[$forbiddenfield[0]] = 'Not allowed'; 347 403 } 348 404 $filtered[] = $retFields; -
branches/newtoken/wifidog/ws/index.php
r1427 r1446 95 95 $exceptionClass = get_class($e); 96 96 if (!is_null($output)) { 97 echo $output->outputError(array('type' => $exceptionClass, 97 if ($exceptionClass == 'WSException') { 98 echo $output->outputError(array('type' => $exceptionClass, 99 'message' => sprintf(_("Web service exception: %s (%s)"), $e->getMessage(), $e->getCode()))); 100 } else 101 echo $output->outputError(array('type' => $exceptionClass, 98 102 'message' => sprintf(_("Detailed error was: Uncaught %s %s (%s) thrown in file %s, line %d"),get_class($e), $e->getMessage(), $e->getCode(), $e->getFile(), $e->getLine()))); 99 103 } else { 100 echo sprintf(_("Detailed error was: Uncaught %s %s (%s) thrown in file %s, line %d"),get_class($e), $e->getMessage(), $e->getCode(), $e->getFile(), $e->getLine()); 104 if ($exceptionClass == 'WSException') { 105 echo sprintf(_("Web service exception: %s => %s (%s)"),get_class($e), $e->getMessage(), $e->getCode(), $e->getFile(), $e->getLine()); 106 } else 107 echo sprintf(_("Detailed error was: Uncaught %s %s (%s) thrown in file %s, line %d"),get_class($e), $e->getMessage(), $e->getCode(), $e->getFile(), $e->getLine()); 101 108 } 102 109 … … 105 112 set_exception_handler('wifidog_exception_handler'); 106 113 107 throw (new WSException(_("The Wifidog API module is not fit for production yet. The source code has been released to share ideas and help development, but it has not been thoroughly tested yet and may represent a security issue for now. If you'd like to test the module, you can do so by commenting this line in the auth server's source code. But it is highly not advised to do so in a production environment for now. Please stay tuned for more development")));114 //throw (new WSException(_("The Wifidog API module is not fit for production yet. The source code has been released to share ideas and help development, but it has not been thoroughly tested yet and may represent a security issue for now. If you'd like to test the module, you can do so by commenting this line in the auth server's source code. But it is highly not advised to do so in a production environment for now. Please stay tuned for more development"))); 108 115 109 116 $service->setParams($_GET);
