mtrack /inc/auth.php

Language PHP Lines 353
MD5 Hash f047c3637c7099f1ae60927f80ebd4d5 Estimated Cost $6,487 (why?)
Repository https://bitbucket.org/yoander/mtrack View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
<?php # vim:ts=2:sw=2:et:
/* For licensing and copyright terms, see the file named LICENSE */

include_once MTRACK_INC_DIR . '/auth/mtrack.php';
include_once MTRACK_INC_DIR . '/auth/anon.php';
include_once MTRACK_INC_DIR . '/auth/http.php';
include_once MTRACK_INC_DIR . '/auth/openid.php';
include_once MTRACK_INC_DIR . '/auth/browserid.php';
include_once MTRACK_INC_DIR . '/auth/facebook.php';

interface IMTrackAuth {
  /** Returns the authenticated user, or null if authentication is
   * required */
  function authenticate();

  /** Called if the user is not authenticated as a registered
   * user and if the page requires it.
   * Should initiate whatever is appropriate to begin the authentication
   * process (eg: displaying logon information).
   * You may assume that no output has been sent to the client at
   * the time that this function is called.
   * Returns null if not supported, throw an exception if failed,
   * else return a the authenticated user (if it can be determined
   * by the time the function returns).
   * If an alternate login page is displayed, this function should
   * exit instead of returning.
   */
  function doAuthenticate($force = false);

  /** Returns a list of available groups.
   * Returns null if not supported, throw an exception if failed. */
  function enumGroups();

  /** Returns a list of groups that a given user belongs to.
   * Returns null if not supported, throw an exception if failed. */
  function getGroups($username);

  /** Adds a user to a group.
   * Returns null if not supported, throw an exception if failed,
   * return true if succeeded */
  function addToGroup($username, $groupname);

  /** Removes a user from a group.
   * Returns null if not supported, throw an exception if failed,
   * return true if succeeded */
  function removeFromGroup($username, $groupname);

  /** Returns userdata for a given user id
   * Some authentication mechanisms outsource the storage of user data.
   * This function returns null if no additional information is available,
   * or an array containing the following keys:
   *   email - the email address
   *   fullname - the full name
   *   avatar - URL to an avatar image
   */
  function getUserData($username);

  /** Returns true if this mechanism is one that is capable of signing
   * out under application control */
  function canLogOut();

  /** logs the user out */
  function LogOut();
}

class MTrackAuth
{
  static $stack = array();
  static $mechs = array();
  static $group_assoc = array();

  public static function registerMech(IMTrackAuth $mech) {
    self::$mechs[] = $mech;
  }

  /** switch user */
  public static function su($user) {
    if (!strlen($user)) throw new Exception("invalid user");
    array_unshift(self::$stack, $user);
    putenv("MTRACK_LOGNAME=$user");
  }

  /** returns the instance of an auth mechanism given its class name */
  public static function getMech($name) {
    foreach (self::$mechs as $inst) {
      if ($inst instanceof $name) {
        return $inst;
      }
    }
    return null;
  }

  /** drop identity set by last su */
  public static function drop() {
    if (count(self::$stack) == 0) {
      throw new Exception("no privs to drop");
    }
    $user = array_shift(self::$stack);
    putenv("MTRACK_LOGNAME=$user");
    return $user;
  }

  /** returns the authenticated user, or null if authentication
   * is required */
  public static function authenticate() {

    /* admin party trumps all; we need to bypass all auth mechs
     * while we're configuring the system */
    if (!MTrackConfig::get('core', 'admin_party')) {
      foreach (self::$mechs as $mech) {
        $name = $mech->authenticate();
        if ($name !== null) {
          return $name;
        }
      }
    }

    /* always fall back on the unix username when running from
     * the console */
    if (php_sapi_name() == 'cli') {
      static $envs = array('MTRACK_LOGNAME', 'LOGNAME', 'USER');
      foreach ($envs as $name) {
        if (isset($_ENV[$name])) {
          return $_ENV[$name];
        }
      }
    } elseif (MTrackConfig::get('core', 'admin_party') == 1) {
      $party = MTrackConfig::get('core', 'admin_party_remote_address');
      if (in_array($_SERVER['REMOTE_ADDR'], explode(',', $party))) {
        return 'adminparty';
      }
    }

    return null;
  }

  public static function isAuthConfigured() {
    return count(self::$mechs) ? true : false;
  }

  /** determine the current identity.  If doauth is true (default),
   * then the authentication hook will be invoked */
  public static function whoami($doauth = true) {
    if (count(self::$stack) == 0 && $doauth) {
      try {
        $who = self::authenticate();
        if ($who === null && !MTrackConfig::get('core', 'admin_party')) {
          foreach (self::$mechs as $mech) {
            $who = $mech->doAuthenticate();
            if ($who !== null) {
              break;
            }
          }
        }
        if ($who !== null) {
          self::su($who);
        }
      } catch (Exception $e) {
        if (php_sapi_name() != 'cli') {
          header('HTTP/1.0 401 Unauthorized');
          echo "<h1>Not authorized</h1>";
          echo htmlentities($e->getMessage());
        } else {
          echo " ** Not authorized\n\n";
          echo $e->getMessage() . "\n";
        }
        error_log($e->getMessage());
        exit(1);
      }
    }
    if (!count(self::$stack)) {
      return "anonymous";
    }
    return self::$stack[0];
  }

