summaryrefslogtreecommitdiffstats
path: root/authfas.module
blob: 203807199168708ac66101162365f0302945ff24 (plain)
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
352
353
354
355
356
357
358
359
<?php
  // $Id$

/**
 * Implementation of hook_help().
 */
function authfas_help($path, $arg) {
  $output = '';
  switch ($path) {
  case "admin/help#authfas":
    $output = '<p>'.  t("Authentication to the Fedora Account System (FAS)") .'</p>';
    break;
  }
  return $output;
} // function authfas_help

/**
 * Implementation of hook_perm().
 */
function authfas_perm() {
  return array('administer FAS settings');
} // function authfas_perm()

/**
 * Implementation of hook_admin().
 */
function authfas_admin() {
  $form = array();
  
  $form['authfas_fasurl'] = array(
    '#type' => 'textfield',
    '#title' => t('Location of FAS instance'),
    '#default_value' => variable_get('authfas_fasurl', 'admin.fedoraproject.org/accounts'),
    '#size' => 50,
    '#maxlength' => 255,
    '#description' => t('The location of the FAS instance to which users can authenticate'),
    '#required' => TRUE,
  );
  // Include a fieldset for validating the FAS URL if desired
  $form['authfas_verify_fasurl'] = array(
    '#type' => 'fieldset',
    '#title' => t('FAS URL validation information'),
    '#description' => t('Enter a valid account and passphrase to validate the FAS URL above. This information is not required, but can be used to test via JSON whether the URL above is working correctly.  To skip validation, clear these fields.'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
  );
  $form['authfas_verify_fasurl']['fas_username'] = array(
    '#type' => 'textfield',
    '#title' => t('FAS username'),
    '#size' => 40,
    '#maxlength' => 255,
    '#default_value' => '');
  $form['authfas_verify_fasurl']['fas_password'] = array(
    '#type' => 'password',
    '#title' => t('FAS password'),
    '#size' => 40,
    '#maxlength' => 255,
    '#default_value' => '');
  // We have a required setting for the Authenticated User role.
  $form['authfas_authuser_fasgroup'] = array(
    '#type' => 'textfield',
    '#title' => t('FAS group for authenticated users'),
    '#default_value' => variable_get('authfas_authuser_fasgroup', ''),
    '#size' => 50,
    '#maxlength' => 255,
    '#description' => t('To authenticate when this module is enabled, a user must be a member of this FAS group.'),
    '#required' => TRUE,
  );
  $form['authfas_maildomain'] = array(
    '#type' => 'textfield',
    '#title' => t('Email domain used for FAS users'),
    '#default_value' => variable_get('authfas_maildomain', ''),
    '#size' => 50,
    '#maxlength' => 255,
    '#description' => t('Enter the domain name to be appended to accounts authenticated via FAS. Do not include the @ sign.'),
    '#required' => TRUE,
  );

  $form['authfas_more_information'] = array(
    '#type' => 'item',
    '#title' => t('More information'),
    '#description' => t('Visit the <a href="@roles">Roles</a> settings page to set FAS group mappings for specific roles.', array('@roles' => url('admin/user/roles'))),
  );

  return system_settings_form($form);
}

/**
 * Implementation of hook_menu().
 */
function authfas_menu() {
  $items = array();

  $items['admin/settings/authfas'] = array(
    'title' => t('AuthFAS module settings'),
    'description' => t('Settings for authenticating to a FAS instance'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('authfas_admin'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function authfas_fas_login($username, $password, $url, $headers = '') {
  $username = strtolower($username);
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_POST, 1);
  curl_setopt($ch, CURLOPT_POSTFIELDS, "user_name=".urlencode($username)."&password=".urlencode($password)."&login=Login");
  // Sticking extra headers in user agent string for now, no other good CURLOPT?
  curl_setopt($ch, CURLOPT_USERAGENT, "Drupal AuthFAS 0.1; ".$headers);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  // The following two lines need to be enabled when using a test FAS
  // with an invalid cert.  Otherwise they should be commented (or
  // set to True) for security.
  // #curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
  // #curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
  $response = json_decode(curl_exec($ch), true);
  curl_close ($ch);

  return $response;
}

/**
 * Validate settings entered in AuthFAS settings menu
 */
function authfas_admin_validate($form, &$form_state) {
  $fasurl = $form_state['values']['authfas_fasurl'];
  $username = $form_state['values']['fas_username'];
  $password = $form_state['values']['fas_password'];

  if (($username != '') and ($password != '')) {
    $response = authfas_fas_login($username, $password, 'https://'.$fasurl.'/json/', 'Accept: application/json;');

    if (!isset($response["help"])) {
      form_set_error("authfas_fasurl", t('Could not verify FAS username <em>@username</em>.', array('@username' => $username)));
      return FALSE;
    }
    // else we're peachy
    drupal_set_message(t('FAS validation was successful.'));
  }
  return TRUE;
}

/**
 * To connect an arbitrary number of roles in Drupal with FAS groups,
 * we first alter the role editing form to add a field, using the
 * hook_form_FORM_ID_alter() function.  We then push a custom function
 * onto the callback array to allow us to run database queries on
 * submit.
 */
// First, alter the user role editing form.
function authfas_form_user_admin_role_alter(&$form, $form_state) {
  $newform = array();
  // I'm obviously not very good at PHP because I couldn't figure
  // out a more clever way to insert this field into an existing
  // $form array.  We want the field for FAS group mapping to be part
  // of the form *before* the submit control.
  while (list($key, $val) = each($form)) {
    if ($key == 'submit') {
      $fasgroup = db_result(db_query("SELECT fasgroup FROM {authfas_ridmap} WHERE rid = %d;", $form['rid']['#value']));
      $newform['fasgroup'] = array(
        '#type' => 'textfield',
        '#title' => t('FAS group mapping'),
        '#description' => t('Enter the name for a FAS group that maps to this role. To delete an existing mapping, clear this field. When you delete an existing mapping, users are not removed from the Drupal role. You can either delete the role entirely to remove all users from it, or remove individual users from the role by <a href="@edit">editing them directly</a>.', array('@edit' => url('admin/user/user'))),
        '#size' => 30,
        '#maxlength' => 255,
        '#default_value' => $fasgroup,
      );
    }
    $newform[$key] = $val;
  }
  // Add a callback to the stack
  $newform['#submit'][] = 'authfas_user_admin_role_submit';
  $form = $newform;
}

// Next, add functions to update the database.
function authfas_user_admin_role_submit($form, &$form_state) {
  $fasgroup = $form_state['values']['fasgroup'];
  $rid = $form_state['values']['rid'];
  $name = $form_state['values']['name'];
  $op = $form_state['values']['op'];
  $current = db_result(db_query("SELECT fasgroup FROM {authfas_ridmap} WHERE rid = %d;", $form_state['values']['rid']));

  // If we're deleting a role or removing the FAS group, delete the row.
  if (($op == t('Delete role')) or ($fasgroup == '')) {
    $result = db_query("DELETE FROM {authfas_ridmap} WHERE rid = %d", $rid);
    if ($result) {
      drupal_set_message(t('The <em>@role</em> role has been removed from the FAS group map.', array('@role' => $name)));
    } else {
      form_set_error(t('Database error'));
    }
  } // End delete
  // If we're saving a role, update the row.
  else if (($op == t('Save role')) and (isset($fasgroup))) {
    if ($current == '') { // Wasn't mapped before
      $result = db_query("INSERT INTO {authfas_ridmap} (rid, fasgroup) VALUES (%d, '%s')", $rid, $fasgroup);
      if ($result) {
        drupal_set_message(t('The role <em>@role</em> is now mapped to FAS group <em>@fasgroup</em>.', array('@role' => $name, '@fasgroup' => $fasgroup)));
      } else { form_set_error(t('Database error')); }
    } else { // Was mapped before
      $result = db_query("UPDATE {authfas_ridmap} SET fasgroup = '%s' WHERE rid = %d", $fasgroup, $rid);
      if ($result) { 
        drupal_set_message(t('The <em>@role</em> role is now mapped to FAS group <em>@fasgroup</em>.', array('@role' => $name, '@fasgroup' => $fasgroup))); 
      } else { form_set_error(t('Database error')); }
    } // End mapped before
  } // End insert/update
}

/**
 * Implementation of hook_form_alter().
 *
 * Change the normal form login form behaviour.
 */
function authfas_form_user_login_alter(&$form, $form_state) {
  unset($form['links']);
  $form['#validate'] = array(
    'user_login_name_validate',
    'authfas_login_validate',
    'user_login_final_validate');
}

function authfas_form_user_login_block_alter(&$form, $form_state) {
  return authfas_form_user_login_alter($form, $form_state);
}

function authfas_remap_roles($username, $fasgroups) {
  /**
   * This function is called after the user is registered but before
   * the final session creation happens.
   */
  global $user;

  foreach ($fasgroups as $fasgroup) {
    $newfasgroups[] = $fasgroup['name'];
  }
  $fasgroups = $newfasgroups;
  // Retrieve ridmap from the DB and append required FAS group
  $result = db_query('SELECT rid, fasgroup FROM {authfas_ridmap}');
  while ($row = db_fetch_array($result)) {
    $ridmap[] = array('rid' => intval($row['rid']), 'fasgroup' => $row['fasgroup']);
  }
  /**
   * User is already in $authuser_fasgroup. If we decide later to
   * implement a special external authentication rid, we'll need to
   * include the standard "authenticated user" rid here in $ridmap.
   */
  foreach ($ridmap as $ridmapentry) {
    // For all the rid<->fasgroup mappings that Drupal knows about...
    if (in_array($ridmapentry['fasgroup'], $fasgroups)) {
      // If the user's in the fasgroup...
      if (!in_array($ridmapentry['rid'], array_keys($user->roles))) {
        // But the rid isn't in the user's Drupal roles...
        // ...make it so!
        db_query("INSERT INTO {users_roles} (uid, rid) VALUES ('%s', '%s')", $user->uid, $ridmapentry['rid']);
      }
    } else { // If the user's *NOT* in the fasgroup...
      if (in_array($ridmapentry['rid'], array_keys($user->roles))) {
        // But the rid *IS* in the user's Drupal roles...
        // ...make it not so!
        db_query("DELETE FROM {users_roles} WHERE uid=%d AND rid=%d", $user->uid, $ridmapentry['rid']);
      }
    }
  } // End of going through the ridmap

}

/**
 * Validate login for FAS user
 */
function authfas_login_validate($form, &$form_state) {
  $username = strtolower($form_state['values']['name']);
  $fasurl = variable_get('authfas_fasurl', '');
  $authuser_fasgroup = variable_get('authfas_authuser_fasgroup', '');

  if ((!$fasurl) or (!$authuser_fasgroup)) {
    form_set_error(t('AuthFAS settings are incorrect or invalid. Please visit the <a href="@settings">module settings</a> or consult the administrator of this system for assistance.', array('@settings' => url('admin/settings/authfas'))));
    return FALSE;
  }
  $response = authfas_fas_login($username, $form_state['values']['pass'], 'https://'.$fasurl.'/json/person_by_username?username='.$username.'&tg_format=json', 'Accept: application/json;');
  if ($response['success']) {
    $authenticated = FALSE; // Until proven otherwise
    $fasgroups = $response['person']['approved_memberships'];

    // You'd better be in the authenticated user FAS group!
    foreach ($fasgroups as $group) {
      if ($group['name'] == $authuser_fasgroup) {
        $authenticated = TRUE;
      }
    }
    if (!$authenticated) return FALSE;

    user_external_login_register($username, 'authfas');
    // Now $user exists, if I'm right...
    authfas_remap_roles($username, $fasgroups);
    user_authenticate_finalize($form_state['values']);

  } else {
    // If not in FAS, try to authenticate normally through Drupal
    user_login_authenticate_validate($form, &$form_state);
  }
}


/**
 * Implementation of hook_user().
 */
function authfas_user($op, &$edit, &$account, $category = null) {
  $fasmaildomain = variable_get('authfas_maildomain', '');
  switch($op) {
    case('insert'):
      /**
       * Called during the registration process, after new user is
       * added to {users} but before roles are written to
       * {users_roles} table
       */
      if (empty($account->mail)) {
        db_query("UPDATE {users} SET mail = '%s' WHERE uid = %d", $account->name.'@'.$fasmaildomain, $account->uid);
      }

      /**
       * FIXME: We might want to do something here to add a special
       * 'FAS authenticated' role to the new FAS user.  That might
       * make other comparisons simpler.
       */
      break;

    case('update'): // Called before database record (or $account) is updated
      /**
       * Forbidden to change email address if it's based on FAS
       * username. If you're not admin, and your account has been set
       * up with a FAS maildomain, your change is reverted.
       */
      if (($user->uid != 1) and ($account->mail == $account->name.'@'.$fasmaildomain)) {
        if (strcmp($account->mail, $edit['mail'])) {
          unset($edit['mail']);
          drupal_set_message(t('Sorry, FAS users cannot change their e-mail address.'), 'error');
        }
        // Also forbidden to change passwords in the Drupal instance
        if ($edit['pass'] != '') {
          unset($edit['pass']);
          drupal_set_message(t('Please use FAS to change your password.'), 'error');
        }
      }
      break;
  }
}

// Local variables:
// mode:php
// tab-width:2
// indent-tabs-mode:nil
// End: