xref: /dokuwiki/lib/plugins/auth.php (revision 93a7873eb0646b5712d75b031cd8b8b143968ba2)
1<?php
2/**
3 * Auth Plugin Prototype
4 *
5 * foundation authorisation class
6 * all auth classes should inherit from this class
7 *
8 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
9 * @author    Chris Smith <chris@jalakai.co.uk>
10 * @author    Jan Schumann <js@jschumann-it.com>
11
12 */
13// must be run within Dokuwiki
14if(!defined('DOKU_INC')) die();
15
16class DokuWiki_Auth_Plugin extends DokuWiki_Plugin {
17    var $success = true;
18
19    /**
20     * Posible things an auth backend module may be able to
21     * do. The things a backend can do need to be set to true
22     * in the constructor.
23     */
24    var $cando = array (
25        'addUser'     => false, // can Users be created?
26        'delUser'     => false, // can Users be deleted?
27        'modLogin'    => false, // can login names be changed?
28        'modPass'     => false, // can passwords be changed?
29        'modName'     => false, // can real names be changed?
30        'modMail'     => false, // can emails be changed?
31        'modGroups'   => false, // can groups be changed?
32        'getUsers'    => false, // can a (filtered) list of users be retrieved?
33        'getUserCount'=> false, // can the number of users be retrieved?
34        'getGroups'   => false, // can a list of available groups be retrieved?
35        'external'    => false, // does the module do external auth checking?
36        'logout'      => true,  // can the user logout again? (eg. not possible with HTTP auth)
37    );
38
39    /**
40     * Constructor.
41     *
42     * Carry out sanity checks to ensure the object is
43     * able to operate. Set capabilities in $this->cando
44     * array here
45     *
46     * Set $this->success to false if checks fail
47     *
48     * @author  Christopher Smith <chris@jalakai.co.uk>
49     */
50    function __construct() {
51        // the base class constructor does nothing, derived class
52        // constructors do the real work
53    }
54
55    /**
56     * Capability check. [ DO NOT OVERRIDE ]
57     *
58     * Checks the capabilities set in the $this->cando array and
59     * some pseudo capabilities (shortcutting access to multiple
60     * ones)
61     *
62     * ususal capabilities start with lowercase letter
63     * shortcut capabilities start with uppercase letter
64     *
65     * @author  Andreas Gohr <andi@splitbrain.org>
66     * @return  bool
67     */
68    function canDo($cap) {
69        switch($cap){
70            case 'Profile':
71                // can at least one of the user's properties be changed?
72                return ( $this->cando['modPass']  ||
73                        $this->cando['modName']  ||
74                        $this->cando['modMail'] );
75                break;
76            case 'UserMod':
77                // can at least anything be changed?
78                return ( $this->cando['modPass']   ||
79                        $this->cando['modName']   ||
80                        $this->cando['modMail']   ||
81                        $this->cando['modLogin']  ||
82                        $this->cando['modGroups'] ||
83                        $this->cando['modMail'] );
84                break;
85            default:
86                // print a helping message for developers
87                if(!isset($this->cando[$cap])){
88                    msg("Check for unknown capability '$cap' - Do you use an outdated Plugin?",-1);
89                }
90                return $this->cando[$cap];
91        }
92    }
93
94    /**
95     * Trigger the AUTH_USERDATA_CHANGE event and call the modification function. [ DO NOT OVERRIDE ]
96     *
97     * You should use this function instead of calling createUser, modifyUser or
98     * deleteUsers directly. The event handlers can prevent the modification, for
99     * example for enforcing a user name schema.
100     *
101     * @author Gabriel Birke <birke@d-scribe.de>
102     * @param string $type Modification type ('create', 'modify', 'delete')
103     * @param array $params Parameters for the createUser, modifyUser or deleteUsers method. The content of this array depends on the modification type
104     * @return mixed Result from the modification function or false if an event handler has canceled the action
105     */
106    function triggerUserMod($type, $params) {
107        $validTypes = array(
108            'create' => 'createUser',
109            'modify' => 'modifyUser',
110            'delete' => 'deleteUsers'
111        );
112        if(empty($validTypes[$type]))
113            return false;
114        $eventdata = array('type' => $type, 'params' => $params, 'modification_result' => null);
115        $evt = new Doku_Event('AUTH_USER_CHANGE', $eventdata);
116        if ($evt->advise_before(true)) {
117            $result = call_user_func_array(array($this, $validTypes[$type]), $params);
118            $evt->data['modification_result'] = $result;
119        }
120        $evt->advise_after();
121        unset($evt);
122        return $result;
123    }
124
125    /**
126     * Log off the current user [ OPTIONAL ]
127     *
128     * Is run in addition to the ususal logoff method. Should
129     * only be needed when trustExternal is implemented.
130     *
131     * @see     auth_logoff()
132     * @author  Andreas Gohr <andi@splitbrain.org>
133     */
134    function logOff(){
135    }
136
137    /**
138     * Do all authentication [ OPTIONAL ]
139     *
140     * Set $this->cando['external'] = true when implemented
141     *
142     * If this function is implemented it will be used to
143     * authenticate a user - all other DokuWiki internals
144     * will not be used for authenticating, thus
145     * implementing the checkPass() function is not needed
146     * anymore.
147     *
148     * The function can be used to authenticate against third
149     * party cookies or Apache auth mechanisms and replaces
150     * the auth_login() function
151     *
152     * The function will be called with or without a set
153     * username. If the Username is given it was called
154     * from the login form and the given credentials might
155     * need to be checked. If no username was given it
156     * the function needs to check if the user is logged in
157     * by other means (cookie, environment).
158     *
159     * The function needs to set some globals needed by
160     * DokuWiki like auth_login() does.
161     *
162     * @see auth_login()
163     * @author  Andreas Gohr <andi@splitbrain.org>
164     *
165     * @param   string  $user    Username
166     * @param   string  $pass    Cleartext Password
167     * @param   bool    $sticky  Cookie should not expire
168     * @return  bool             true on successful auth
169     */
170    function trustExternal($user,$pass,$sticky=false){
171        /* some example:
172
173        global $USERINFO;
174        global $conf;
175        $sticky ? $sticky = true : $sticky = false; //sanity check
176
177        // do the checking here
178
179        // set the globals if authed
180        $USERINFO['name'] = 'FIXME';
181        $USERINFO['mail'] = 'FIXME';
182        $USERINFO['grps'] = array('FIXME');
183        $_SERVER['REMOTE_USER'] = $user;
184        $_SESSION[DOKU_COOKIE]['auth']['user'] = $user;
185        $_SESSION[DOKU_COOKIE]['auth']['pass'] = $pass;
186        $_SESSION[DOKU_COOKIE]['auth']['info'] = $USERINFO;
187        return true;
188
189        */
190    }
191
192    /**
193     * Check user+password [ MUST BE OVERRIDDEN ]
194     *
195     * Checks if the given user exists and the given
196     * plaintext password is correct
197     *
198     * May be ommited if trustExternal is used.
199     *
200     * @author  Andreas Gohr <andi@splitbrain.org>
201     * @return  bool
202     */
203    function checkPass($user,$pass){
204        msg("no valid authorisation system in use", -1);
205        return false;
206    }
207
208    /**
209     * Return user info [ MUST BE OVERRIDDEN ]
210     *
211     * Returns info about the given user needs to contain
212     * at least these fields:
213     *
214     * name string  full name of the user
215     * mail string  email addres of the user
216     * grps array   list of groups the user is in
217     *
218     * @author  Andreas Gohr <andi@splitbrain.org>
219     * @return  array containing user data or false
220     */
221    function getUserData($user) {
222        if(!$this->cando['external']) msg("no valid authorisation system in use", -1);
223        return false;
224    }
225
226    /**
227     * Create a new User [implement only where required/possible]
228     *
229     * Returns false if the user already exists, null when an error
230     * occurred and true if everything went well.
231     *
232     * The new user HAS TO be added to the default group by this
233     * function!
234     *
235     * Set addUser capability when implemented
236     *
237     * @author  Andreas Gohr <andi@splitbrain.org>
238     */
239    function createUser($user,$pass,$name,$mail,$grps=null){
240        msg("authorisation method does not allow creation of new users", -1);
241        return null;
242    }
243
244    /**
245     * Modify user data [implement only where required/possible]
246     *
247     * Set the mod* capabilities according to the implemented features
248     *
249     * @author  Chris Smith <chris@jalakai.co.uk>
250     * @param   $user      nick of the user to be changed
251     * @param   $changes   array of field/value pairs to be changed (password will be clear text)
252     * @return  bool
253     */
254    function modifyUser($user, $changes) {
255        msg("authorisation method does not allow modifying of user data", -1);
256        return false;
257    }
258
259    /**
260     * Delete one or more users [implement only where required/possible]
261     *
262     * Set delUser capability when implemented
263     *
264     * @author  Chris Smith <chris@jalakai.co.uk>
265     * @param   array  $users
266     * @return  int    number of users deleted
267     */
268    function deleteUsers($users) {
269        msg("authorisation method does not allow deleting of users", -1);
270        return false;
271    }
272
273    /**
274     * Return a count of the number of user which meet $filter criteria
275     * [should be implemented whenever retrieveUsers is implemented]
276     *
277     * Set getUserCount capability when implemented
278     *
279     * @author  Chris Smith <chris@jalakai.co.uk>
280     */
281    function getUserCount($filter=array()) {
282        msg("authorisation method does not provide user counts", -1);
283        return 0;
284    }
285
286    /**
287     * Bulk retrieval of user data [implement only where required/possible]
288     *
289     * Set getUsers capability when implemented
290     *
291     * @author  Chris Smith <chris@jalakai.co.uk>
292     * @param   start     index of first user to be returned
293     * @param   limit     max number of users to be returned
294     * @param   filter    array of field/pattern pairs, null for no filter
295     * @return  array of userinfo (refer getUserData for internal userinfo details)
296     */
297    function retrieveUsers($start=0,$limit=-1,$filter=null) {
298        msg("authorisation method does not support mass retrieval of user data", -1);
299        return array();
300    }
301
302    /**
303     * Define a group [implement only where required/possible]
304     *
305     * Set addGroup capability when implemented
306     *
307     * @author  Chris Smith <chris@jalakai.co.uk>
308     * @return  bool
309     */
310    function addGroup($group) {
311        msg("authorisation method does not support independent group creation", -1);
312        return false;
313    }
314
315    /**
316     * Retrieve groups [implement only where required/possible]
317     *
318     * Set getGroups capability when implemented
319     *
320     * @author  Chris Smith <chris@jalakai.co.uk>
321     * @return  array
322     */
323    function retrieveGroups($start=0,$limit=0) {
324        msg("authorisation method does not support group list retrieval", -1);
325        return array();
326    }
327
328    /**
329     * Return case sensitivity of the backend [OPTIONAL]
330     *
331     * When your backend is caseinsensitive (eg. you can login with USER and
332     * user) then you need to overwrite this method and return false
333     */
334    function isCaseSensitive(){
335        return true;
336    }
337
338    /**
339     * Sanitize a given username [OPTIONAL]
340     *
341     * This function is applied to any user name that is given to
342     * the backend and should also be applied to any user name within
343     * the backend before returning it somewhere.
344     *
345     * This should be used to enforce username restrictions.
346     *
347     * @author Andreas Gohr <andi@splitbrain.org>
348     * @param string $user - username
349     * @param string - the cleaned username
350     */
351    function cleanUser($user){
352        return $user;
353    }
354
355    /**
356     * Sanitize a given groupname [OPTIONAL]
357     *
358     * This function is applied to any groupname that is given to
359     * the backend and should also be applied to any groupname within
360     * the backend before returning it somewhere.
361     *
362     * This should be used to enforce groupname restrictions.
363     *
364     * Groupnames are to be passed without a leading '@' here.
365     *
366     * @author Andreas Gohr <andi@splitbrain.org>
367     * @param string $group - groupname
368     * @param string - the cleaned groupname
369     */
370    function cleanGroup($group){
371        return $group;
372    }
373
374
375    /**
376     * Check Session Cache validity [implement only where required/possible]
377     *
378     * DokuWiki caches user info in the user's session for the timespan defined
379     * in $conf['auth_security_timeout'].
380     *
381     * This makes sure slow authentication backends do not slow down DokuWiki.
382     * This also means that changes to the user database will not be reflected
383     * on currently logged in users.
384     *
385     * To accommodate for this, the user manager plugin will touch a reference
386     * file whenever a change is submitted. This function compares the filetime
387     * of this reference file with the time stored in the session.
388     *
389     * This reference file mechanism does not reflect changes done directly in
390     * the backend's database through other means than the user manager plugin.
391     *
392     * Fast backends might want to return always false, to force rechecks on
393     * each page load. Others might want to use their own checking here. If
394     * unsure, do not override.
395     *
396     * @param  string $user - The username
397     * @author Andreas Gohr <andi@splitbrain.org>
398     * @return bool
399     */
400    function useSessionCache($user){
401        global $conf;
402        return ($_SESSION[DOKU_COOKIE]['auth']['time'] >= @filemtime($conf['cachedir'].'/sessionpurge'));
403    }
404
405
406  /**
407   * loadConfig()
408   * merges the plugin's default settings with any local settings
409   * this function is automatically called through getConf()
410   */
411    function loadConfig(){
412      global $conf;
413
414      parent::loadConfig();
415
416      $this->conf['debug'] = $conf['debug'];
417      $this->conf['useacl'] = $conf['useacl'];
418      $this->conf['disableactions'] = $conf['disableactions'];
419      $this->conf['autopasswd'] = $conf['autopasswd'];
420      $this->conf['passcrypt'] = $conf['ssha'];
421  }
422
423}
424