  static function getUserClass($user = null) {
    if ($user === null) {
      $user = self::whoami();
    }
    if (MTrackConfig::get('core', 'admin_party') == 1
        && $user == 'adminparty'
        && in_array($_SERVER['REMOTE_ADDR'], explode(',', MTrackConfig::get('core', 'admin_party_remote_address')))) {
      return 'admin';
    }

    $user_class = MTrackConfig::get('user_classes', $user);
    if ($user_class === null) {
      if ($user == 'anonymous') {
        return 'anonymous';
      }
      return 'authenticated';
    }
    return $user_class;
  }

  static $userdata_cache = array();
  static function getUserData($username) {
    $username = mtrack_canon_username($username);

    if (array_key_exists($username, self::$userdata_cache)) {
      return self::$userdata_cache[$username];
    }
    $data = null;
    foreach (self::$mechs as $mech) {
      $data = $mech->getUserData($username);
      if ($data !== null) {
        break;
      }
    }
    foreach (MTrackDB::q(
          'select fullname, email from userinfo where userid = ?',
          $username)->fetchAll(PDO::FETCH_ASSOC) as $row) {
      if ($data === null) {
        $data = $row;
        break;
      }
      foreach ($row as $k => $v) {
        if (!isset($data[$k]) || empty($data[$k])) {
          $data[$k] = $v;
        }
      }
      break;
    }
    if ($data === null) {
      $data = array(
        'fullname' => $username
      );
    }

    if (!isset($data['email'])) {
      if (preg_match('/<([a-z0-9_.+=-]+@[a-z0-9.-]+)>/', $username, $M)) {
        // username contains an email address
        $data['email'] = $M[1];
      } else if (preg_match('/^([a-z0-9_.+=-]+@[a-z0-9.-]+)$/', $username)) {
        // username is an email address
        $data['email'] = $username;
      } else if (preg_match('/^[a-z0-9_.+=-]+$/', $username)) {
        // valid localpart; assume a domain and construct an email address
        $dom = MTrackConfig::get('core', 'default_email_domain');
        if ($dom !== null) {
          $data['email'] = $username . '@' . $dom;
        }
      }
    }

    self::$userdata_cache[$username] = $data;

    return $data;
  }

  /* enumerates possible groups from the auth plugin layer */
  static function enumGroups() {
    $groups = array();
    foreach (self::$mechs as $mech) {
      $g = $mech->enumGroups();
      if (is_array($g)) {
        foreach ($g as $i => $grp) {
          if (is_integer($i)) {
            $groups[$grp] = $grp;
          } else {
            $groups[$i] = $grp;
          }
        }
      }
    }
    /* merge in our project groups */
    foreach (MTrackDB::q('select project, g.name, p.name from groups g left join projects p on g.project = p.projid')
        as $row) {
      $gid = "project:$row[0]:$row[1]";
      $groups[$gid] = "$row[1] ($row[2])";
    }
    return $groups;
  }

  /* returns groups of which the authenticated user is a member */
  static function getGroups($user = null) {
    if ($user === null) {
      $user = self::whoami();
    }
    $canon = mtrack_canon_username($user);

    if (isset(self::$group_assoc[$user])) {
      return self::$group_assoc[$user];
    }

    $roles = array($canon => $canon);

    $user_class = self::getUserClass($user); // FIXME: $canon?
    $class_roles = MTrackConfig::get('user_class_roles', $user_class);
    foreach (preg_split('/\s*,\s*/', $class_roles) as $role) {
      $roles[$role] = $role;
    }

    foreach (self::$mechs as $mech) {
      $g = $mech->getGroups($user);
      if (is_array($g)) {
        foreach ($g as $i => $grp) {
          if (is_integer($i)) {
            $roles[$grp] = $grp;
          } else {
            $roles[$i] = $grp;
          }
        }
      }
    }
    /* merge in our project group membership */
    foreach (MTrackDB::q('select project, groupname, p.name from group_membership gm left join projects p on gm.project = p.projid where username = ?',
        $canon)->fetchAll() as $row) {
      $gid = "project:$row[0]:$row[1]";
      $roles[$gid] = "$row[1] ($row[2])";
    }

    self::$group_assoc[$user] = $roles;
    return $roles;
  }

  static function forceAuthenticate() {
    try {
      $who = self::authenticate();
      if ($who === null && !MTrackConfig::get('core', 'admin_party')) {
        foreach (self::$mechs as $mech) {
          $who = $mech->doAuthenticate(true);
          if ($who !== null) {
            break;
          }
        }
      }
      if ($who !== null) {
        self::su($who);
      }
    } catch (Exception $e) {
    }
  }

  static function canLogOut() {
    foreach (self::$mechs as $mech) {
      if ($mech->canLogOut()) {
        return true;
      }
    }
    return false;
  }

  static function LogOut() {
    foreach (self::$mechs as $mech) {
      $mech->LogOut();
    }
  }

}
Back to Top