Changeset 20269

Show
Ignore:
Timestamp:
09/30/08 13:59:10 (5 years ago)
Author:
gen
Message:

adminプ pluginとか入れてみました(はぁと

Location:
events/phpframework/akelos/trunk
Files:
219 added
5 removed
9 modified

Legend:

Unmodified
Added
Removed
  • events/phpframework/akelos/trunk/app/installers/user_installer.php

    r19814 r20269  
    11<?php 
    2 /** 
    3 * This is the User Installer. And installer allows you to perform 
    4 * database migrations in the same way your file versions are managed by subversion. 
    5 * 
    6 * You just need to create up and down methods for each database version. 
    7 * 
    8 * Once you've added the database structure, you just need to call 
    9 * 
    10 * ./script/migrate User install 
    11 * 
    12 * And your database will be upgraded to the latest revision 
    13 */ 
    142class UserInstaller extends AkInstaller 
    153{ 
    164    function up_1() 
    175    { 
     6        /* admin plugin 
     7        $this->createTable('users', ' 
     8          id, 
     9          login string(40) not null idx, 
     10          email string(50) not null idx, 
     11          password string(40) not null, 
     12          password_salt string(16) not null, 
     13          last_login_at, 
     14          is_enabled bool default 1 
     15        ');  
     16         */ 
     17 
    1818        $this->createTable('users', " 
    1919          id, 
    2020          name string(100) notnull, 
    21           email string(255) notnull, 
     21          login string(100) notnull index, 
     22          email string(255) notnull index, 
    2223          password string(64) notnull, 
     24          password_salt string(16) notnull, 
     25          last_login_at, 
    2326          image string null, 
    2427          is_private, 
  • events/phpframework/akelos/trunk/app/locales/user/en.php

    r20135 r20269  
    3737$dictionary['Create a Free Twitter Account'] = 'Create a Free Twitter Account'; 
    3838 
     39// 2008-09-30 10:21:31 
     40 
     41 
     42$dictionary['email %email already in use'] = 'email %email already in use'; 
     43$dictionary['login %login already in use'] = 'login %login already in use'; 
     44$dictionary['can\'t be blank'] = 'can\'t be blank'; 
     45$dictionary['Invalid email address'] = 'Invalid email address'; 
     46$dictionary['pick a shorter login'] = 'pick a shorter login'; 
     47$dictionary['pick a longer name'] = 'pick a longer name'; 
     48$dictionary['pick a shorter password'] = 'pick a shorter password'; 
     49$dictionary['pick a longer password'] = 'pick a longer password'; 
     50$dictionary['Must match confirmation'] = 'Must match confirmation'; 
     51 
    3952 
    4053?> 
  • events/phpframework/akelos/trunk/app/locales/user/ja.php

    r20135 r20269  
    3737$dictionary['Create a Free Twitter Account'] = 'Create a Free Twitter Account'; 
    3838 
     39// 2008-09-30 10:21:31 
     40 
     41 
     42$dictionary['email %email already in use'] = 'email %email already in use'; 
     43$dictionary['login %login already in use'] = 'login %login already in use'; 
     44$dictionary['can\'t be blank'] = 'can\'t be blank'; 
     45$dictionary['Invalid email address'] = 'Invalid email address'; 
     46$dictionary['pick a shorter login'] = 'pick a shorter login'; 
     47$dictionary['pick a longer name'] = 'pick a longer name'; 
     48$dictionary['pick a shorter password'] = 'pick a shorter password'; 
     49$dictionary['pick a longer password'] = 'pick a longer password'; 
     50$dictionary['Must match confirmation'] = 'Must match confirmation'; 
     51 
    3952 
    4053?> 
  • events/phpframework/akelos/trunk/app/models/user.php

    r19968 r20269  
    11<?php 
     2 
     3 
     4defined('AK_DEFAULT_USER_ROLE') ? null : define('AK_DEFAULT_USER_ROLE', 'Registered user'); 
     5 
    26class User extends ActiveRecord 
    37{ 
    4     public static function login($params) 
    5     { 
     8    var $habtm = array('roles' => array('unique'=>true)); 
     9 
     10    /** 
     11     * @access private 
     12     */ 
     13    var $__initial_attributes = array(); 
     14    var $__requires_password_confirmation = true; 
     15 
     16    /** 
     17     * We need to get initial values when instantiating to know if attributes like password have been changed 
     18     */ 
     19    function __construct() 
     20    { 
     21        $attributes = (array)func_get_args(); 
     22        $this->__initial_attributes = isset($attributes[1]) && is_array($attributes[1]) ? $attributes[1] : array(); 
     23        return $this->init($attributes); 
     24    } 
     25 
     26    /** 
     27     * Main authentication method 
     28     *  
     29     * @param string $login user name or password 
     30     * @param string $password 
     31     * @return False if not found or not enabled, User instance if succedes 
     32     */ 
     33    function authenticate($login, $password) 
     34    { 
     35        $UserInstance =& new User(); 
     36 
     37        $login_or_email = preg_match(AK_EMAIL_REGULAR_EXPRESSION, $login) ? 'email' : 'login'; 
     38 
     39        if($User =& $UserInstance->find('first', array('conditions'=>array($login_or_email.' = ? AND __owner.is_enabled = ? AND _roles.is_enabled = ?', $login, true, true), 'include'=>'role')) && $User->isValidPassword($password)){ 
     40            $User->set('last_login_at', Ak::getDate()); 
     41            $User->save(); 
     42            return $User; 
     43        } 
    644        return false; 
    745    } 
    846 
    9     public function logout() 
    10     { 
     47    function signUp($user_details, $options = array()) 
     48    { 
     49        $user_details['is_enabled'] = true; 
     50        $this->setAttributes($user_details); 
     51        if($this->save()){ 
     52            $this->setDefaultRole(); 
     53            $this->sendSignupMessage(array( 
     54            'login' => $user_details['login'], 
     55            'password' => $user_details['password'], 
     56            )); 
     57            return true; 
     58        } 
     59        return false; 
     60    } 
     61 
     62    function setDefaultRole() 
     63    { 
     64        $settings = Ak::getSettings('admin'); 
     65        if(!empty($settings['account_settings']['default_role'])){ 
     66            $this->role->load(); 
     67            $Role = new Role(); 
     68            if($DefaultRole = $Role->findFirstBy('name', $settings['account_settings']['default_role'])){ 
     69                $this->role->set($DefaultRole); 
     70            } 
     71        } 
     72    } 
     73 
     74    function sendSignupMessage($options = array()) 
     75    { 
     76        $default_options = array( 
     77        'signup_message' => 'registration_details' 
     78        ); 
     79        $options = array_merge($default_options, $options); 
     80        if(!empty($options['signup_message'])){ 
     81            Ak::import_mailer('account_mailer'); 
     82            $Mailer =& new AccountMailer(); 
     83            $Mailer->_login = $options['login']; 
     84            $Mailer->_password = $options['password']; 
     85            $Mailer->deliver($options['signup_message'], $this->get('email')); 
     86        } 
     87    } 
     88 
     89 
     90    // Validation 
     91    // --------------- 
     92 
     93    function validate() 
     94    { 
     95        $this->validatesUniquenessOf('email', array('message'=>$this->t('email %email already in use', array('%email'=>$this->get('email'))))); 
     96        $this->validatesUniquenessOf('login', array('message'=>$this->t('login %login already in use', array('%login'=>$this->get('login'))))); 
     97        $this->validatesPresenceOf(array('login','email')); 
     98        $this->validatesFormatOf('email', AK_EMAIL_REGULAR_EXPRESSION, $this->t('Invalid email address')); 
     99        $this->validatesLengthOf('login', array('in'=>array(3, 40), 'too_long' => $this->t('pick a shorter login'), 'too_short' => $this->t('pick a longer name'))); 
     100        $this->validatesLengthOf('password', array('in'=>array(4, 40), 'too_long' => $this->t('pick a shorter password'), 'too_short' => $this->t('pick a longer password'))); 
     101    } 
     102 
     103    function validatesPassword() 
     104    { 
     105        $requires_password_confirmation = $this->hasAttributeBeenModified('password') ? $this->__requires_password_confirmation : false; 
     106        $this->validatesPresenceOf($requires_password_confirmation ? array('password','password_confirmation') : array('password')); 
     107        $requires_password_confirmation ? $this->validatesConfirmationOf('password', $this->t('Must match confirmation')) : null; 
     108        return strlen($this->getErrorsOn('password').$this->getErrorsOn('password_confirmation')) == 0; 
     109    } 
     110 
     111    function needsPasswordLengthValidation() 
     112    { 
     113        return $this->isNewRecord() || !empty($this->password); 
     114    } 
     115 
     116    function needsEmailValidation() 
     117    { 
     118        return empty($this->_byspass_email_validation); 
     119    } 
     120 
     121    function validatesExistanceOfOriginalPasswordWhenUpdatingLogin() 
     122    { 
     123        if($this->hasAttributeBeenModified('login')){ 
     124            if(!$this->isValidPassword($this->get('password'), true, true)){ 
     125                $this->addError('login', $this->t('can\' be modified unless you provide a valid password.')); 
     126            }else{ 
     127                $this->set('password_confirmation', $this->get('password')); 
     128            } 
     129        } 
     130    } 
     131 
     132    function isValidPassword($password, $hash_password = true, $hash_using_original_name = false) 
     133    { 
     134        return $this->getPreviousValueForAttribute('password') == ($hash_password ? $this->sha1($password, $hash_using_original_name) : $password); 
     135    } 
     136 
     137 
     138    // Triggers 
     139    // --------------- 
     140 
     141    function beforeCreate() 
     142    { 
     143        $this->validatesPassword(); 
     144        $this->encryptPassword(); 
     145        return !$this->hasErrors(); 
     146    } 
     147 
     148    function beforeDestroy() 
     149    { 
     150        return !$this->hasRootPrivileges(); 
     151    } 
     152 
     153    function beforeUpdate() 
     154    { 
     155        $this->validatesExistanceOfOriginalPasswordWhenUpdatingLogin(); 
     156        $this->validatesPassword(); 
     157        $this->_encryptPasswordUnlessEmptyOrUnchanged(); 
     158        return !$this->hasErrors(); 
     159    } 
     160 
     161    function afterSave() 
     162    { 
     163        $this->__initial_attributes = $this->getAttributes(); 
    11164        return true; 
    12165    } 
     166 
     167    function afterCreate() 
     168    { 
     169        if(empty($this->roles)){ 
     170            $this->role->load(); 
     171            $Role =& new Role(); 
     172            if($Role =& $Role->findFirstBy('name', AK_DEFAULT_USER_ROLE)){ 
     173                $this->role->set($Role); 
     174            } 
     175        } 
     176        return true; 
     177    } 
     178 
     179 
     180 
     181    // Enabling disabling accounts 
     182    // -------------------------- 
     183 
     184 
     185    function enable() 
     186    { 
     187        $this->updateAttribute('is_enabled', true); 
     188    } 
     189 
     190    function disable() 
     191    { 
     192        $this->updateAttribute('is_enabled', false); 
     193    } 
     194 
     195 
     196 
     197 
     198    // Inspecting original values 
     199    // -------------------------- 
     200 
     201 
     202    function hasAttributeBeenModified($attribute) 
     203    { 
     204        return $this->getPreviousValueForAttribute($attribute) != $this->get($attribute); 
     205    } 
     206 
     207    function getPreviousValueForAttribute($attribute) 
     208    { 
     209        return $this->hasColumn($attribute) && isset($this->__initial_attributes[$attribute]) ? $this->__initial_attributes[$attribute] : null; 
     210    } 
     211 
     212 
     213    // Hashing 
     214    // ----------------------- 
     215 
     216    function encryptPassword() 
     217    { 
     218        $this->set('password', $this->sha1($this->get('password'))); 
     219    } 
     220 
     221    function sha1($phrase, $use_original_login = false) 
     222    { 
     223        $login = $use_original_login ? $this->getPreviousValueForAttribute('login') : $this->get('login'); 
     224        empty($this->password_salt) ? $this->set('password_salt', Ak::randomString(16)) : null; 
     225        return sha1($this->get('password_salt').$phrase.$login); 
     226    } 
     227 
     228    function isTokenValid($token) 
     229    { 
     230        return $this->getToken() == $token; 
     231    } 
     232 
     233    function _encryptPasswordUnlessEmptyOrUnchanged() 
     234    { 
     235        if($this->hasAttributeBeenModified('password') || $this->get('password') == ''){ 
     236            $this->encryptPassword(); 
     237        }else{ 
     238            $this->set('password', $this->getPreviousValueForAttribute('password')); 
     239        } 
     240    } 
     241 
     242 
     243 
     244 
     245    // User::getToken(), User::loadFromToken() 
     246    /** 
     247     * Returns a one time use token for accesing an account. 
     248     *  
     249     * This might be used for retrieving lost passwords. 
     250     *  
     251     * Tokens can be validated using the Sentinel::isValidLoginTokenForUser method 
     252     */ 
     253    function getToken($options = array()) 
     254    { 
     255        $default_options = array( 
     256        'id' => (int)$this->get('id'), 
     257        'single_use' => !empty($options['single_use']) 
     258        ); 
     259        $options = array_merge($default_options, $options); 
     260 
     261        $options['expires'] = empty($options['expires']) ? 0 : Ak::getTimestamp()+((empty($options['expires']) ? '0' : ($options['expires'] == true ? 86400 : $options['expires']))); 
     262        $options['single_use'] = $options['single_use'] ? 1 : 0; 
     263 
     264        $options['hash'] = $this->_getTokenHash($options); 
     265 
     266        return $this->_encodeToken($options); 
     267    } 
     268 
     269    function _getTokenHash($options) 
     270    { 
     271        return md5($this->get('id'). 
     272        $this->get('email'). 
     273        $this->get('login'). 
     274        $this->get('password'). 
     275        $this->get('password_salt'). 
     276        (!empty($options['single_use'])?$this->get('last_login_at'):''). 
     277        $this->get('is_enabled'). 
     278        (isset($options['expires'])?$options['expires']:'')); 
     279    } 
     280 
     281    /** 
     282     * Given an array of options it will return an encrypted url string 
     283     * 
     284     * @param array $options token options 
     285     * @return string Url ready authentication Token 
     286     */ 
     287    function _encodeToken($options) 
     288    { 
     289        return base64_encode(Ak::blowfishEncrypt(Ak::toJson($options), Ak::getSetting('admin', 'token_key'))); 
     290    } 
     291 
     292    /** 
     293     * Decodes a token generated with encodeToken and returns an array of options 
     294     *  
     295     * @param string $token token options 
     296     * @param bool $url_decode should it URL decode the token true by default 
     297     * @return array Array of options for the authentication token 
     298     */ 
     299    function _decodeToken($token) 
     300    { 
     301        return (array)Ak::fromJson(Ak::blowfishDecrypt(base64_decode($token), Ak::getSetting('admin', 'token_key'))); 
     302    } 
     303 
     304 
     305    // Permissions 
     306    // ---------------------- 
     307    function &getPermissions() 
     308    { 
     309        $this->role->load(); 
     310        $Permissions = array(); 
     311        if(!empty($this->roles)){ 
     312            foreach (array_keys($this->roles) as $k){ 
     313                $Permissions = array_merge($Permissions, $this->roles[$k]->getPermissions()); 
     314            } 
     315        } 
     316        return $Permissions; 
     317    } 
     318 
     319    function can($task, $extension = null, $force_reload = false) 
     320    { 
     321        if(!isset($this->_activeRecordHasBeenInstantiated) ||  
     322            $this->getModelName() != 'User'){ 
     323            if (User::isLoaded()) { 
     324                $User =& User::getCurrentUser(); 
     325                return $User->can($task, $extension, $force_reload); 
     326            } else { 
     327                return false; 
     328            } 
     329        } 
     330 
     331        static $Permissions; 
     332        if(!isset($Permissions) || $force_reload){ 
     333            $Permissions = array(); 
     334            $UserPermissions =& $this->getPermissions(); 
     335            foreach (array_keys($UserPermissions) as $k){ 
     336                $extension_id = $UserPermissions[$k]->get('extension_id'); 
     337                $Permissions[(empty($extension_id)?'core':$extension_id)][] = $UserPermissions[$k]->get('name'); 
     338            } 
     339        } 
     340        $extension_id = $this->_getExtensionId($extension); 
     341        return (!empty($Permissions[$extension_id]) && in_array($task, $Permissions[$extension_id])) ? true : $this->_addRootPermission($task, $extension_id); 
     342    } 
     343 
     344    function hasRole($role_name, $force_reload = false) 
     345    { 
     346        if(!isset($this->_activeRecordHasBeenInstantiated)){ 
     347            $User =& User::getCurrentUser(); 
     348            return $User->hasRole($role_name, $force_reload); 
     349        } 
     350        $role_name = strtolower($role_name); 
     351        $Roles =& $this->getRoles($force_reload); 
     352        if(!empty($Roles)){ 
     353            foreach(array_keys($Roles) as $k){ 
     354                if(strtolower($Roles[$k]->get('name')) == $role_name){ 
     355                    return true; 
     356                } 
     357            } 
     358        } 
     359        return false; 
     360    } 
     361 
     362    function &getRoles($force_reload = false) 
     363    { 
     364        if((!isset($this->LoadedRoles) || $force_reload) && $this->role->load()){ 
     365            $this->LoadedRoles = array(); 
     366            foreach (array_keys($this->roles) as $k){ 
     367                $this->LoadedRoles[$this->roles[$k]->getId()] =& $this->roles[$k]; 
     368                foreach ($this->roles[$k]->nested_set->getFullSet() as $Role){ 
     369                    $this->LoadedRoles[$Role->getId()] = $Role; 
     370                } 
     371            } 
     372            return $this->LoadedRoles; 
     373        } 
     374        $result = array(); 
     375        return $result; 
     376    } 
     377 
     378    function hasRootPrivileges() 
     379    { 
     380        $this->role->load(); 
     381        return isset($this->roles[0]) ? $this->roles[0]->nested_set->isRoot() : false; 
     382    } 
     383 
     384    function _addRootPermission($task, $extension_id) 
     385    { 
     386        if($this->hasRootPrivileges()){ 
     387            $Permission =& new Permission(); 
     388            $Permission =& $Permission->findOrCreateBy('name AND extension_id', $task, $extension_id); 
     389            $this->roles[0]->addPermission($Permission); 
     390            return true; 
     391        } 
     392        return false; 
     393    } 
     394 
     395    function _getExtensionId($extension, $force_reload = false) 
     396    { 
     397        static $extenssion_ids = array(); 
     398        if(is_string($extension) && !is_numeric($extension)){ 
     399            if(isset($extenssion_ids[$extension]) && $force_reload == false){ 
     400                return $extenssion_ids[$extension]; 
     401            } 
     402            $extension_key = $extension; 
     403            Ak::import('Extension'); 
     404            $ExtensionInstance =& new Extension(); 
     405            $extension =& $ExtensionInstance->findOrCreateBy('name', $extension); 
     406        } 
     407        $extension = is_object($extension) ? $extension->getId() : (empty($extension)?'core':$extension); 
     408        isset($extension_key) ? $extenssion_ids[$extension_key] = $extension : null; 
     409        return $extension; 
     410    } 
     411 
     412 
     413    /** 
     414     * Returns the current user if it is set, otherwise throws an error 
     415     *  
     416     * @see isLoaded() to check before and not throw an error 
     417     * @return User 
     418     */ 
     419    function getCurrentUser() 
     420    { 
     421        $User =& Ak::getStaticVar('CurrentUser'); 
     422        if (empty($User)) { 
     423            trigger_error(Ak::t('Current user has not been set yet.'), E_USER_ERROR); 
     424        } 
     425        return $User; 
     426    } 
     427    /** 
     428     * Checks if the user is set 
     429     * 
     430     * @return boolean 
     431     */ 
     432    function isLoaded() 
     433    { 
     434        return Ak::getStaticVar('CurrentUser') != null; 
     435    } 
     436 
     437    /** 
     438     * Sets the current user 
     439     * 
     440     * @param User $CurrentUser 
     441     */ 
     442    function setCurrentUser($CurrentUser) 
     443    { 
     444        Ak::_staticVar('CurrentUser', $CurrentUser); 
     445    } 
     446 
     447 
     448    function unsetCurrentUser() 
     449    { 
     450        User::setCurrentUser(null); 
     451    } 
    13452} 
     453 
     454 
     455?> 
  • events/phpframework/akelos/trunk/config/locales/en.php

    r20124 r20269  
    306306$dictionary['Static calls emulation is not supported by PHP5 < 5.4'] = 'Static calls emulation is not supported by PHP5 < 5.4'; 
    307307 
     308// 2008-09-30 10:21:31 
     309 
     310 
     311$dictionary['File %file exists.'] = 'File %file exists.'; 
     312 
    308313 
    309314?> 
  • events/phpframework/akelos/trunk/config/locales/ja.php

    r20124 r20269  
    304304$dictionary['Static calls emulation is not supported by PHP5 < 5.4'] = 'Static calls emulation is not supported by PHP5 < 5.4'; 
    305305 
     306// 2008-09-30 10:21:31 
     307 
     308 
     309$dictionary['File %file exists.'] = 'File %file exists.'; 
     310 
    306311 
    307312?> 
  • events/phpframework/akelos/trunk/config/routes.php

    r20121 r20269  
    1 <?php 
     1<?php  
     2 
     3 $Map->connect('/admin/:controller/:action/:id', array('controller' => 'dashboard', 'action' => 'index', 'module' => 'admin')); 
    24 
    35// You can find more about routes on /lib/AkRouters.php and /test/test_AkRouter.php 
  • events/phpframework/akelos/trunk/test/fixtures/app/models/user.php

    r18146 r20269  
    11<?php 
    2  
    3 class User extends ActiveRecord 
    4 { 
    5     var $habtm = 'groups,posts'; 
    6 } 
     2require_once(AK_BASE_DIR.DS.'app'.DS.'models'.DS.substr(strrchr(__FILE__, DS), 1)); 
    73 
    84?> 
  • events/phpframework/akelos/trunk/test/unit/app/models/user.php

    r19814 r20269  
    11<?php 
    2 // To run this test calling ./script/test unit/app/models/user// More about testing at http://wiki.akelos.org/testing-guide 
    32 
    43class UserTestCase extends AkUnitTest 
    54{ 
     5    var $module = 'admin'; 
     6 
     7    var $insert_models_data = true; 
     8 
    69    function test_setup() 
    710    { 
    8         $this->installAndIncludeModels('User'); 
     11        $this->uninstallAndInstallMigration('AdminPlugin'); 
     12        $this->includeAndInstatiateModels('User', 'Role', 'Permission'); 
     13    } 
     14 
     15    function test_should_request_valid_password() 
     16    { 
     17        $Alicia =& new User(array('email' => 'alicia@example.com', 'login'=>'alicia', 'password' => 'abcd1234')); 
     18        $this->assertFalse($Alicia->save()); 
     19        $this->assertEqual("can't be blank", $Alicia->getErrorsOn('password_confirmation')); 
     20 
     21        $Alicia->setAttributes(array('password' => 'abcd1234','password_confirmation' => 'abcd1234')); 
     22        $this->assertTrue($Alicia->save()); 
     23        $this->assertNotEqual($Alicia->get('password'), 'abcd1234'); 
     24        $this->assertTrue(strlen($Alicia->get('password_salt')) == 16); 
     25    } 
     26 
     27    function test_should_avoid_replicated_users() 
     28    { 
     29        $Alicia =& new User(array('email' => 'alicia@example.com', 'login'=>'alicia', 'password' => 'abcd1234', 'password_confirmation' => 'abcd1234')); 
     30        $this->assertFalse($Alicia->save()); 
     31        $this->assertEqual("email alicia@example.com already in use", $Alicia->getErrorsOn('email')); 
     32        $this->assertEqual("login alicia already in use", $Alicia->getErrorsOn('login')); 
     33    } 
     34 
     35    function test_should_prevent_from_using_invalid_email_addresses() 
     36    { 
     37        $Bogus =& new User(array('email' => 'bogus', 'login'=>'alicia', 'password' => 'abcd1234', 'password_confirmation' => 'abcd1234')); 
     38        $this->assertFalse($Bogus->save()); 
     39        $this->assertEqual("Invalid email address", $Bogus->getErrorsOn('email')); 
    940    } 
    1041     
    11     function test_User() 
    12     { 
    13         $this->assertTrue(false,'Unit test for User not implemented'); 
     42    function test_should_update_without_changing_password() 
     43    { 
     44        $Alicia =& $this->User->findFirstBy('login', 'alicia'); 
     45        $pass = $Alicia->get('password'); 
     46        $Alicia->save(); 
     47        $Alicia->reload(); 
     48        $this->assertEqual($Alicia->get('password'), $pass); 
     49    } 
     50 
     51    function test_should_not_update_password_if_no_confirmation_is_provided() 
     52    { 
     53        $Alicia =& $this->User->findFirstBy('login', 'alicia'); 
     54        $pass = $Alicia->get('password'); 
     55        $Alicia->set('password', 'badpass'); 
     56        $this->assertFalse($Alicia->save()); 
     57        $Alicia->reload(); 
     58        $this->assertEqual($Alicia->get('password'), $pass); 
     59    } 
     60 
     61    function test_should_update_password() 
     62    { 
     63        $Alicia =& $this->User->findFirstBy('login', 'alicia'); 
     64        $pass = $Alicia->get('password'); 
     65        $Alicia->set('password', 'goodpass'); 
     66        $Alicia->set('password_confirmation', 'goodpass'); 
     67        $this->assertTrue($Alicia->save()); 
     68        $Alicia->reload(); 
     69        $this->assertNotEqual($Alicia->get('password'), $pass); 
     70    } 
     71 
     72    function test_should_emit_and_and_validate_single_use_login_token() 
     73    { 
     74        $Alicia =& $this->User->findFirstBy('login', 'alicia'); 
     75        $token = $Alicia->getToken(array('single_use'=> true)); 
     76        $this->assertTrue($User = User::authenticateWithToken($token)); 
     77        $this->assertEqual($Alicia->get('login'), $User->get('login')); 
     78        $this->assertFalse($User = User::authenticateWithToken($token)); 
     79    } 
     80 
     81    function test_should_emit_and_and_validate_login_token() 
     82    { 
     83        $Alicia =& $this->User->findFirstBy('login', 'alicia'); 
     84        $token = $Alicia->getToken(); 
     85        $this->assertTrue($User = User::authenticateWithToken($token));         
     86        $this->assertEqual($Alicia->get('login'), $User->get('login')); 
     87        $this->assertTrue($User = User::authenticateWithToken($token)); 
     88    } 
     89     
     90    function test_should_issue_expiring_tokens() 
     91    { 
     92         
     93        $Alicia =& $this->User->findFirstBy('login', 'alicia'); 
     94        $token = $Alicia->getToken(array('expires'=>1)); 
     95        $this->assertTrue($User = User::authenticateWithToken($token));         
     96        $this->assertTrue($User = User::authenticateWithToken($token));         
     97        $this->assertEqual($Alicia->get('login'), $User->get('login')); 
     98        sleep(1); 
     99        $this->assertFalse($User = User::authenticateWithToken($token)); 
     100    } 
     101 
     102    function test_should_detect_if_given_password_is_valid() 
     103    { 
     104        $Alicia =& $this->User->findFirstBy('login', 'alicia'); 
     105        $this->assertTrue($Alicia->isValidPassword('goodpass')); 
     106        $this->assertFalse($Alicia->isValidPassword('badone')); 
     107    } 
     108 
     109    function test_should_avoid_changing_login_if_no_password_is_provided() 
     110    { 
     111        $Alicia =& $this->User->findFirstBy('login', 'alicia'); 
     112        $Alicia->set('login', 'aliciasadurni'); 
     113        $this->assertFalse($Alicia->save()); 
     114 
     115        $Alicia->set('password', 'badpass'); 
     116 
     117        $this->assertFalse($Alicia->save()); 
     118 
     119        $Alicia->reload(); 
     120        $Alicia->set('login', 'aliciasadurni'); 
     121        $Alicia->set('password', 'goodpass'); 
     122 
     123        $this->assertTrue($Alicia->save()); 
     124    } 
     125 
     126 
     127    function test_should_set_roles() 
     128    { 
     129        $Alicia =& $this->User->findFirstBy('login', 'aliciasadurni'); 
     130 
     131        $this->_createRoles(); 
     132 
     133        $Alicia->role->add($this->Role->findFirstBy('name', 'Visitor')); 
     134        $Alicia->role->add($this->Role->findFirstBy('name', 'Editor')); 
     135        $Alicia->role->add($this->Role->findFirstBy('name', 'Copywriter')); 
     136        $Alicia->save(); 
     137 
     138        $Alicia->reload(); 
     139        $Alicia->role->load(); 
     140 
     141        $this->assertTrue($Alicia->role->count(), 3); 
     142 
     143    } 
     144 
     145 
     146    function test_should_be_able_to_authenticate() 
     147    { 
     148        $this->assertFalse(User::authenticate('aliciasadurni', 'badpass')); 
     149        $this->assertTrue($Alicia = User::authenticate('aliciasadurni', 'goodpass')); 
     150        $this->assertNotNull($Alicia->get('last_login_at'), 'Should update last_login_at'); 
     151        $this->assertEqual(substr($Alicia->get('last_login_at'),0,-2), substr(Ak::getDate(),0,-2)); 
     152    } 
     153 
     154    function test_should_create_disabled_user() 
     155    { 
     156        $Bermi =& new User(array('email'=>'bermi@example.com', 'login'=>'bermi', 'password'=>'abcde', 'password_confirmation'=>'abcde', 'is_enabled' => false)); 
     157        $this->assertTrue($Bermi->save()); 
     158 
     159        $this->assertFalse($Bermi->get('is_enabled')); 
     160    } 
     161 
     162    function test_should_only_authenticate_users_with_roles() 
     163    { 
     164        $Bermi =& $this->User->findFirstBy('login', 'bermi'); 
     165        $Bermi->enable(); 
     166        $this->assertFalse(User::authenticate('bermi', 'abcde')); 
     167        $Bermi->role->add(new Role(array('name'=>'Tmp Role'))); 
     168        $Bermi->save(); 
     169        $this->assertTrue(User::authenticate('bermi', 'abcde')); 
     170    } 
     171 
     172 
     173    function test_should_only_authenticate_enabled_users() 
     174    { 
     175        $Bermi =& $this->User->findFirstBy('login', 'bermi'); 
     176 
     177        $this->assertTrue($User = User::authenticate('bermi', 'abcde')); 
     178 
     179        $Bermi->disable(); 
     180        $this->assertFalse(User::authenticate('bermi', 'abcde')); 
     181 
     182        $Role =& new Role(); 
     183        $Role =& $Role->findFirstBy('name', 'Tmp Role'); 
     184        $Role->destroy(); 
     185    } 
     186 
     187 
     188    function test_should_get_roles() 
     189    { 
     190        $Alicia =& $this->User->findFirstBy('login', 'aliciasadurni'); 
     191        $Alicia->role->load(); 
     192        $this->assertEqual(array_values($Alicia->collect($Alicia->roles, 'id','name')), array('Visitor', 'Editor', 'Copywriter')); 
     193    } 
     194 
     195    function test_should_get_permissions() 
     196    { 
     197        $Alicia =& $this->User->findFirstBy('login', 'aliciasadurni'); 
     198        $this->assertEqual($this->_getPermissionDescriptionsForUser($Alicia), array('authenticate','create','edit','list','view')); 
     199    } 
     200 
     201    function test_should_verify_user_credential_for_specific_tasks() 
     202    { 
     203        $Alicia =& $this->User->findFirstBy('login', 'aliciasadurni'); 
     204 
     205        $this->assertTrue($Alicia->can('authenticate')); 
     206        $this->assertTrue($Alicia->can('create')); 
     207        $this->assertTrue($Alicia->can('edit')); 
     208        $this->assertTrue($Alicia->can('list')); 
     209        $this->assertTrue($Alicia->can('view')); 
     210 
     211        $this->assertFalse($Alicia->can('remove')); 
     212        $this->assertFalse($Alicia->can('connect')); 
     213    } 
     214 
     215    function test_should_verify_user_credential_for_specific_tasks_on_extensions() 
     216    { 
     217        $Alicia =& $this->User->findFirstBy('login', 'aliciasadurni'); 
     218        $Alicia->role->add($this->Role->findFirstBy('name', 'Developer')); 
     219 
     220        $this->assertTrue($Alicia->can('connect', 2, true)); 
     221        $this->assertTrue($Alicia->can('connect', 2)); 
     222        $this->assertTrue($Alicia->can('remove', 2)); 
     223        $this->assertFalse($Alicia->can('remove')); 
     224        $this->assertFalse($Alicia->can('connect')); 
     225    } 
     226 
     227    function test_should_set_user_roles_by_id() 
     228    { 
     229        $Administrator =& $this->Role->findFirstBy('name', 'Administrator'); 
     230        $Developer =& $this->Role->findFirstBy('name', 'Developer'); 
     231        $Visitor =& $this->Role->findFirstBy('name', 'Visitor'); 
     232 
     233 
     234        $Salavert =& new User(array('email'=>'salavert@example.com', 'login'=>'salavert', 'password'=>'abcde', 'password_confirmation'=>'abcde')); 
     235        $this->assertTrue($Salavert->save()); 
     236 
     237        $Salavert->role->load(); 
     238        $Salavert->role->setByIds(array($Administrator->id, $Developer->id)); 
     239 
     240        $Salavert->reload(); 
     241 
     242        $this->assertEqual(count($Salavert->roles), 2); 
     243        $this->assertEqual($Salavert->roles[0]->id, $Administrator->id); 
     244        $this->assertEqual($Salavert->roles[1]->id, $Developer->id); 
     245 
     246        $Salavert->role->setByIds(array($Visitor->id)); 
     247 
     248        $Salavert =& $Salavert->find($Salavert->id, array('include'=>'roles')); 
     249 
     250        $this->assertEqual(count($Salavert->roles), 1); 
     251        $this->assertEqual($Salavert->roles[0]->id, $Visitor->id); 
     252    } 
     253 
     254    /**/ 
     255    function _createRoles() 
     256    { 
     257        $Administrator =& $this->Role->create(array('name' => 'Administrator')); 
     258 
     259        // Page roles 
     260        $Collaborator =& $Administrator->addChildrenRole('Collaborator'); 
     261        $Collaborator->addPermission('create'); 
     262        $Collaborator->addPermission('rename'); 
     263 
     264        $Authenticated =& $Collaborator->addChildrenRole('Authenticated'); 
     265        $Authenticated->addPermission('comment'); 
     266 
     267        $Visitor =& $Authenticated->addChildrenRole('Visitor'); 
     268        $Visitor->addPermission('authenticate'); 
     269        $Visitor->addPermission('view'); 
     270        $Visitor->addPermission('list'); 
     271 
     272        // API Roles 
     273        $Developer =& $Administrator->addChildrenRole('Developer'); 
     274        $Developer->addPermission(array('name'=>'connect','extension_id'=>2)); 
     275        $Developer->addPermission(array('name'=>'remove','extension_id'=>2)); 
     276 
     277        // Outsourced 
     278        $ServiceProviders =& $Administrator->addChildrenRole('Service providers'); 
     279        $ContentManagement =& $ServiceProviders->addChildrenRole('Content management'); 
     280        $ContentManagement->addPermission('create'); 
     281 
     282        $Editor =& $ContentManagement->addChildrenRole('Editor'); 
     283        $Editor->addPermission('edit'); 
     284        $Translator =& $ContentManagement->addChildrenRole('Translator'); 
     285        $Translator->addPermission('fork'); 
     286        $Translator->addPermission('edit'); 
     287        $Legal =& $ServiceProviders->addChildrenRole('Legal'); 
     288        $Legal->addPermission('warn'); 
     289 
     290        $Copywriter =& $Legal->addChildrenRole('Copywriter'); 
     291        $Copywriter->addPermission('edit'); 
     292        $Copywriter->addPermission('create'); 
     293        $Auditor =& $Legal->addChildrenRole('Auditor'); 
     294        $Auditor->addPermission('remove'); 
     295        $Auditor->addPermission('warn'); 
     296    } 
     297 
     298    function _getPermissionDescriptionsForUser(&$User) 
     299    { 
     300        $permissions = array_values($User->collect($User->getPermissions(),'id','name')); 
     301        sort($permissions); 
     302        return $permissions; 
    14303    } 
    15304}