Skip to content

Instantly share code, notes, and snippets.

@nfsarmento
Forked from itzikbenh/a-theme-auth.php
Created January 31, 2018 19:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nfsarmento/b3ffd005fc713f1e4171a897f13cad11 to your computer and use it in GitHub Desktop.
Save nfsarmento/b3ffd005fc713f1e4171a897f13cad11 to your computer and use it in GitHub Desktop.
WordPress class for registering users via Linkedin
<?php
function a_theme_auth_options_page()
{
add_options_page( "A-Theme Auth options", "A-Theme Auth", "manage_options", "a-theme-auth", "a_theme_auth_options" );
}
add_action( 'admin_menu', 'a_theme_auth_options_page' );
function register_a_theme_auth_settings()
{
register_setting( 'a_theme_auth_options_group', 'ath_auth_settings' );
}
add_action( 'admin_init', 'register_a_theme_auth_settings' );
function a_theme_auth_options()
{
include( plugin_dir_path( __FILE__ ) . '/options-template.php' );
}

#How does it work?

  1. Read this - https://developer.linkedin.com/docs/oauth2
  2. You send an API GET call to get the authorization code.
  3. With the authorization code you send a POST call to get the access token.
  4. With the access token you send a GET call to get the users data. Simple right?

You will probably need to tweak it to your needs, but this is a good starting point. The socialite class has all the methods that interacts with Linkedin.

