bf226ee4 by Chris Boden

Facebook with WP registration working, login/out working

1 parent 90891653
......@@ -12,23 +12,19 @@ namespace Tz\WordPress\Tools\Auth;
use Tz\WordPress\Tools;
use Tz\Common;
use Exception, LogicException, InvalidArgumentException, BadMethodCallException;
const ACTION_CHECK_AUTH = 'check_auth';
use WP_User;
// These are all WordPress hooks, I put them here for easy reference
const ACTION_LOGIN = 'wp_login';
const ACTION_LOGOUT = 'wp_logout';
const ACTION_ACTIVATE = 'user_register';
//const ACTION_REGISTER
const ACTION_REGISTER = 'user_register';
const ACTION_ACTIVATE = 'wpmu_activate_user';
const OPTION_NAME = 'tz_auth'; // Database lookup key (`wp_options`.`option_name`)
call_user_func(function() {
Vars::$options = new Tools\WP_Option(OPTION_NAME);
Tools\add_actions(__NAMESPACE__ . '\Actions');
if (is_admin()) {
require_once(__DIR__ . DIRECTORY_SEPARATOR . 'Settings.php');
}
......@@ -92,7 +88,7 @@ function signin($username, $remember = true) {
_set_current_user($user->ID);
do_action('wp_login', $username);
return $user;
return new WP_User($user->ID);
}
/**
......@@ -153,6 +149,8 @@ function register($username, $email, $password, $meta = Array()) {
'meta' => $meta
));
// do_action('ACTION_REGISTER'); ???
return $key;
}
......@@ -162,7 +160,7 @@ function register($username, $email, $password, $meta = Array()) {
* @see wpmu_activate_signup
*/
function activate($key) {
global $wpdb;
global $wpdb, $current_site;
$signup = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->signups} WHERE activation_key = %s", $key));
if (empty($signup)) {
......@@ -177,14 +175,6 @@ function activate($key) {
// Do I need to re-sanatize this?
$meta = unserialize($signup->meta);
/*
$user_data = Array(
'user_login' => $signup->user_login
, 'user_email' => $signup->user_email
, 'user_pass' => $meta['password']
);
$id = (int)_insert_user($user_data);
*/
$id = _create_user($signup->user_login, $meta['password'], $signup->user_email);
unset($meta['password']);
......@@ -192,38 +182,17 @@ function activate($key) {
throw new Exception('Unable to create user');
}
/* Add the user to the appropriate blog
$now = current_time('mysql', true);
$wpdb->update($wpdb->signups, array('active' => 1, 'activated' => $now), array('activation_key' => $key));
$wpdb->update($wpdb->signups, Array('active' => 1, 'activated' => current_time('mysql', true)), Array('activation_key' => $key));
$user_site = get_site_option('dashboard_blog', $current_site->blog_id);
add_user_to_blog(($user_site ?: 1), $id, get_site_option('default_user_role', 'subscriber'));
global $current_site;
$user_site = get_site_option( 'dashboard_blog', $current_site->blog_id );
if ( $user_site == false )
add_user_to_blog( '1', $user_id, get_site_option( 'default_user_role', 'subscriber' ) );
else
add_user_to_blog( $user_site, $user_id, get_site_option( 'default_user_role', 'subscriber' ) );
add_new_user_to_blog( $user_id, $user_email, $meta );
do_action('wpmu_activate_user', $user_id, $password, $meta);
*/
// If use these, fix variables, they're wrong
// add_new_user_to_blog( $id, $user_email, $meta );
// do_action(ACTION_ACTIVATE, $id, $password, $meta);
return (int)$id;
}
class Actions {
/*
// I forget why I chose wp() instead of set_current_user()...
public static function wp() {
global $post; // I want a better way to do this
if ($post->ID == Vars::$options['login_page'] && !is_user_logged_in()) {
do_action(ACTION_CHECK_AUTH);
}
}
*/
}
class Validation extends Common\Validation {
/**
* @rule Not blank
......
......@@ -39,7 +39,7 @@ const OPTION_NAME = 'tz_auth_fb';
//setcookie('wpfb_logout', '', time() - 3600, '/');
call_user_func(function() {
Vars::$options = new Tools\WP_Option(OPTION_NAME, Array('button_title' => 'Login'));
Vars::$options = new Tools\WP_Option(OPTION_NAME, Array('button_title' => 'Login', 'ext_perms' => Array('email' => 1)));
Tools\add_actions(__NAMESPACE__ . '\Actions');
Tools\add_shortcodes(__NAMESPACE__ . '\ShortCodes');
......@@ -57,7 +57,7 @@ const OPTION_NAME = 'tz_auth_fb';
function drawLoginButton($echo = true) {
$title = Vars::$options['button_title'] ?: 'Login';
$btn = '<a id="TzFB" class="fb_button fb_button_medium"><span class="fb_button_text">' . $title . '</span></a>';
$btn = '<fb:login-button></fb:login-button>';
// $btn = '<fb:login-button></fb:login-button>';
if (!$echo) {
return $btn;
......@@ -83,16 +83,13 @@ function getSDK() {
}
function load() {
Vars::$loaded = true;
?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: '<?php echo Vars::$options['application_id']; ?>', status: true, cookie: true, xfbml: true});
FB.getLoginStatus(function(response) {
console.log(response.status);
});
FB.Event.subscribe('auth.login', function(response) { window.location.reload(); });
<?php if (isset($_COOKIE['wpfb_logout'])): ?>
......@@ -102,7 +99,7 @@ function load() {
var date = new Date();
date.setTime(date.getTime() - 1);
document.cookie = 'wpfb_logout=;expires=' + date.toGMTString() + ';path=/';
// window.location.reload();
});
}
......@@ -120,18 +117,7 @@ function load() {
<?php
}
/*
* Logic for all these methods needs to be re-thought out
* Should only load FB stuff when something happens (decide)
* 1) drawLoginButton() has been called
* 2) User is on the login_page
* 3) Some other clever way of deciding if FB stuff should load
*/
class Actions {
/**
* Logs the user in to WP if they logged into FB
* @global $post
*/
public static function set_current_user() {
$sdk = getSDK();
if (null === ($sess = $sdk->getSession())) {
......@@ -146,17 +132,20 @@ class Actions {
// if user is not logged in do the following
// if user is logged in merge account? do checks?
// User is not logged into WP and has just logged in via FB
// need try/catch here - I think I got an OAuthException at one point
try {
$info = $sdk->api('/me');
$username = 'fbc' . $sess['uid'];
} catch (FB\FacebookApiException $e) {
// Load up an error thingie
return;
}
if (is_user_logged_in()) {
// was user already logged in from Facebook/other or were they logged in and then linked with facebook
// merge account
// return
}
require_once(ABSPATH . WPINC . DIRECTORY_SEPARATOR . 'registration.php');
if (username_exists($username)) {
$user = Auth\signin($username);
......@@ -170,32 +159,28 @@ class Actions {
$key = Auth\register($username, $info['email'], _generate_password());
$id = Auth\activate($key);
$user = Auth\signin($username);
_update_user(Array(
'ID' => $user->ID
, 'user_nicename' => $info['name']
, 'first_name' => $info['first_name']
, 'last_name' => $info['last_name']
, 'nickname' => $info['name']
, 'display_name' => $info['name']
, 'user_url' => ($info['user_website'] ?: '')
));
update_user_meta($user->ID, 'fbuid', $info['id']);
} catch (Exception $e) {
// many types of exceptions
}
}
foreach (Vars::$options['ext_perms'] as $key => $on) {
// I need to map some keys to WordPress presets
// update_user_meta($user->ID, $key, $info[$key]);
}
}
/**
* Load the Facebook scripts for login
*/
public static function OFF_wp_enqueue_scripts() {
_enqueue_script('facebook-all', 'http://connect.facebook.net/en_US/all.js');
_enqueue_script('tz-facebook', Tools\url('tz-facebook.js', __FILE__), Array('addEvent', 'Cookie'));
_localize_script('tz-facebook', 'TzFBData', Array('AppID' => Vars::$options['application_id'], 'ext_perms' => implode(',', array_keys(Vars::$options['ext_perms'])), 'loginPage' => get_permalink(Auth\Vars::$options['login_page'])));
}
public static function wp_enqueue_scripts() {
_enqueue_script('tz-facebook', Tools\url('tz-facebook.js', __FILE__), Array('addEvent'));
/**
* Creates the anchor needed for Facebook scripts
*/
public static function OFF_get_footer() {
echo '<div id="fb-root"></div>';
_localize_script('tz-facebook', 'TzFBData', Array('ext_perms' => implode(',', array_keys(Vars::$options['ext_perms']))));
}
/**
......@@ -208,22 +193,12 @@ class Actions {
class ShortCodes {
public static function fb_login_button() {
/*
if (is_user_logged_in()) {
return '';
}
*/
$sdk = getSDK();
if ($sdk->getSession()) {
ob_start();
print_r($sdk->getSession());
print_r($_COOKIE);
try {
print_r($sdk->api('/me'));
} catch (Exception $e) {
die('fuck');
}
$data = '<pre>' . ob_get_contents() . '</pre>';
ob_end_clean();
......@@ -240,5 +215,6 @@ class Vars {
* @type WP_Option
*/
public static $options;
public static $loaded = false;
}
?>
\ No newline at end of file
......
......@@ -18,7 +18,7 @@ function validate($data) {
}
class Vars {
public static $data_permissions = Array('email', 'read_insights', 'read_stream', 'read_mailbox', 'ads_management', 'xmpp_login', 'user_about_me', 'user_activities', 'user_birthday', 'user_education_history', 'user_events', 'user_groups', 'user_hometown', 'user_interests', 'user_likes', 'user_location', 'user_notes', 'user_online_presence', 'user_photo_video_tags', 'user_photos', 'user_relationships', 'user_religion_politics', 'user_status', 'user_videos', 'user_website', 'user_work_history', 'read_friendlists', 'read_requests');
public static $data_permissions = Array('read_insights', 'read_stream', 'read_mailbox', 'ads_management', 'xmpp_login', 'user_about_me', 'user_activities', 'user_birthday', 'user_education_history', 'user_events', 'user_groups', 'user_hometown', 'user_interests', 'user_likes', 'user_location', 'user_notes', 'user_online_presence', 'user_photo_video_tags', 'user_photos', 'user_relationships', 'user_religion_politics', 'user_status', 'user_videos', 'user_website', 'user_work_history', 'read_friendlists', 'read_requests');
}
class Actions {
......@@ -30,8 +30,19 @@ class Actions {
add_settings_section(OPTION_SECTION_SEL, 'Facebook Extended Data Permissions', function() { echo '<p>Select which additional data you wish to collect from the user</p>'; }, Auth\Settings\ADMIN_PAGE);
foreach (Vars::$data_permissions as $option) {
add_settings_field($option, ucwords(str_replace('_', ' ', $option)), Array(new Opt_Fields(), $option), Auth\Settings\ADMIN_PAGE, OPTION_SECTION_SEL);
add_settings_field(
$option
, ucwords(str_replace('_', ' ', $option))
, function() use ($option) {
echo '<input type="checkbox" id="' . $option . '" name="' . Facebook\OPTION_NAME . '[ext_perms][' . $option . ']" value="1" ' . checked('1', Facebook\Vars::$options['ext_perms'][$option], false) . ' />';
}
, Auth\Settings\ADMIN_PAGE
, OPTION_SECTION_SEL
);
}
add_settings_field('email', '', function() {
echo '<input type="hidden" id="email" name="' . Facebook\OPTION_NAME . '[ext_perms][email]" value="1" />';
}, Auth\Settings\ADMIN_PAGE, OPTION_SECTION_SEL);
}
}
......@@ -56,10 +67,4 @@ class Cred_Fields {
echo '<input type="text" id="' . __FUNCTION__ . '" name="' . Facebook\OPTION_NAME . '[' . __FUNCTION__ . ']" value="' . Facebook\Vars::$options[__FUNCTION__] . '" />';
}
}
class Opt_Fields {
public function __call($fn, $args) {
echo '<input type="checkbox" id="' . $fn . '" name="' . Facebook\OPTION_NAME . '[ext_perms][' . $fn . ']" value="1" ' . checked('1', Facebook\Vars::$options['ext_perms'][$fn], false) . ' />';
}
}
?>
\ No newline at end of file
......
window.fbAsyncInit = function() {
FB.init({appId: TzFBData.AppID, status: true, cookie: true, xfbml: true});
FB.Event.subscribe('auth.login', function(response) { console.log('login called'); window.location.href = TzFBData.loginPage; });
var oBtn = document.getElementById('TzFB');
if (oBtn) {
addEvent(oBtn, 'click', FB.login);
}
if (Cookie.read('wpfb_logout')) {
Cookie.erase('wpfb_logout');
FB.getLoginStatus(function(response) {
if (response.session) {
FB.logout(function() {
Cookie.erase('wpfb_logout');
window.location.reload();
});
}
});
}
};
\ No newline at end of file
addEvent(window, 'load', function() {
var oBtn = document.getElementById('TzFB');
if (oBtn) {
addEvent(oBtn, 'click', function() {
FB.login(function() {}, {perms: TzFBData.ext_perms});
});
}
});
\ No newline at end of file
......