Add Snippet To Project
<?php
// Include phpCAS library
require_once ABSPATH . 'path/to/phpCAS/CAS.php';
// Initialize phpCAS
phpCAS::client(CAS_VERSION_2_0, 'cas-server-url', 443, '/cas');
phpCAS::setCasServerCACert(ABSPATH . 'path/to/cas.crt');
// Enable CAS authentication
phpCAS::setNoCasServerValidation();
phpCAS::forceAuthentication();
// Get the connected user's username
$user = phpCAS::getUser();
// Assign "employer" role to the connected user
$user_id = username_exists($user);
if ($user_id && !user_has_role($user_id, 'employer')) {
$user = new WP_User($user_id);
$user->add_role('employer');
}
// Helper function to check if a user has a specific role
function user_has_role($user_id, $role) {
$user = new WP_User($user_id);
return in_array($role, $user->roles);
}
When the wp-plugin.php file is loaded, it includes the phpCAS library (CAS.php) using the require_once statement. After that, the phpCAS library is initialized with the CAS server details, such as the server URL and SSL certificate path.
Next, CAS authentication is enabled and enforced using phpCAS::setNoCasServerValidation() and phpCAS::forceAuthentication(). This ensures that the user is redirected to the CAS server for authentication.
Once the user is authenticated, the connected user's username is retrieved using phpCAS::getUser().
Finally, the code checks if the user already exists in WordPress (username_exists($user)) and if they don't have the "employer" role, the role is assigned to the user using WP_User and add_role() functions.
This entire process takes place when the plugin file is loaded in the front-end of the website, ensuring that CAS authentication and the assignment of the "employer" role are performed for authenticated users visiting the site.