PHP-使用wp_set_auth_cookie不带任何钩子

wordpress版本4.7.5

我正在从Instagram注册新用户,我能够成功注册新用户.注册后,我尝试登录用户.

I can use hook, but would like better solution than the dirty one, I
have posted as that will be totally unuseful .

if( $user_created ) {
    $new_user = get_user_by( 'id', $user_created ); 
    //$loggedin = programmatic_login( $new_user->user_login );
    //ob_start();
    if ( !is_user_logged_in() ) {
        wp_clear_auth_cookie();
        wp_set_current_user( $user_created, $new_user->user_login );
        wp_set_auth_cookie( $user_created, true );
        do_action( 'wp_login', $new_user->user_login );
        // wp_safe_redirect(site_url() . '/profile/');
        // exit;
        // $redirect_to=user_admin_url();
        // wp_safe_redirect($redirect_to);
        // exit();
    }
    //ob_end_clean();
} ?>
<script>jQuery(document).ready(function(){ window.location.href = "<?PHP echo site_url() . '/profile/'; ?>";});</script> <?PHP

还尝试了另一篇文章中的自定义programmatic_login函数.

如果我要在此下方进行var_dump wp_get_current_user()和$_COOKIE,我将获得wp_get_current_user()和array(1)的用户对象{[“” wordpress_test_cookie“] =>用于$_COOKIE的string(15)“ WP Cookie检查”}.

重要编辑

代码位于一个函数内部,该函数被挂钩到一个钩子,该钩子在显示标题后的页面中被调用,因此我们在这里不能使用init.任何其他方式,也由于此wp_safe_redirect()或header(‘Location:’)也无法正常工作.

我刚刚尝试过的重要更新

肮脏的工作

当我从Instagram登录名创建用户时,成功创建后,我将用户重定向到带有诸如getp_user == insertted_id之类的get参数的页面,并在wp钩上,我尝试获取GET [‘user_id’]并将其记录下来工作,试图找到合适的解决方案.

if ( $wpdb->insert_id ){  //that is registration with instagram
   ?>
    <script>jQuery(document).ready(function(){ window.location.href = "<?PHP echo get_bloginfo('url') . '/profile/?id=' . $wpdb->insert_id; ?>";});</script>
   <?PHP
}

接着

add_action( 'wp', 'login_current_user' );
function login_current_user(){
    if ( is_page() && get_the_id() == 863 ){
        if ( isset( $_GET['id'] ) ){
            if ( !is_user_logged_in() ) {
                $user_id = $_GET['id'];
                $user = get_user_by( 'id', $user_id ); 
                wp_clear_auth_cookie();
                wp_set_current_user( $user_id, $user->user_login );
                wp_set_auth_cookie( $user_id, true );
                do_action( 'wp_login', $user->user_login );
                if ( is_user_logged_in() ){
                    $redirect_to=site_url() . '/profile';
                    wp_safe_redirect($redirect_to);
                    exit();
                }
            }
        }
    }
}

Proble with dirty trick. If the id we are passing as get parameter
exists in wp_users table then with no verification that will be logged
in .

更新资料

我创建了一个user_Meta,然后重定向到个人资料页面,并在验证登录登录用户删除了userMeta,就像OTP一样.如果可能的话,尝试使其更好.

代码下方:-

if ( $wpdb->insert_id ){  //that is registration with instagram
    $temporary_token = sha1(rand());
    update_user_Meta( $wpdb->insert_id, 'temporary_token', $temporary_token);
   ?>
    <script>jQuery(document).ready(function(){ window.location.href = "<?PHP echo get_bloginfo('url') . '/profile/?id=' . $wpdb->insert_id . '&token=' . $temporary_token; ?>";});</script>
   <?PHP
}

接着

add_action( 'wp', 'login_current_user' );
    function login_current_user(){
        if ( is_page() && get_the_id() == 863 ){
            if ( isset( $_GET['id'] ) ){
                if ( !is_user_logged_in() ) {
                    $user_id = $_GET['id'];
                    $user = get_user_by( 'id', $user_id );
                    if ( $_GET['token'] == get_user_Meta( $user_id, 'temporary_token', true ) ){
                        delete_user_Meta( $user_id, 'temporary_token', $_GET['token'] ); 
                        wp_clear_auth_cookie();
                        wp_set_current_user( $user_id, $user->user_login );
                        wp_set_auth_cookie( $user_id, true );
                        do_action( 'wp_login', $user->user_login );
                        if ( is_user_logged_in() ){
                            $redirect_to=site_url() . '/profile';
                            wp_safe_redirect($redirect_to);
                            exit();
                        }
                    }
                }
            }
        }
    }

解决方法:

如果在调用wp_clear_auth_cookie()或wp_set_auth_cookie()之前已发送了头,则两者都不起作用,因为两者都依赖于PHP的setcookie函数.在发送标题之前,将执行after_setup_theme操作,因此,对其进行钩挂并在其中设置cookie应该可以解决此问题.

