Skip to content

Instantly share code, notes, and snippets.

@t-asa2000
Last active September 21, 2021 10:01
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 t-asa2000/3dfcbbacfc7bb2b12d8d9770fa660211 to your computer and use it in GitHub Desktop.
Save t-asa2000/3dfcbbacfc7bb2b12d8d9770fa660211 to your computer and use it in GitHub Desktop.
[PHP] Create wordpress user with Slack command [Register to WP from Slack API]

Register to WP from Slack API v1.2.0

1. Create slack app in your workspace

1-a. Create new app

You can decide 'App name' freely.
https://api.slack.com/apps

1-b. Setup 'Bot token scopes'

You have to add these scopes to the 'Bot token'.
https://api.slack.com/authentication/basics#scopes

  • commands

2. Install this PHP script (with config file) in the WordPress directory

2-a. Copy and paste signing secret

Please access to your app -> 'Basic infomation', and copy 'Signing secret'.
https://api.slack.com/authentication/verifying-requests-from-slack

Open the PHP config file in your editor, and paste 'Signing secret'.

2-b. Upload the PHP script

You have to upload the PHP files with FTP to your WordPress site directory.

3. Setup slash command

You have to setup slash command in your app settings page.
https://api.slack.com/interactivity/slash-commands

Slash command details

Please rewrite for your environment.

  • Command: /wpsubmit (Default)

    • Request URL: https://yoursite.com/slack_register.php
    • Short Description: (Freely)
    • Usage: [Login ID] [Public ID(Slug)] [E-mail]
  • Command: /wplogin (Default)

    • Request URL: https://yoursite.com/slack_register.php
    • Short Description: (Freely)
    • Usage: [Login ID]

4. Reinstall your app

Please access to your app -> 'Install App', and click 'Reinstall to workspace'.

How to use

Create WordPress account

/wpsubmit [Login ID] [Public ID(Slug)] [E-mail]

Public ID(Slug) is used in the author archive page (.../authors/[Public ID]).

This app provides URL for login(one-time). If you want to login from browser, you have to change the password in wp-admin. (Your password is auto generated random long string.)

Login WordPress account

/wplogin [Login ID]

Link your WordPress account to Slack ID

  1. Login to WordPress by the web browser.
  2. Send command /wplogin [Login ID].
  3. App shows next command in the web browser. Copy and paste to Slack, and run.

Changelog

  • v1.2.0 : Add function to link an existing WordPress account.
  • v1.1.0 : Onetime token function was mounted.
  • v1.0.1 : $result discriminant fixed.
  • v1.0.0 : Published.
<?php
/* Register to WP from Slack API v1.2.0 */
/* Slack Command: <COMAND_NAME> [Login ID] [Public ID(Slug)] [E-mail] */
require_once( dirname( __FILE__ ) . '/wp-load.php' ); //WP core
require_once( dirname( __FILE__ ) . '/slack_register_config.php' ); //Config
/* [Function] Check request and sign */
function checksign(){
if(!isset($_SERVER['HTTP_X_SLACK_REQUEST_TIMESTAMP'],$_SERVER['HTTP_X_SLACK_SIGNATURE'])) return false;
$data = 'v0:'.$_SERVER['HTTP_X_SLACK_REQUEST_TIMESTAMP'].':'.file_get_contents('php://input');
return ('v0='.hash_hmac('sha256', $data, SLACK_SECRET) == $_SERVER['HTTP_X_SLACK_SIGNATURE']);
}
/* [Function] Generate one-time signin URL(token) */
function generate_login_url($id,$tokenmode = false){
$token = bin2hex(openssl_random_pseudo_bytes(32));
$hash = wp_hash_password($token);
$limit = time()+600;
update_user_meta($id,'onetimetoken',$hash);
update_user_meta($id,'onetimetokenlimit',$limit);
if($tokenmode) return $token;
return site_url().'/'.basename(__FILE__).'?auth='.$id.'&token='.$token;
}
/* [Function] One-time signin */
function auth(){
$hash = get_user_meta($_GET['auth'],'onetimetoken',true);
$limit = get_user_meta($_GET['auth'],'onetimetokenlimit',true);
/* Check the hash */
if(time() <= intval($limit) && wp_check_password($_GET['token'],$hash)){
/* Check linking to Slack ID */
if(get_user_meta($_GET['auth'],'slackhash',true)){
delete_user_meta($_GET['auth'],'onetimetoken');
delete_user_meta($_GET['auth'],'onetimetokenlimit');
wp_set_auth_cookie($_GET['auth'],true,true);
wp_redirect(admin_url());
/* Generate token to link Slack ID */
}else if(get_current_user_id() == $_GET['auth']){
echo 'Your WordPress account is not linked to Slack ID.<br>
Please run this command in Slack. The token is disabled after 10 minutes.<br>'.COMMAND_LOGIN.' '.
wp_get_current_user()->user_login.' '.generate_login_url($_GET['auth'],true);
}else{
echo '<a href="'.wp_logout_url().'">Please login again as the correct user.</a>';
}
}
exit;
}
/* [Function] User Activation */
function submit($parameters){
/* Array of userdata */
$userdata = [
'user_login' => $parameters[0],
'user_nicename' => $parameters[1],
'user_email' => $parameters[2],
'user_pass' => wp_generate_password(PASS_LENGTH,true,true),
'role' => ROLE
];
/* Insert user */
$id = wp_insert_user( $userdata ) ;
/* Link to Slack ID */
if($id){
update_user_meta($id,'slackhash',wp_hash_password($_POST[user_id]));
/* Success responce */
return [
true,
'Login ID: '.$parameters[0],
'Public ID(Slug): '.$parameters[1],
'E-mail: '.$parameters[2],
'Onetime Login(10min.): '.generate_login_url($id),
'If you change the password, please do yourself in wordpress admin.'
];
}
/* Error responce */
return [false,'Usage: '.COMMAND_SUBMIT.' [Login ID] [Public ID(Slug)] [E-mail]'];
}
/* [Function] User login */
function login($parameters){
$user = get_user_by('login',$parameters[0]);
if(!$user) return [false, 'Login ID is incorrect.'];
$slackhash = get_user_meta($user->ID,'slackhash',true);
/* Check Slack ID */
if($slackhash ? wp_check_password($_POST[user_id],$slackhash) : !isset($parameters[1])){
/* Success responce */
return [true, 'Onetime Login(10min.): '.generate_login_url($user->ID)];
/* Check the hash */
}else if(isset($parameters[1])){
$hash = get_user_meta($user->ID,'onetimetoken',true);
$limit = get_user_meta($user->ID,'onetimetokenlimit',true);
if(time() <= intval($limit) && wp_check_password($parameters[1],$hash)){
/* Link to Slack ID */
update_user_meta($user->ID,'slackhash',wp_hash_password($_POST[user_id]));
/* Success responce */
return [true,
'Success linking your WordPress account to Slack ID.',
'Onetime Login(10min.): '.generate_login_url($user->ID)];
}else{
/* Error responce */
return [false, 'Login ID or token is incorrect.'];
}
}else{
/* Error responce */
return [false, 'Login ID is incorrect.'];
}
}
/* [Function] Generate JSON to responce for Slack API */
function generate_json($messages){
$blocks = [];
foreach ($messages as $m){
$blocks[] = [
'type'=>'section',
'text'=>[
'type'=>'mrkdwn',
'text'=>$m
]
];
}
return ['blocks' => $blocks];
}
/* Function select */
if(isset($_GET['auth'],$_GET['token'])){
auth();
}else if(checksign()){
$parameters = explode(' ',$_POST['text']);
if(count($parameters) > 2 && $_POST['command'] == COMMAND_SUBMIT) $messages = submit($parameters);
if(count($parameters) && $_POST['command'] == COMMAND_LOGIN) $messages = login($parameters);
}else{
$messages = [false];
}
/* Generate JSON to responce for Slack API */
$messages[0] = $messages[0] ? 'OK' : 'ERROR';
$json = generate_json($messages);
/* Echo JSON */
header("Content-Type: application/json; charset=utf-8;Access-Control-Allow-Origin: *");
echo json_encode($json);
?>
<?php
/* Register to WP from Slack API Config */
define('SLACK_SECRET','xxxx'); //Signing secret (Slack API)
define('COMMAND_SUBMIT','/wpsubmit'); //Slash command(Submit)
define('COMMAND_LOGIN','/wplogin'); //Slash command(Login)
define('PASS_LENGTH',100); //Default password length
define('ROLE','editor'); //Default role
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment