Categories
php Plugin wordpress

WP REST with JWT

Using the WordPress REST API with JWT authentication

Step 1. Install this plugin => https://wordpress.org/plugins/advanced-access-manager/. The free version will suffice. This goes on the site you will be xtracting data from. The REST API must be enabled in the WordPress settings.

Step 2. Configure the plugin and on it’s Settings tab add the Secret as per this page => https://aamplugin.com/article/how-to-authenticate-wordpress-user-with-jwt-token

On the Page pulling the data from the above server, use the following PHP code :

function getToken()
{
	$token="";
	$html="<div>";
	
	$postRequest = array(
		'username' => 'ANY_ADMIN_USERNAME',
		'password' => 'THE_PASSWORD_FOR_SAID_USER'
	);
	$h=http_build_query($postRequest);
	$ch = curl_init("https://YOUR_SERVER_NAME.COM/wp-json/aam/v1/authenticate");
	curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$h);
	curl_setopt($ch, CURLOPT_FAILONERROR, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_VERBOSE, true);
	
    $server_output = curl_exec ($ch);
	$info = curl_getinfo($ch);
	//$html="<pre>".print_r($info,true)."</pre>";
	//echo $html;
    if ($server_output === false)
	{
        die('Error getting JWT token on WordPress for API integration.');
    }
    $server_output = json_decode($server_output);

    if ($server_output === null && json_last_error() !== JSON_ERROR_NONE)
	{
        die('Invalid response getting JWT token on WordPress for API integration.');
    }
    if (!empty($server_output->token))
	{
        $token = $server_output->token; # Token is here
        curl_close ($ch);
        return $token;
    }
	else
	{
        die('Invalid response getting JWT token on WordPress for API integration.');
    }
    return false;
}

The when you need the token, call it like such :

$mytoken=getToken();

And that’s about it…..

Categories
Linux wordpress

WordPress Security

This applies to self-managed Apache2 servers. Shared servers require different permissions, for example wp-config : set that file’s permissions to 440 or 400.

Site Lockdown

File permissions to lock down website, from the websites home folder. Do this from the root directory for example and you will break your server.


chown root:root  -R * 
find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;

Change the folder ownership of the site to root

chown root:root -R * 

Change to wp-content/uploads (to allow uploads)

chown www-data:www-data -R * 

To edit any files via ftp change that ownership to the ftpuser:wwwdata

chown username:www-data -R * 

If you get asked for ftp details when trying to upgrade wordpress, or any plugins or themes, you need to add the following to wp-config.php

define('FS_METHOD','direct');

Refer to https://wordpress.org/support/article/hardening-wordpress/ for more details, especially those regarding MySql.

On the server install

Denyhosts

Disable root login

Install rkhunter (root kit hunter) to check for vulnerabilities.

sudo apt-get install rkhunter

Perform check with

sudo rkhunter --check --skip-keypress

or on first run

sudo rkhunter --checkall --skip-keypress

And keep it updated with

sudo rkhunter --update

For Ubuntu server you may have to “fix” /etc/rkhunter.conf

UPDATE_MIRRORS=0 to UPDATE_MIRRORS=1
MIRRORS_MODE=1 to MIRRORS_MODE=0
WEB_CMD="/bin/false" to WEB_CMD=""
Categories
Linux Raspberry PI

SSL Localhost

To enable ssl on a localhost website, and stop Chrome from showing is as “unsafe” ….

Pertains to Ubuntu 18.04 Bionic, and running Apache 2.4.29

Create localhost.cnf

HOME = .
RANDFILE = $ENV::HOME/.rnd
oid_section = new_oids

[ new_oids ]
tsa_policy1 = 1.2.3.4.1
tsa_policy2 = 1.2.3.4.5.6
tsa_policy3 = 1.2.3.4.5.7

[ ca ]
default_ca = CA_default		# The default ca section

[ CA_default ]
dir = ./localhostCA		# Where everything is kept
certs = $dir/certs		# Where the issued certs are kept
crl_dir = $dir/crl		# Where the issued crl are kept
database = $dir/index.txt	# database index file.
	# several certs with same subject.
new_certs_dir = $dir/newcerts		# default place for new certs.
certificate = $dir/cacert.pem 	# The CA certificate
serial = $dir/serial 		# The current serial number
crlnumber = $dir/crlnumber	# the current crl number
	# must be commented out to leave a V1 CRL
crl = $dir/crl.pem 		# The current CRL
private_key = $dir/private/cakey.pem# The private key
RANDFILE = $dir/private/.rand	# private random number file
x509_extensions = usr_cert		# The extensions to add to the cert
name_opt = ca_default		# Subject Name options
cert_opt = ca_default		# Certificate field options
default_days = 365			# how long to certify for
default_crl_days = 30			# how long before next CRL
default_md = default		# use public key default MD
preserve = no			# keep passed DN ordering
policy = policy_match

[ policy_match ]
countryName = match
stateOrProvinceName = match
organizationName = match
organizationalUnitName = optional
commonName = supplied
emailAddress = optional

[ policy_anything ]
countryName = optional
stateOrProvinceName = optional
localityName = optional
organizationName = optional
organizationalUnitName = optional
commonName = supplied
emailAddress = optional

[ req ]
default_bits = 2048
default_keyfile = privkey.pem
distinguished_name = req_distinguished_name
attributes = req_attributes
x509_extensions = v3_ca	# The extensions to add to the self signed cert
string_mask = utf8only
req_extensions = v3_req

[ req_distinguished_name ]
countryName = Country Name (2 letter code)
countryName_default = AU
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = Some-State
localityName = Locality Name (eg, city)
0.organizationName = Organization Name (eg, company)
0.organizationName_default = Internet Widgits Pty Ltd
organizationalUnitName = Organizational Unit Name (eg, section)
commonName = Common Name (e.g. server FQDN or YOUR name)
commonName_max = 64
emailAddress = Email Address
emailAddress_max = 64

[ req_attributes ]
challengePassword = A challenge password
challengePassword_min = 4
challengePassword_max = 20
unstructuredName = An optional company name

[ usr_cert ]
basicConstraints = CA:FALSE
nsComment = "OpenSSL Generated Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer

[ v3_req ]
basicConstraints = CA:FALSE
keyUsage = nonRepudiation, digitalSignature, keyEncipherment
subjectAltName = @alt_names

[ v3_ca ]
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid:always,issuer
basicConstraints = critical, CA:TRUE, pathlen:3
keyUsage = critical, cRLSign, keyCertSign
nsCertType = sslCA, emailCA

[ crl_ext ]
authorityKeyIdentifier = keyid:always

[ proxy_cert_ext ]
basicConstraints = CA:FALSE
nsComment = "OpenSSL Generated Certificate"
subjectKeyIdentifier = hash
authorityKeyIdentifier = keyid,issuer
proxyCertInfo = critical,language:id-ppl-anyLanguage,pathlen:3,policy:foo

[ tsa ]
default_tsa = tsa_config1	# the default TSA section

[ tsa_config1 ]
dir = ./demoCA		# TSA root directory
serial = $dir/tsaserial	# The current serial number (mandatory)
crypto_device = builtin		# OpenSSL engine to use for signing
signer_cert = $dir/tsacert.pem 	# The TSA signing certificate
	# (optional)
certs = $dir/cacert.pem	# Certificate chain to include in reply
	# (optional)
signer_key = $dir/private/tsakey.pem # The TSA private key (optional)
signer_digest = sha256			# Signing digest to use. (Optional)
default_policy = tsa_policy1		# Policy if request did not specify it
	# (optional)
other_policies = tsa_policy2, tsa_policy3	# acceptable policies (optional)
digests = sha1, sha256, sha384, sha512  # Acceptable message digests (mandatory)
accuracy = secs:1, millisecs:500, microsecs:100	# (optional)
clock_precision_digits = 0	# number of digits after dot. (optional)
ordering = yes	# Is ordering defined for timestamps?
	# (optional, default: no)
tsa_name = yes	# Must the TSA name be included in the reply?
	# (optional, default: no)
ess_cert_id_chain = no	# Must the ESS cert id chain be included?
	# (optional, default: no)
ess_cert_id_alg = sha1	# algorithm to compute certificate
	# identifier (optional, default: sha1)

[ alt_names ]
DNS.1 = localhost
DNS.2 = *.localhost


Then use openssl to generate the certificates in 3 steps

openssl req -new -x509 -subj "/CN=localhost" -extensions v3_ca -days 3650 -key ca.key.pem -sha256 -out ca.pem -config localhost.cnf
openssl req -subj "/CN=localhost" -extensions v3_req -sha256 -new -key ca.key.pem -out localhost.csr
openssl x509 -req -extensions v3_req -days 3650 -sha256 -in localhost.csr -CA ca.pem -CAkey ca.key.pem -CAcreateserial -out localhost.crt -extfile localhost.cnf

Edit /etc/apache2/sites-available/default-ssl.conf as below

<IfModule mod_ssl.c>
        <VirtualHost _default_:443>
                ServerAdmin webmaster@localhost

                DocumentRoot /var/www/html

                ErrorLog ${APACHE_LOG_DIR}/error.log
                CustomLog ${APACHE_LOG_DIR}/access.log combined

                SSLEngine on

                SSLCertificateFile      /home/gavin/ssl/localhost.crt
                SSLCertificateKeyFile /home/gavin/ssl/ca.key.pem

                <FilesMatch "\.(cgi|shtml|phtml|php)$">
                                SSLOptions +StdEnvVars
                </FilesMatch>
                <Directory /usr/lib/cgi-bin>
                                SSLOptions +StdEnvVars
                </Directory>

        </VirtualHost>
</IfModule>

Enable the site

sudo a2ensite default-ssl

… and restart Apache2

sudo systemctl restart apache2

As things stand you will be asked for the certificate key password used in the certificate creation process.

The go into chrome and call https://localhost. The usual warnings will appear about an untrusted site. Go to advanced and select ‘Proceed to unsafe site’

View the certificate and export it.

Got to chrome settings and import this certificate under ‘Servers’. Change the certificate settings to be able to identify sites.

In the same settings under ‘Authorities’ import ca.pem, and change it’s settings to ‘Identify Websites’

Restart chrome and all should be in order. Just deal with any issues as they may arise. An example being you might have to create a .rnd folder first, etc.

Categories
php Plugin wordpress

WordPress Basic Plugin

Below is a very simple working example of a plugin. Create a directory in your plugins directory, create a php file and copy the below into it.

Then from the wordpress plugins menu simply activate it.

Just know that this plugin does absolutely nothing other than to show the basic setup, including public and protected variables.

<?php
/*
	Plugin Name: Plugin Demo
	Plugin URI: https://southcoasthosting.com/
	Description: Just a plugin demo to show how to set up the class and add an admin menu item
	Author: Gavin Simpson
	Version: 1.0
	Author URI: https://southcoasthosting.com
*/

class plugindemo
{
	protected $namespace;
	public $posttype="plugindemo";
	public static function init()
	{
		$class = __CLASS__;
		new $class;
	}
	public function __construct()
	{
		$this->namespace=test;
		add_action( 'admin_menu', array($this,'my_plugin_menu'),10,0);
	}
	public function test_function($namespace)
	{
		$this->namespace=$namespace;
	}
	function my_plugin_menu()
	{
		
		if (current_user_can('administrator'))
		{
			add_menu_page( 'SCHS Menu', 'SCHS Menu', 'manage_options', 'schs-menu', array($this,'my_plugin_menu_page_callback'),null,1);
			add_submenu_page( 'schs-menu', 'SCHS Submenu', 'SCHS Submenu', 'manage_options', 'schs-submenu', array($this,'schs_submenu_page_callback'));
		}
	}
	function my_plugin_menu_page_callback()
	{
		echo "<div class='wrap'>";
		echo "<h1>".esc_html(get_admin_page_title())."</h1>";
		echo "</div>";
	}
	function schs_submenu_page_callback()
	{
		echo "<div class='wrap'>";
		echo "<h1>".esc_html(get_admin_page_title())."</h1>";
		echo "</div>";		
	}
}

add_action('init',array('plugindemo','init'));
?>

Categories
Linux Raspberry PI

Ubuntu Must Have Apps

As Open Office is part of the standard Ubuntu install, like other software installed as default, I have not listed it.

There are a number of must have applications needed to get the most out of Uubuntu 18.04, but first thing to do is change the deskop. Ubuntu’s standard is way too slow and reminds me of the bad old Microsoft Windows days.

The solution is the xfce4 Desktop.

sudo apt-get install xubuntu-desktop
Multimedia

VLC for watching movies

sudo apt-get install vlc

Kazam for taking screenshots and video capture of desktop

sudo apr-get install kazam

Gimp for editing images

sudo apt-get install gimp

OpenSCAD for CAD drawing

sudo add-apt-repository ppa:openscad/releases
sudo apt-get update
sudo apt-get install openscad
Development

Notepadqq – text editor

sudo add-apt-repository ppa:notepadqq-team/notepadqq
sudo apt-get update
sudo apt-get install notepadqq
3d Printing

Repetier-host for 3d printing – AppImage

https://www.repetier.com/download-now/
CNC Cutting

cncjs – AppImage

https://github.com/cncjs/cncjs/releases
Categories
Linux Raspberry PI

Linux miscellaneous

Pertains mostly to Ubuntu 18.04.4 and Apache 2.4.29

Get Ubuntu version

lsb_release -a

Get Apache version

apache2 -v

Get MySql version

mysql --version

Find Files and hide all permission denied messages

find /start_directory -name filename 2>/dev/null

Copy file with ssh from server to localhost

scp user@server:/directory_from/filename.txt /local_directory/

Copy file from localhost to server with ssh

scp file_to_copy.txt user@servername:/directory_to_copy_to/

Copy directory from server recursively with ssh

scp -r user@server:/directory_from /local_directory/

Copy directory to server from localhost recursively with ssh

$ scp -r /local_directory/ user@server:/server_directory/

Copy directory with ftp recursively into current directory

sudo wget -r ftp://user:password@server/folder1/folder2/filename

To use ftp to put files onto a server recursively

ncftpput -R -v -u user -p password -P 21 ftp.server.com /directory_to_copy_to /directory_to_copy_from

Import .sql into MySql

mysql -uUser -pPassword Database < sql_file.sql

To export MySql table to .sql file

sudo mysqldump database table -uUsername -pPassword > sql_file.sql
Categories
MySql php wordpress

Exporting/Importing Woocommerce Orders with SQL 2020

Covers WordPress version 5.3.2

No matter how you use the SQL, be it on the command line, PhpMyAdmin or PHP, These are just the SQL commands needed.

There are 4 tables invlovled not counting the variable product data. I’ll be adding that as soon as a get a free moment.

  • wp_posts
  • wp_postmeta
  • wp_woocommerce_order_items
  • wp_woocommerce_order_itemmeta

wp_posts are where the main orders are kepts, with the post_id being the actual order ID. The other 3 tables use this id to attach items, customer details, etc to the order.

wp_postmeta contains the customer data.

wp_woocommerce_order_items contains the items that are ordered.

wp_woocommerce_order_itemmeta contains the price, etc of the items ordered.

So, on to the SQL by example

SELECT * FROM wp_posts WHERE post_type="shop_order"  and date(post_date)=date("2020-02-25")

The main thing is the “shop_order” post type. If you leve out the date part of the SQL then obviously you will get all orders in the database. If using PhpMyAdmin you can then simply export the results, os CLI pipe to a file, whatever, saving the data into something like wp_posts.sql