function myPlugin_createuser(){
  // Probably need to put code that creates user here too otherwise $user_created will never return true
  if( $user_created ) {
      $new_user = get_user_by( 'id', $user_created ); 
      if ( !is_user_logged_in() ) {
          wp_clear_auth_cookie();
          wp_set_current_user( $user_created, $new_user->user_login );
          wp_set_auth_cookie( $user_created, true );
          do_action( 'wp_login', $new_user->user_login );
      }
  } 
}

add_action( 'after_setup_theme', 'myPlugin_createuser' );

更新:

如果要在触发createuser函数之前输出视图元素,它将无法正常工作,因此我们需要确保它们彼此完全独立地运行.下面,我整理了一个有关如何实现此目标的简单示例-在视图中,我们输出一个传递GET参数的链接,该参数由插件拾取,并在呈现任何内容之前运行操作,从而允许我们设置Cookie .

my-plugin.PHP

// Note: you'll need to include a completed version of myPlugin_createuser() function as above for these examples to work
add_shortcode( 'my-plugin', function() {  
   // I've used a GET request for simplicity- a form + POST request may be more practical for your purposes and will prevent caching issues.
   echo "<a href='?my_plugin_login_user=1'>Login</a>";
});

// Check for our GET parameter 
if( isset( $_GET['my_plugin_login_user'] ) ) {
  // nothing should be rendered yet as plugin template hasn't even started loading yet so cookies should set fine
  add_action( 'plugins_loaded', 'myPlugin_createuser' ); 
}

page-my-template.PHP

<div> ...
    <?PHP 
        do_shortcode( 'my-plugin' ); 
    ?>
</div>

更新2:
如果使用Instagram身份验证API,则概述为https://www.instagram.com/developer/authentication/的显式流程(下面使用的大多数示例均来自此处)可能是最好的方法.下面我将简要介绍如何实现它.大部分内容都是从那里获取的,并添加了注释.

用户发送到https://api.instagram.com/oauth/authorize/?client_id=CLIENT-ID&redirect_uri=REDIRECT-URI&response_type=code

您可以在回调URL上包含wordpress用户ID作为参数,或者如果尚未创建用户,并且需要维护状态,则需要生成一个临时令牌,稍后可以使用该令牌与数据或在不敏感的情况下存储该数据客户端,这可能会变得更容易和更好,因为它不需要用户登录即可运行.

用户然后将登录

关于此步骤,无需多说-如果发生错误,它们将被重定向到http:// your-redirect-uri?error = access_denied& error_reason = user_denied& error_description =用户拒绝了您的请求

如果登录成功,用户将被重定向到http:// your-redirect-uri?code = CODE

重定向URL上传回的CODE,我们可以兑换访问令牌.

因此,从这里开始,我们可以采用多种方法来处理它,但实际上,我们需要的是重定向的终结点,在发送任何HTTP响应正文之前,我们有足够的控制权来发送HTTP标头.

解决此问题的方法(并非详尽列表):

>有条件地允许页面上的Instagram身份验证(如您的示例).这具有不需要额外重定向的优点.
>自定义页面模板
>手动引导wordpress的外部脚本执行了我们需要的操作,然后重定向

因此,现在完成端点设置后,我们需要兑换代码获取访问令牌.改编自https://gist.github.com/arturmamedov/7f5a90b85a20e06e344ebb88dc898d25的此代码

$uri = 'https://api.instagram.com/oauth/access_token'; 
$data = [
    'client_id' => '213esdaedasdasd12...YOUR_CLIENT_ID', 
    'client_secret' => 'a8b4aaf06c0da310...YOUR_CLIENT_SECRET', 
    'grant_type' => 'authorization_code', 
    'redirect_uri' => 'http://www.YOUR_REDIRECT_URL.it',      // The exact redirect URL as used prevIoUsly
    'code' => $_GET['code']  
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $uri); // uri
curl_setopt($ch, CURLOPT_POST, true); // POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // POST DATA
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // RETURN RESULT true
curl_setopt($ch, CURLOPT_HEADER, 0); // RETURN HEADER false
curl_setopt($ch, CURLOPT_NOBODY, 0); // NO RETURN BODY false / we need the body to return
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); // VERIFY SSL HOST false
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); // VERIFY SSL PEER false
$result = json_decode(curl_exec($ch));

$result将是JSON响应的对象表示形式:

{
"access_token": "fb2e77d.47a0479900504cb3ab4a1f626d174d2d",
"user": {
    "id": "1574083",
    "username": "snoopdogg",
    "full_name": "Snoop Dogg",
    "profile_picture": "..."
  }
}

在这里,我们仅创建我们的用户/使用wordpress进行身份验证,然后重定向到所需的页面/呈现模板(如果通过条件挂钩进行处理,则无需重定向),并在需要时恢复页面状态.

相关文章

我们有时候在定制WORDPRESS主题的时候,由于菜单样式的要求我...
很多朋友在做wordpree主题制作的时候会经常遇到一个问题,那...
wordpress后台的模块很多,但并不是每个都经常用到。介绍几段...
从WordPress4.2版本开始,如果我们在MYSQL5.1版本数据中导出...
很多网友会遇到这样一个问题,就是WordPress网站上传图片、附...
对于经常要在文章中出现代码的IT相关博客,安装一个代码高亮...