Changeset 1446

Show
Ignore:
Timestamp:
02/11/10 17:34:27 (3 years ago)
Author:
gbastien
Message:

* Merged recent changes in the trunk into this branch
* New token architecture not yet fully functional, nor tested, but ...

  • can now edit token templates for different context of tokens (from the edit netork interface at the bottom of page)
  • Users connected through a wifidog gateway can view their connection token information
Location:
branches/newtoken
Files:
2 added
26 modified

Legend:

Unmodified
Added
Removed
  • branches/newtoken/CHANGELOG

    r1436 r1446  
    11# $Id$ 
    22 
    3 2009-12-17 
     32010-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 
     82010-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 
     142009-12-17 Geneviève Bastien <gbastien@versatic.net> 
    415 * Code refactoring: Network, NodeGroup, Node inherit from HotspotGraphElement (#677) 
    516 
    6 2009-12-08 
     172009-12-08 Geneviève Bastien <gbastien@versatic.net> 
    718 * 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) 
    819 * Login and signup and logout script now receive the mac address as parameter (#675) 
  • branches/newtoken/wifidog/admin/generic_object_admin.php

    r1424 r1446  
    7474$supportsPreview = true; 
    7575$supportsDeletion = true; 
     76$readOnly = false; 
    7677/* 
    7778 * Check for the object class to use 
     
    357358            case "ContentTypeFilter" : 
    358359            case "ProfileTemplate" : 
     360            case "Connection": 
     361            case "TokenTemplate": 
    359362                $supportsPreview = false; 
    360363                break; 
     
    367370        switch ($_REQUEST['object_class']) { 
    368371            case "User" : 
     372            case "Connection": 
    369373                $supportsDeletion = false; 
    370374                break; 
     
    379383                break; 
    380384        } 
     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        
    381396 
    382397        if (!$object) { 
     
    396411        $html .= $object->getAdminUI(); 
    397412        $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        } 
    400417 
    401418        if ($supportsDeletion) { 
  • branches/newtoken/wifidog/auth/index.php

    r1419 r1446  
    5252require_once('classes/Network.php'); 
    5353require_once('classes/User.php'); 
     54require_once('classes/Connection.php'); 
    5455$db = AbstractDb::getObject(); 
    5556$auth_response = ACCOUNT_STATUS_DENIED; 
     
    6061{ 
    6162    $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     
    6377    if($dbRetval==false){ 
    6478        $auth_message .= "| Error: couldn't retrieve the requested token: $token because of a SQL error. "; 
    6579        $auth_response = ACCOUNT_STATUS_ERROR; 
    66     } 
     80    }*/ 
    6781} 
    6882else { 
  • branches/newtoken/wifidog/classes/AbstractDb.php

    r1445 r1446  
    357357    { 
    358358        // WARNING : magic quotes must be off 
    359         if (is_null($string)) 
    360             return "null"; 
    361359        return pg_escape_string($string); 
    362360    } 
  • branches/newtoken/wifidog/classes/Authenticator.php

    r1445 r1446  
    358358        // Stop traffic counters update 
    359359        $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"; 
    361361        $sql .= "UPDATE tokens SET token_status='".TOKEN_USED."' FROM connections WHERE connections.token_id=tokens.token_id AND conn_id='{$conn_id}';\n"; 
    362362         
  • branches/newtoken/wifidog/classes/ContentTypeFilter.php

    r1421 r1446  
    288288 
    289289                !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=''; 
    291291                 
    292292                $additional_where = $db->escapeString($additional_where); 
  • branches/newtoken/wifidog/classes/HotspotGraph.php

    r1436 r1446  
    5656{ 
    5757 
     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     
    5871    /** 
    5972     * Gets recursively all parents of the given object 
  • branches/newtoken/wifidog/classes/HotspotGraphElement.php

    r1436 r1446  
    116116     * @access public 
    117117     */ 
    118     public static function createNewObject($element_id, $element_type) 
     118    public static function createNewObject($element_id, $element_type, $parent_element = null) 
    119119    { 
    120120        $db = AbstractDb::getObject(); 
     
    130130        } 
    131131        $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         
    132141        return $object; 
    133142    } 
  • branches/newtoken/wifidog/classes/Mail.php

    r1424 r1446  
    368368         */ 
    369369        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            } 
    371376            require_once ($phpmailerPath.'class.phpmailer.php'); 
    372377            require_once ($phpmailerPath.'class.smtp.php'); 
  • branches/newtoken/wifidog/classes/MainUI.php

    r1435 r1446  
    329329        // Get all network content and node "everywhere" content 
    330330        $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') "; 
    333331        $node = Node :: getCurrentNode(); 
    334         $sql_node = null; 
     332        // Get all the parent objects of the node 
    335333        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"; 
    342352        $db->execSql($sql, $content_rows, false); 
    343353        if ($content_rows) { 
  • branches/newtoken/wifidog/classes/Network.php

    r1436 r1446  
    5656require_once('classes/Security.php'); 
    5757require_once('classes/HotspotGraphElement.php'); 
     58require_once('classes/TokenTemplate.php'); 
     59 
    5860 
    5961/** 
     
    688690            } 
    689691        } 
     692        $params = array_map('trim',$params); 
    690693        return call_user_func_array(array (new ReflectionClass($this->_row['network_authenticator_class']), 'newInstance'), $params); 
    691694 
     
    16941697         * Content management 
    16951698         */ 
    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);*/ 
    17001699         
    17011700        $html .= parent::getContentAdminUI(); 
     
    19281927        $html .= InterfaceElements::generateAdminSectionContainer("network_profile_templates", $title, $data); 
    19291928         
     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         
    19301935        // objects hierarchy 
    19311936        $html .= parent::getGraphAdminUI($this); 
     
    19501955        // Content management 
    19511956        parent::processContentAdminUI(); 
    1952         /* $name = "network_".$this->_id."_content"; 
    1953         Content :: processLinkedContentUI($name, 'network_has_content', 'network_id', $this->_id);*/ 
    19541957 
    19551958        // name 
     
    20692072        ProfileTemplate :: processLinkedProfileTemplateUI($name, 'network_has_profile_templates', 'network_id', $this->_id); 
    20702073         
     2074        // Token templates 
     2075        $name = "network_".$this->_id."_token_templates"; 
     2076        TokenTemplate :: processTemplatesForNetworkUI($name, $this); 
     2077         
    20712078        parent::processGraphAdminUI($errMsg, $this); 
    20722079        if(!empty($errMsg)) { 
     
    20822089        } 
    20832090    } 
    2084  
    2085     /** 
    2086      * Add network-wide content to this network 
    2087      * 
    2088      * @param object Content object 
    2089      * 
    2090      * @return void 
    2091      * 
    2092      * @access public 
    2093      */ 
    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 network 
    2105      * 
    2106      * @param object Content object 
    2107      * 
    2108      * @return void 
    2109      * 
    2110      * @access public 
    2111      */ 
    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  
    21212091 
    21222092    /** 
  • branches/newtoken/wifidog/classes/Node.php

    r1436 r1446  
    281281        } 
    282282 
    283         HotspotGraphElement::createNewObject($node_id, 'Node'); 
     283        HotspotGraphElement::createNewObject($node_id, 'Node', $network); 
    284284         
    285285        $object = self::getObject($node_id); 
     
    11851185 
    11861186        //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        
    11911188        $html .= parent::getContentAdminUI(); 
    11921189             
     
    14071404        // Content processing 
    14081405        parent::processContentAdminUI(); 
    1409         /*$name = "node_{$node_id}_content"; 
    1410         Content::processLinkedContentUI($name, 'node_has_content', 'node_id', $this->id);*/ 
    14111406 
    14121407        // Name 
     
    15891584    } 
    15901585 
    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  
    16101586    /** 
    16111587     * 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  
    170170        } 
    171171         
    172         HotspotGraphElement::createNewObject($node_group_id, 'NodeGroup'); 
     172        HotspotGraphElement::createNewObject($node_group_id, 'NodeGroup', $network); 
    173173 
    174174        $object = self::getObject($node_group_id); 
     
    538538    } 
    539539 
    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  
    560540    /** Reloads the object from the database.  Should normally be called after a set operation */ 
    561541    protected function refresh() 
  • branches/newtoken/wifidog/classes/Role.php

    r1421 r1446  
    485485 
    486486        $retval = false; 
    487         if (Security::hasPermission('SERVER_PERM_EDIT_ROLES', Server::getServer())) { 
     487        if (Security::hasPermission(Permission::P('SERVER_PERM_EDIT_ROLES'), Server::getServer())) { 
    488488            $db = AbstractDb::getObject(); 
    489489            $id = $db->escapeString($this->getId()); 
  • branches/newtoken/wifidog/classes/SmartyWifidog.php

    r1421 r1446  
    189189     Node::assignSmartyValues($this); 
    190190     User::assignSmartyValues($this); 
     191     Token::assignSmartyValues($this); 
    191192     return parent::fetch($resource_name, $cache_id, $compile_id, $display); 
    192193    } 
  • branches/newtoken/wifidog/classes/Token.php

    r1445 r1446  
    5555class Token  
    5656{ 
    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) { 
    5876        $retval = false; 
    5977        if ($user->isUserValid()) { 
    6078            $db = AbstractDb::getObject(); 
    61             $session = Session::getObject(); 
    62              
     79                         
    6380            // Delete unused connection token 
    6481 
    6582            $token = self :: generateToken(); 
    66             if ($_SERVER['REMOTE_ADDR']) { 
     83            if (is_null($node_ip) && $_SERVER['REMOTE_ADDR']) { 
    6784                $node_ip = $db->escapeString($_SERVER['REMOTE_ADDR']); 
    6885            } 
    6986             
    70             if ($session && $node_ip && $session->get(SESS_NODE_ID_VAR)) { 
     87            if ($node_ip && $node) { 
    7188                //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); 
    7491                if($abuseControlFault) { 
    7592                    throw new Exception ($abuseControlFault); 
     
    8299                $sql = "DELETE FROM connections USING tokens "."WHERE tokens.token_id=connections.token_id AND token_status='".TOKEN_UNUSED."' AND user_id = '".$user->getId()."';\n"; 
    83100                $db->execSqlUpdate($sql, false); 
    84                 // TODO:  Try to find a reusable token before creating a brand new one! 
    85101 
    86102               // Check if we have any token templates 
    87                 // TODO: token templates should be from a specific template and there should always be a template 
    88103                $templates = TokenTemplate::getTemplatesForNetwork($network); 
    89104                if (count($templates) == 0) { 
    90105                    // 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 
    92107                    $token = self :: generateToken(); 
    93108                    $sql = "INSERT INTO tokens (token_owner, token_issuer, token_id, token_status) VALUES ('" . $user->getId() . "', '" . $user->getId() . "', '$token', '" . TOKEN_UNUSED . "');\n"; 
     
    144159                                $max_incoming_data_value = (!is_null($template->getMaxIncomingData())?$template->getMaxIncomingData():"null"); 
    145160                                $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())) 
    147165                                    $expiry_date = "CURRENT_TIMESTAMP + '" . $template->getMaxUsageDuration() . "'"; 
    148166                                elseif (!is_null($template->getMaxWallClockDuration())) 
     
    164182            } 
    165183        } 
    166         
     184        self::setCurrentToken($retval); 
    167185        return $retval; 
    168186    }  
    169187     
    170                 /** 
    171      * Generate a new access token for the specified user 
    172      * 
    173      * @param string $validated_user       The user to generate a token for 
    174      * 
    175      * @param string $creator              The user generating the token 
    176      * 
    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 create 
    179      *                                     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 tokenid 
    184      * 
    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      
    195188    public static function generateToken() { 
    196189        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        }*/ 
    197259    } 
    198260} 
  • branches/newtoken/wifidog/classes/TokenTemplate.php

    r1445 r1446  
    4848require_once('classes/Token.php'); 
    4949 
     50// Token templates context constants 
     51define('TT_CONTEXT_USER_ALLOWED', 1); 
     52define('TT_CONTEXT_USER_VALIDATING', 2); 
     53define('TT_CONTEXT_USER_FORGOT_PASSWORD', 3); 
     54define('TT_CONTEXT_GUEST', 4); 
     55define('TT_CONTEXT_SPLASH_ONLY', 5); 
     56 
     57 
    5058/** 
    5159 * Abstract a token template 
     
    7785    } 
    7886 
    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; 
    81113    } 
    82114     
     
    120152    } 
    121153 
    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 
    144162    } 
    145163 
     
    235253    } 
    236254 
    237     function getCreationDate() { 
    238         return $this->_row['token_template_creation_date']; 
    239     } 
    240  
    241     public function setCreationDate($value) { 
    242         // Init values 
    243         $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      
    254255    function getMaxIncomingData() { 
    255256        return $this->_row['token_max_incoming_data']; 
     
    313314        if ($value != $this->getMaxConnectionDuration()) { 
    314315            $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); 
    317318            $this->refresh(); 
    318319        } 
     
    330331        if ($value != $this->getMaxUsageDuration()) { 
    331332            $db = AbstractDb::getObject(); 
    332             $value = $db->escapeString($value); 
     333            $value = ($value != ''?"'".$db->escapeString($value)."'": 'null'); 
    333334            $retVal = $db->execSqlUpdate("UPDATE token_templates SET token_max_usage_duration = '{$value}' WHERE token_template_id = '{$this->getId()}'", false); 
    334335            $this->refresh(); 
     
    338339     
    339340    function getMaxWallClockDuration() { 
    340         return $this->_row['token_max_usage_duration']; 
     341        return $this->_row['token_max_wall_clock_duration']; 
    341342    } 
    342343 
     
    347348        if ($value != $this->getMaxWallClockDuration()) { 
    348349            $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); 
    351352            $this->refresh(); 
    352353        } 
     
    363364        if ($value != $this->getMaxAge()) { 
    364365            $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(); 
    365382            $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); 
    367400            $this->refresh(); 
    368401        } 
     
    386419        return $retVal; 
    387420    } 
     421     
    388422 
    389423    public static function generateToken() { 
     
    443477        return $html; 
    444478    } 
    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 
    451489     */ 
    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 
    468565    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         
    469571        /* 
    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 
    562681    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         
    619721    } 
    620722     
     
    626728     */ 
    627729    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; 
    629755       /* $retval = false; 
    630756        // A new token can be generated if 
     
    687813    } 
    688814 
    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 template 
    700          * 
    701          * These values are used in the default template of WiFoDog but could be 
    702          * used in a customized template to restrict certain links to specific 
    703          * user access levels.  Note however that they will all be deprecateb by the 
    704          * 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 know 
    711             $smarty->assign('debugRequested', true); 
    712             $smarty->assign('debugOutput', print_r($_REQUEST, true)); 
    713         }*/ 
    714     } 
    715815} 
    716816 
  • branches/newtoken/wifidog/classes/User.php

    r1445 r1446  
    172172        return $object; 
    173173    } 
     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    } 
    174198 
    175199    /** Instantiate a user object 
     
    653677                $node_id = $db->escapeString($session->get(SESS_NODE_ID_VAR)); 
    654678                $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); 
    655717                if($abuseControlFault) { 
    656718                    throw new Exception ($abuseControlFault); 
     
    857919            if (!empty ($_REQUEST[$name])) { 
    858920                $username = $_REQUEST[$name]; 
    859                 return self :: getUserByUsernameOrEmail($username, $errMsg); 
     921                return self :: getUserByUsernameOrEmailAndOrigin($username, $network, $errMsg); 
    860922            } else 
    861923            return null; 
  • branches/newtoken/wifidog/include/common.php

    r1428 r1446  
    156156define('LOGOUT_REASON_GARBAGE_COLLECTED', 3); 
    157157define('LOGOUT_REASON_UNKNOWN', 0); 
     158define('LOGOUT_REASON_USER_LOGOUT', 1); 
     159 
    158160/* End of Other constants */ 
    159161 
  • branches/newtoken/wifidog/include/schema_validate.php

    r1445 r1446  
    15291529        printUpdateVersion($new_schema_version); 
    15301530        $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"; 
    15311535         
    15321536        //$networks = Network::getAllNetworks(); 
     
    15351539        foreach ($networks as $network) { 
    15361540            $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 "; 
    15381542        } 
     1543         
    15391544    } 
    15401545     
  • branches/newtoken/wifidog/login/index.php

    r1445 r1446  
    197197        $user = $network->getSplashOnlyUser(); 
    198198        //$token = $user->generateConnectionToken($mac); 
    199         $token = Token::generateConnectionToken($mac, $network, $user); 
     199        $token = Token::generateConnectionToken($mac, $network, $node, $user); 
    200200        User::setCurrentUser($user); 
    201201        header("Location: http://" . $gw_address . ":" . $gw_port . "/wifidog/auth?token=" . $token); 
     
    222222            // Login from a gateway, redirect to the gateway to activate the token 
    223223            // $token = $user->generateConnectionToken($mac); 
    224             $token = Token::generateConnectionToken($mac, $network, $user); 
     224            $token = Token::generateConnectionToken($mac, $network, $node, $user); 
    225225            if(!$token) 
    226226            { 
     
    280280$html .= "<h1>"._("I'm having difficulties:")."</h1>\n"; 
    281281$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"; 
    285285$html .= "</ul>\n"; 
    286286$html .= "</div>\n"; 
     
    309309 
    310310// 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 
    315312if ($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 
     324foreach($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"; 
    322331$db->execSql($sql, $content_rows, false); 
    323332if ($content_rows) { 
     
    329338    } 
    330339} 
     340$showMoreLink = false; 
     341 
    331342 
    332343/* 
  • branches/newtoken/wifidog/signup.php

    r1435 r1446  
    233233            // Make sure the user IDs match 
    234234            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); 
    236238 
    237239                $redirURL = "http://" . $gw_address . ":" . $gw_port . "/wifidog/auth?token=" . $token; 
  • branches/newtoken/wifidog/templates/classes/MainUI_ToolContent.tpl

    r1308 r1446  
    5555                    <div>{"Logged in as"|_}: {$userListUI}</div> 
    5656                    <a id="preferences_link" href="{$base_ssl_path}admin/generic_object_admin.php?object_id={$userId}&amp;object_class=User&amp;action=edit"><img src="{$common_images_url}profile.gif">&nbsp;{"Profile / Settings"|_}</a> 
     57                    {if $hasConnection}<a id="preferences_link" href="{$base_ssl_path}admin/generic_object_admin.php?object_id={$tokenId}&amp;object_class=Connection&amp;action=edit"><img src="{$common_images_url}profile.gif">&nbsp;{"Connection information"|_}</a>{/if} 
    5758                    <a id="logout_link" href="{$base_ssl_path}login/?logout=true{$logoutParameters}"><img src="{$common_images_url}logout.gif">&nbsp;{"Logout"|_}</a> 
    5859                {else} 
  • branches/newtoken/wifidog/ws/classes/Exceptions/WSException.php

    r1427 r1446  
    5050class WSException extends Exception 
    5151{ 
     52    CONST INVALID_PARAMETER = 8801; 
     53    CONST GENERIC_EXCEPTION = 8800; 
     54    CONST PROCESS_ERROR = 8802; 
     55     
    5256    // Redefine the exception so message isn't optional 
    53     public function __construct($message, $code = 0) { 
     57    public function __construct($message, $code = 8800) { 
    5458        // some code 
    5559    
  • branches/newtoken/wifidog/ws/classes/WifidogWS/V1.php

    r1427 r1446  
    4343 * Web service V1 class 
    4444 * 
    45  * Actions are: 
     45 * mandatory parameters: 
     46 * action: get|list|auth 
     47 * 
     48 * Each action has its own set of parameters: 
     49 *  
    4650 * 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 *                
    4756 * 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 
    4970 *     NOTE: This action DOES NOT authenticate the user on the gateway and hence, DOES NOT grant access to the internet. 
    5071 *           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 page 
     72 *           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 
    5273 * 
    5374 * @package    WiFiDogAuthServer 
     
    125146    } 
    126147     
     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     
    127159    /** 
    128160     * This function executes the action requested by the web service 
     
    132164    protected function executeAction() { 
    133165        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);  
    135167        } 
    136168        switch($this->_action) { 
     
    151183            case 'auth': 
    152184                $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); 
    154189                $username = (isset($this->_params['username']) ? $this->_params['username']:''); 
    155190                $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); 
    157192                break; 
    158193            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); 
    160195                break; 
    161196        } 
     
    171206     * @return unknown_type 
    172207     */ 
    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) { 
    174209        $this->_outputArr['auth'] = 0; 
    175210         
     
    180215         
    181216        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); 
    184219            } 
    185220            $node = Node::getObjectByGatewayId($gw_id); 
     
    187222                $network = $node->getNetwork(); 
    188223            } 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); 
    190225            } 
    191226        } else { 
     
    198233         * If this is a splash-only node, then the user is automatically authenticated 
    199234         */ 
     235        $token = null; 
    200236        if (!empty($node) && $node->isSplashOnly()) { 
    201237            $this->_outputArr['auth'] = 1; 
    202238            $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); 
    203241        } else { 
    204242            // Authenticate the user on the requested network 
     
    209247            } else { 
    210248                $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; 
    212258        } 
    213259    } 
     
    222268    protected function executeGet($objectClass, $objectId, $fields = array(), $idtype = null) { 
    223269        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); 
    225271        } 
    226272        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); 
    228274        } 
    229275        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); 
    231277        } 
    232278         
     
    247293        // IF the object still is not found, then return an error 
    248294        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); 
    250296        } 
    251297   
     298        $fields = $this->mapFields($objectClass, $fields); 
    252299        if (empty($fields)) { 
    253300            $fields = array_keys(self::$_allowedFields[$objectClass]); 
     
    255302        $allowedFields = self::$_allowedFields[$objectClass]; 
    256303         
     304        $this->_outputArr = self::filterRet($object, $fields); 
     305        /* 
    257306        foreach($fields as $field) { 
    258307            if (isset($allowedFields[ucfirst(strtolower($field))])) { 
     
    268317            } 
    269318        } 
    270          
     319        */ 
    271320         
    272321    } 
     
    282331    protected function executeList($objectClass, $fields = array(), $parentClass = null, $parentId = null) { 
    283332        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); 
    285334        } 
    286335        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); 
    288337        } 
    289338         
     
    294343            if (!is_null($parentId)) { 
    295344                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); 
    297346                } 
    298347                include_once('classes/'.$parentClass.'.php'); 
    299348                $parentObject = call_user_func($parentClass.'::getObject', $parentId); 
    300349            } 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); 
    302351            } 
    303352        } 
     
    308357            } 
    309358        } 
     359        $fields = $this->mapFields($objectClass, $fields); 
    310360        if (empty($fields)) { 
    311361            $fields = self::$_allowedFields[$objectClass]; 
    312         } 
     362        }  
    313363 
    314364        $this->_outputArr = self::filterRet($objectList, $fields); 
     
    326376        } 
    327377        $filtered = array(); 
     378 
    328379        foreach($retVals as $key => $value) { 
    329380            // If the return is one object we filter, return only the allowed fields 
     
    339390                    $retFields = array(); 
    340391                    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'; 
    347403                    } 
    348404                    $filtered[] = $retFields; 
  • branches/newtoken/wifidog/ws/index.php

    r1427 r1446  
    9595    $exceptionClass = get_class($e); 
    9696    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,  
    98102                                    '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()))); 
    99103    } 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()); 
    101108    } 
    102109 
     
    105112set_exception_handler('wifidog_exception_handler'); 
    106113 
    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"))); 
    108115 
    109116$service->setParams($_GET);