<?php
function ath_linkedin_authentication()
{
$socialite = new Socialite();
//After this all will be handled by ath_linkedin_callback function.
$socialite->get_authorization_code();
}
function ath_linkedin_callback()
{
$socialite = new Socialite();
$homepage = network_site_url( '/' );
$code = $_GET['code'];
$state = $_GET['state'];
if( $socialite->state == $state )
{
$access_token = $socialite->get_access_token( $code );
}
if( $access_token )
{
$users_data = $socialite->get_users_data( $access_token );
}
$email = $users_data->emailAddress;
$profile_image = $users_data->pictureUrl;
$first_name = $users_data->firstName;
$last_name = $users_data->lastName;
$username = $users_data->firstName." ".$users_data->lastName;
//If user exists we will simply log him in.
$user = get_user_by( "email", $email );
if( ! empty( $user ) )
{
wp_clear_auth_cookie();
wp_set_current_user ( $user->ID );
wp_set_auth_cookie ( $user->ID, true );
$_SESSION["home_success"] = "Welcome back $user->user_login!";
wp_redirect( $homepage );
exit;
}
$user_data = array(
'user_login' => $username,
'user_email' => $email,
'user_pass' => ""
);
$user_id = wp_insert_user( $user_data );
if( is_wp_error( $user_id ) )
{
$_SESSION["errors"]["register_error_url"] = "Sorry, registration failed due to an unxpected error. We are working on fixing it as soon as possible.";
wp_safe_redirect( $register_url );
exit;
}
add_user_meta( $user_id, "profile_image", $profile_image );
add_user_meta( $user_id, "provider", "linkedin" );
//Login the user.
wp_clear_auth_cookie();
wp_set_current_user ( $user_id );
wp_set_auth_cookie ( $user_id, true );
$_SESSION["home_success"] = "Welcome $username, you have registered successfully.";
wp_safe_redirect( $homepage );
exit;
}
<!--
An example of how the login/register buttin might look. The action and the hidden input are the most important parts.
-->
<form class="form-horizontal" action="<?php echo get_admin_url() ?>admin-post.php">
<div class="form-group">
<input type='hidden' name='action' value='linkedin_authentication' />
<button class="btn btn-block btn-social btn-linkedin" type="submit">
<i class="fa fa-linkedin"></i> Sign in with Linkedin
</button>
</div>
</form>
<?php
define( 'ATH_AUTH_PATH', plugin_dir_path( __FILE__ ) );
include( ATH_AUTH_PATH . 'includes/options/a-theme-auth.php' );
include( ATH_AUTH_PATH . 'includes/socialite/socialite-class.php' );
include( ATH_AUTH_PATH . 'includes/socialite/callbacks/linkedin-callback.php' );
//For the linkedin button that the user will click
add_action('admin_post_nopriv_linkedin_authentication', 'ath_linkedin_authentication');
//For the callback URL
add_action('admin_post_nopriv_linkedin_callback', 'ath_linkedin_callback');
<div class="wrap">
<h1>A-Theme Auth settings page</h1>
<form method="post" action="options.php">
<?php settings_fields( 'a_theme_auth_options_group' ); ?>
<?php do_settings_sections( 'a_theme_auth_options_group' ); ?>
<?php
$options = get_option( 'ath_auth_settings' );
?>
<table class="form-table">
<tr valign="top">
<th scope="row">Linkedin client id</th>
<td>
<?php $linkedin_client_id = ( isset( $options['linkedin_client_id'] ) ) ? "*******".substr( $options['linkedin_client_id'], -4 ) : ""; ?>
<input class="regular-text" type="text" name="ath_auth_settings[linkedin_client_id]" value="<?php echo $linkedin_client_id; ?>"/>
</td>
</tr>
<tr valign="top">
<th scope="row">Linkedin client secret</th>
<td>
<?php $linkedin_client_secret = ( isset( $options['linkedin_client_secret'] ) ) ? "*******".substr( $options['linkedin_client_secret'], -4 ) : ""; ?>
<input class="regular-text" type="text" name="ath_auth_settings[linkedin_client_secret]" value="<?php echo $linkedin_client_secret; ?>"/>
</td>
</tr>
</table>
<?php submit_button(); ?>
</form>
</div>
<?php
class Socialite
{
private $linkedin_client_id;
private $linkedin_client_secret;
private $redirect_uri = "http://localhost:3000/water/wp-admin/admin-post.php?action=linkedin_callback";
private $linkedin_scope = "r_basicprofile r_emailaddress";
private $linkedin_auth_uri = "https://www.linkedin.com/oauth/v2/authorization";
private $linkedin_token_uri = "https://www.linkedin.com/oauth/v2/accessToken";
private $linkedin_people_uri = "https://api.linkedin.com/v1/people/";
public $state = "bhjbbcjheghjbcvjhcbbjcjnsfece";
public function __construct()
{
$options = get_option( 'ath_auth_settings' );
$this->linkedin_client_id = ( isset( $options['linkedin_client_id'] ) ) ? $options['linkedin_client_id'] : "";
$this->linkedin_client_secret = ( isset( $options['linkedin_client_secret'] ) ) ? $options['linkedin_client_secret'] : "";
}
public function get_authorization_code()
{
$curl = curl_init( $this->linkedin_auth_uri."?".http_build_query( array(
"response_type" => "code",
"client_id" => $this->linkedin_client_id,
"redirect_uri" => $this->redirect_uri,
"state" => $this->state,
"scope" => $this->linkedin_scope
) )
);
$response = curl_exec( $curl );
$info = curl_getinfo( $curl );
curl_close( $curl );
wp_redirect( $info['redirect_url'] );
}
public function get_access_token( $code )
{
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_HTTPHEADER => array('Content-Type: application/x-www-form-urlencoded'),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $this->linkedin_token_uri,
CURLOPT_POST => 1,
CURLOPT_POSTFIELDS => http_build_query ( array(
"client_id" => $this->linkedin_client_id,
"client_secret" => $this->linkedin_client_secret,
"grant_type" => "authorization_code",
"redirect_uri" => $this->redirect_uri,
"code" => $code
)),
));
$response = json_decode( curl_exec( $curl ) );
$info = curl_getinfo( $curl );
if( $info['http_code'] != 200 )
{
return false;
}
curl_close( $curl );
return $response->access_token;
}
public function get_users_data( $access_token )
{
$curl = curl_init();
$login_url = network_site_url( '/login' );
curl_setopt_array($curl, array(
CURLOPT_HTTPHEADER => array( 'Authorization: Bearer'.$access_token ),
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $this->linkedin_people_uri.'~:(email-address,first-name,last-name,picture-url)?format=json'
));
$response = json_decode( curl_exec( $curl ) );
$info = curl_getinfo( $curl );
curl_close( $curl );
if( $info['http_code'] == 401 )
{
$_SESSION["errors"]["login_error_url"] = "Something went wrong. Please try again or contact us.";
wp_redirect( $login_url );
exit;
}
return $response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment