lucianoes

SimpleSAMLphp with network in Wordpress with blog creation

Feb 28th, 2012
456
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 6 11.38 KB | None | 0 0
  1. register_activation_hook( __FILE__, 'set_simplesamlphp_settings' );
  2. add_action('admin_menu', 'simplesaml_authentication_add_options_page');
  3.  
  4. $simplesaml_authentication_opt = get_site_option('simplesaml_authentication_options');
  5.  
  6. $simplesaml_configured = true;
  7.  
  8. // try to configure the simpleSAMLphp client
  9. if ($simplesaml_authentication_opt['include_path'] == '') {
  10.   $simplesaml_configured = false;
  11. } else {
  12.   $include_file = $simplesaml_authentication_opt['include_path']."/lib/_autoload.php";
  13.   if (!include_once($include_file))
  14.     $simplesaml_configured = false;
  15. }
  16.  
  17. if ($simplesaml_configured) {
  18.   if($simplesaml_authentication_opt['sp_auth'] == '')
  19.     $sp_auth = 'default-sp';
  20.   else
  21.     $sp_auth = $simplesaml_authentication_opt['sp_auth'];
  22.   $as = new SimpleSAML_Auth_Simple($sp_auth);
  23. }
  24.  
  25. // for wp_create_user function on line 120
  26. require_once (ABSPATH . WPINC . '/registration.php');
  27.  
  28. // plugin hooks into authentication system
  29. add_action('wp_authenticate', array('SimpleSAMLAuthentication', 'authenticate'), 10, 2);
  30. add_action('wp_logout', array('SimpleSAMLAuthentication', 'logout'));
  31. add_action('lost_password', array('SimpleSAMLAuthentication', 'disable_function'));
  32. add_action('retrieve_password', array('SimpleSAMLAuthentication', 'disable_function'));
  33. add_action('password_reset', array('SimpleSAMLAuthentication', 'disable_function'));
  34. add_filter('show_password_fields', array('SimpleSAMLAuthentication', 'show_password_fields'));
  35.  
  36. if (!class_exists('SimpleSAMLAuthentication')) {
  37.   class SimpleSAMLAuthentication {
  38.  
  39.     // password used by the plugin
  40.     function passwordRoot() {
  41.       return 'Authenticated through SimpleSAML';
  42.     }    
  43.  
  44.     /*
  45.      We call simpleSAMLphp to authenticate the user at the appropriate time
  46.      If the user has not logged in previously, we create an account for them
  47.     */
  48.     function authenticate(&$username, &$password) {
  49.       global $simplesaml_authentication_opt, $simplesaml_configured, $as;
  50.  
  51.       if (!$simplesaml_configured)
  52.         die("simplesaml-authentication plugin not configured");
  53.  
  54.       // Reset values from input ($_POST and $_COOKIE)
  55.       $username = $password = '';      
  56.  
  57.       $as->requireAuth();
  58.  
  59.       $attributes = $as->getAttributes();
  60.       $username = $attributes['cn'][0];
  61.       $password = md5(SimpleSAMLAuthentication::passwordRoot());
  62.  
  63.       if (!function_exists('get_userdatabylogin'))
  64.         die("Could not load user data");
  65.       $user = get_userdatabylogin($username);
  66.  
  67.       if ($user) {
  68.         // user already exists
  69.         //we will update the password in the user account just in case we have screwed it up and changed it!
  70.         $user_info = array();
  71.         $user_info['ID'] = $user->ID;
  72.         $user_info['user_pass'] = $password;
  73.         wp_update_user( $user_info ) ;
  74.         return true;
  75.       } else {
  76.         // first time logging in
  77.         if ($simplesaml_authentication_opt['new_user'] == 1) {
  78.           // auto-registration is enabled
  79.  
  80.           // User is not in the WordPress database
  81.           // they passed SimpleSAML and so are authorized
  82.           // add them to the database
  83.           // User must have an email address to register
  84.           if($attributes['mail']) {
  85.             // Try to get email address from attributes
  86.             $user_email = $attributes['mail'][0];
  87.           } else {
  88.             // Otherwise use default email suffix
  89.             if ($simplesaml_authentication_opt['email_suffix'] != '')
  90.               $user_email = $username . '@' . $simplesaml_authentication_opt['email_suffix'];
  91.           }
  92.           //correctly read other attributs
  93.           $user_info = array();
  94.           $user_info['user_login'] = $username;
  95.           $user_info['user_pass'] = $password;
  96.           $user_info['user_email'] = $user_email;
  97.  
  98.           if($attributes['givenName'])
  99.             $user_info['first_name'] = $attributes['givenName'][0];
  100.           if($attributes['sn'])
  101.             $user_info['last_name'] = $attributes['sn'][0];
  102.  
  103.           // Set user role based on eduPersonEntitlement
  104.           if($simplesaml_authentication_opt['admin_entitlement'] != '' &&
  105.           $attributes['eduPersonEntitlement'] &&
  106.              in_array($simplesaml_authentication_opt['admin_entitlement'],
  107.                 $attributes['eduPersonEntitlement'])) {
  108.             $user_info['eduPersonEntitlement'] = "administrator";
  109.           } else {
  110.             $user_info['eduPersonEntitlement'] = "author";
  111.           }
  112.           //now create the users primary blog for them
  113.           $blog_title = strtolower(preg_replace('/[^a-zA-Z0-9 ]/','',$username));
  114.           $wp_uid = wp_insert_user($user_info);
  115.           $result = wpmu_create_blog('blogs.glew.org.uk','/' .$blog_title,$blog_title,$wp_uid,array(),'1');
  116.           //remove user from main blog!
  117.           remove_user_from_blog($wp_uid, '1', '');
  118.           //write options for authentication plugin
  119.           if (function_exists('add_options_page')) {
  120.                 add_options_page('simpleSAMLphp Authentication', 'simpleSAMLphp Authentication', 8, basename(__FILE__), 'simplesaml_authentication_options_page');
  121.           }
  122.           // Setup Default Options Array
  123.           global $wpdb;
  124.           $optionarray_update = array(
  125.                'new_user' => TRUE,
  126.                'redirect_url' => '',
  127.                'email_suffix' => 'example.com',
  128.                'sp_auth' => 'default-sp',
  129.                'include_path' => $simplesaml_authentication_opt['include_path'],
  130.                'admin_entitlement' => '',
  131.                );
  132.           add_site_option($result, 'simplesaml_authentication_options', $optionarray_update);
  133.         }
  134.         else {
  135.           $error = sprintf(__('<p><strong>ERROR</strong>: %s is not registered with this blog. Please contact the <a href="mailto:%s">blog administrator</a> to create a new account!</p>'), $username, get_option('admin_email'));
  136.           $errors['registerfail'] = $error;
  137.           print($error);
  138.           print('<p><a href="/wp-login.php?action=logout">Log out</a> of SimpleSAML.</p>');
  139.           exit();
  140.         }
  141.       }
  142.     }
  143.  
  144.     //do hook for activating a blog
  145.     function set_simplesamlphp_settings() {
  146.           // Setup Default Options Array
  147.           global $wpdb;
  148.           global $blog_id;
  149.           $optionarray_update = array(
  150.                'new_user' => TRUE,
  151.                'redirect_url' => '',
  152.                'email_suffix' => 'example.com',
  153.                'sp_auth' => 'default-sp',
  154.                'include_path' => '<path to your simplesamlphp installation for service provider>',
  155.                'admin_entitlement' => '',
  156.                );
  157.           add_blog_option($blog_id, 'simplesaml_authentication_options', $optionarray_update);
  158.     }
  159.  
  160.     function logout() {
  161.       global $simplesaml_authentication_opt, $simplesaml_configured, $as;
  162.       if (!$simplesaml_configured)
  163.         die("simplesaml-authentication not configured");
  164.  
  165.       $as->logout(get_settings('siteurl'));
  166.     }
  167.  
  168.     /*
  169.      Don't show password fields on user profile page.
  170.    */
  171.    function show_password_fields($show_password_fields) {
  172.      return false;
  173.    }
  174.  
  175.    function disable_function() {
  176.      die('Disabled');
  177.    }
  178.  
  179.  }
  180. }
  181.  
  182. //----------------------------------------------------------------------------
  183. //      ADMIN OPTION PAGE FUNCTIONS
  184. //----------------------------------------------------------------------------
  185.  
  186. function simplesaml_authentication_add_options_page() {
  187.  if (function_exists('add_options_page')) {
  188.    add_options_page('simpleSAMLphp Authentication', 'simpleSAMLphp Authentication', 8, basename(__FILE__), 'simplesaml_authentication_options_page');
  189.  }
  190. }
  191.  
  192. function simplesaml_authentication_options_page() {
  193.  global $wpdb;
  194.  
  195.  // Setup Default Options Array
  196.  $optionarray_def = array(
  197.                'new_user' => TRUE,
  198.                'redirect_url' => '',
  199.                'email_suffix' => 'example.com',
  200.                'sp_auth' => 'default-sp',
  201.                'include_path' => '<path to your simplesamlphp installation for service provider',
  202.                'admin_entitlement' => '',
  203.                );
  204.  
  205.  if (isset($_POST['submit']) ) {
  206.    // Options Array Update
  207.    $optionarray_update = array (
  208.                  'new_user' => $_POST['new_user'],
  209.                  'redirect_url' => $_POST['redirect_url'],
  210.                  'email_suffix' => $_POST['email_suffix'],
  211.                  'include_path' => $_POST['include_path'],
  212.                  'sp_auth' => $_POST['sp_auth'],
  213.                  'admin_entitlement' => $_POST['admin_entitlement'],
  214.                  );
  215.  
  216.    update_site_option('simplesaml_authentication_options', $optionarray_update);
  217.  }
  218.  
  219.  // Get Options
  220.  $optionarray_def = get_site_option('simplesaml_authentication_options');
  221.  
  222.  ?>
  223.     <div class="wrap">
  224.     <h2>simpleSAMLphp Authentication Options</h2>
  225.    <?php
  226.  
  227.         global $current_blog;
  228.         $blog_path = substr($current_blog->path,0,-1);
  229.         if(is_super_admin()) {
  230.     ?>
  231.  
  232.     <form method="post" action="<?php echo $blog_path . $_SERVER['PHP_SELF'] .  '?page=' . basename(__FILE__); ?>&updated=true">
  233.     <fieldset class="options">
  234.  
  235.     <h3>User registration options</h3>
  236.  
  237.     <table class="form-table">
  238.        <tr valign="top">
  239.         <th scope="row">User registration</th>
  240.         <td><label for="new_user">
  241.         <input name="new_user" type="checkbox" id="new_user_inp" value="1" <?php checked('1', $optionarray_def['new_user']); ?> />
  242. Automatically register new users</label>
  243.         <span class="setting-description">(Users will be registered with the role of Subscriber.)</span></td>
  244.         </tr>
  245.         <tr>
  246.         <th><label for="email_suffix"> Default email domain</label></th>
  247.         <td>
  248.         <input type="text" name="email_suffix" id="email_suffix_inp" value="<?php echo $optionarray_def['email_suffix']; ?>" size="35" />
  249.         <span class="setting-description">If an email address is not availble from the <acronym title="Identity Provider">IdP</acronym> <strong>username@domain</strong> will be used.</td>
  250. </tr>
  251.         <tr>
  252.         <th> <label for="admin_entitlement">Administrator Entitlement URI</label></th>
  253.         <td>
  254.         <input type="text" name="admin_entitlement" id="admin_entitlement_inp" value="<?php echo $optionarray_def['admin_entitlement']; ?>" size="40" />
  255.         <span class="setting-description">An <a href="http://rnd.feide.no/node/1022">eduPersonEntitlement</a> URI to be mapped to the Administrator role.</span>
  256.         </td>
  257.         </tr>
  258.     </table>
  259.  
  260.    <h3>simpleSAMLphp options</h3>
  261.    <p><em>Note:</em> Once you fill in these options, WordPress authentication will happen through <a href="http://rnd.feide.no/simplesamlphp">simpleSAMLphp</a>, even if you misconfigure it. To avoid being locked out of WordPress, use a second browser to check your settings before you end this session as Administrator. If you get an error in the other browser, correct your settings here. If you can not resolve the issue, disable this plug-in.</p>
  262.     <table class="form-table">
  263.        <tr valign="top">
  264.         <th scope="row"><label for="include_path">Path to simpleSAMLphp</label></th>
  265.         <td><input type="text" name="include_path" id="include_path_inp" value="<?php echo $optionarray_def['include_path']; ?>" size="35" />
  266.         <span class="setting-description">simpleSAMLphp suggested location is <tt>/var/simplesamlphp</tt>.</span>
  267.         </td>
  268.         </tr>
  269.  
  270.        <tr valign="top">
  271.        <th scope="row"><label for="sp_auth">Authentication source ID</label></th>
  272.        <td><input type="text" name="sp_auth" id="sp_auth_inp" value="<?php echo $optionarray_def['sp_auth']; ?>" size="35" />
  273.         <span class="setting-description">simpleSAMLphp default is "default-sp".</span>
  274.             </td>
  275.          </tr>
  276.     </table>
  277.     </fieldset>
  278.     <p />
  279.     <div class="submit">
  280.         <input type="submit" name="submit" value="<?php _e('Update Options') ?> &raquo;" />
  281.     </div>
  282.     </form>
  283.    <?php } else { ?>
  284.    <div>Sorry, but you cannot edit these settings</div>
  285.    <? } ?>
  286. <?php
  287. }
  288. ?>
Advertisement
Add Comment
Please, Sign In to add comment