Now assuming a list of orders with post_id’s of 11538, 11541,11542, 11543, 11533, 11534, 11535, 11536, 11537, 11539, 11540 was resturned. We need to get all the info for those numbers starting with wp_postmeta.

SELECT * FROM wp_posts WHERE post_type="shop_order"  and date(post_date)=date("2020-02-25")

Save the results to wp_postmeta.sql.

SELECT * FROM wp_woocommerce_order_items WHERE order_id in (11538,11541,11542,11543,11533,11534,11535,11536,11537,11539,11540)

This will give us the items ordered, so save teh results to wp_woocommerce_order_items.sql.

SELECT * FROM wp_woocommerce_order_itemmeta WHERE order_item_id in (11538,11541,11542,11543,11533,11534,11535,11536,11537,11539,11540)

And save these results to wp_woocommerce_order_itemmeta.sql.

So now we have 4 sql files containing the orders and order data that we want to import, possibly on another server. The assumption at this point is the users exist already, otherwise you will have to export the users as well which is beyond the scope of this blog.

If would/could be a very, very bad idea so simply import as it, as chances are the key values are already in use.

The plan therefore is simple, edit the .sql files and change them to a number higher that what exists in the database you are importing to.

So you would change the post_id in the first file, then edit the second file to point to the new numbers you created, as well as create new meta_id values, and so forth. All the id numbers in the 4 files must match up.

Then you can simply import the 4 files into the new database, and there you go, your orders have been imported.

Summary

SELECT * FROM wp_posts WHERE post_type="shop_order"  and date(post_date)=date("2020-02-25")

SELECT * FROM wp_postmeta WHERE post_id in (11538,11541,11542,11543,11533,11534,11535,11536,11537,11539,11540)

SELECT * FROM wp_woocommerce_order_items WHERE order_id in (11538,11541,11542,11543,11533,11534,11535,11536,11537,11539,11540,11545)

SELECT * FROM wp_woocommerce_order_itemmeta WHERE order_item_id in (11538,11541,11542,11543,11533,11534,11535,11536,11537,11539,11540,11545)

Thank you for your time, I hope this helps.

Categories
Linux Viynl Cutter

Sharing a Viynl Cutter over the Network in Linux

This setup works for a cheap Chinese no name brand Cutting Plotter I use.

On the host PC add a new printer and set the printer model to “Raw Queue

Set the device URI to, for example, serial:/dev/ttyUSB0?baud=9600. This assumes the servial device is attached to USB port 0.

Make sure it is shared.

On the slave PC simply add the network printer

Enjoy. 

Categories
Inkscape Linux Viynl Cutter

Setting up Inkscape for use with a Vinyl Cutter using Inkcut

Step 1

Download and install the InkCut Extension from the InkCut sourceforge page.

Step 2

Install the following linux libraries :


		sudo apt-get install python-gtk2-dev
		sudo apt-get install python-cups
		sudo apt-get install python-serial
		

Using InkCut to perform the cut

Step 1

Select the objects you wish to cut

Step 2

Ungroup the selected objects

Step 3

Go “Path->Object to Path”

Step 4

Go “Path->Union”

Step 5

Extensions->Cutter/Plotter->Inkcut v1.0

Categories
Linux Raspberry PI

Raspberry PI Setup

  • use GParted to format SD to win32.
  • sudo dd bs=4M status=progress if=~/Downloads/2018-06-27-raspbian-stretch.img of=/dev/sdc; sync
    NB note /dev/sdc, not /dev/sdb1. i.e. Must point to physical device, not partition.
  • Edit config.txt on the SD to set hdmi hot plug support.
  • put sd in the pi, plug in kb and monitor and boot.
  • after install and upgrade process (including setting new password), go to pi configuration and enable ssh and vnc (and camera if attached)
  • reboot pi for changes to take effect.
  • install vnc viewer on pc, and log into the pi.
  • tada, you are up and running on the pi.