Discuz! X3.5 使用自行開發的會員登入

首先要在 source/class/discuz/discuz_application.php 中,修改 init(),在 _init_user(); 之後加入檢查

public function init() {
    if(!$this->initated) {
        $this->_init_db();
        $this->_init_setting();
        $this->_init_user();  // 初始化 Discuz! 會員
        $this->check_my_login(); // 在這裡加入檢查登入狀態
        $this->_init_session();
        $this->_init_mobile();
        $this->_init_cron();
        $this->_init_misc();
    }
    $this->initated = true;
}

然後同一個class內找地方加入

public function check_my_login() {
    session_start();
    
    // 這是自己要另外寫的API,用於回傳登入狀態
    $api = 'https://example.com/check';
    $response = json_decode(file_get_contents($api), true);

    if (!$response || !isset($response['uid'])) {
        // 未登入,跳轉到指定登入頁
        header("Location: https://example.com/login");
        exit;
    }

    $uid = intval($response['uid']);
    $username = addslashes($response['username']);
    $email = addslashes($response['email']);

    // 檢查會員是否存在
    $user = DB::fetch_first("SELECT uid FROM ".DB::table('common_member')." WHERE uid='$uid'");
    
    if (!$user) {
        // 自動創建 Discuz! 會員
        $salt = substr(uniqid(rand()), -6);
        $password = md5(md5(uniqid()) . $salt);
        DB::query("INSERT INTO ".DB::table('common_member')." (uid, username, password, email, salt) 
                   VALUES ('$uid', '$username', '$password', '$email', '$salt')");
        DB::query("INSERT INTO ".DB::table('common_member_count')." (uid) VALUES ('$uid')");
        DB::query("INSERT INTO ".DB::table('common_member_status')." (uid, regdate) VALUES ('$uid', '".time()."')");
        DB::query("INSERT INTO ".DB::table('common_member_profile')." (uid) VALUES ('$uid')");
        DB::query("INSERT INTO ".DB::table('common_member_field_forum')." (uid) VALUES ('$uid')");
        DB::query("INSERT INTO ".DB::table('common_member_field_home')." (uid) VALUES ('$uid')");
    }

    // 設置 Discuz! 登入 cookie,讓會員保持登入狀態
    dsetcookie('auth', authcode("$uid\t$password", 'ENCODE'), 2592000);
}

另外自己寫的API這邊,要回傳這樣

{
  "uid": 12345,
  "username": "testuser",
  "email": "[email protected]"
}