Monday, September 23, 2024

Software Testing on Non-functional areas

Software testing is an approach to ensure software is made with the highest reliability possible. Non-functional testing is testing of the software not related to the system itself. It is done after Functional testing have taken place.

Its common to use automation tools to perform these test in areas to improve the performance of the software, ensure high-security levels, make the software more user-friendly, usability and help the software compliance with customer needs. Sometimes, its compatibility with other systems and previous versions are also measured.

Examples of test

Load testing, Stress testing, Accessibility testing

Metrics are created for non-functional in order to be successful, example response time, speed of the software itself, and load time. It depends on the investment on the software, where the amount and categories of testing will be determined. It would be good to have testing in all categories, but resources, cost and time always limits its implementation.

Broad category of testing

  • Stress Test
  • Volume Test
  • Maintainability Test
  • Security Test
  • Scalability Test
  • Failover Test
  • Usability Test
  • Configuration Test
  • Load Test

Continuous integration (CI) is an approach where developers regularly merge their code changes into a central repository, after which automated builds and tests are run. It is common to use containers to perform such test.

Common tools for non-functional testing (Affordable ones)

  • Apache JMeter,
  • Selenium
  • Nessus Essentials
  • New Relic
  • SonarQube
Let me know if mentioned any wrongly. :)

Friday, April 5, 2024

RabbitMQ implementation in Laravel and Linux Centos 8

The use of multiple servers with dedicated functionality can communicate with each other through API and notifications. 

Overview

Example where a backend server that performs a task followed by notification to user via Email, while to another server through PUSH notification.

email and notifications
The push allows communication between 2 computer systems through an agreed protocol. RabbitMQ is a message-queueing software also known as a message broker or queue manager, that provides such a service, implementing protocols AMQP 1.0 and MQTT 5. It is can be used under the Apache License 2.0 and Mozilla Public License 2.

In a simple description on its usage;
  1. A producer: Sends a message to RabbitMQ with a specified exchange (direct, topic, or fanout) and queue(s) name.
  2. RabbitMQ: Places the message to the queue(s).
  3. A consumer: Configured to retrieve message from a queue.
  4. A consumer: Check and retrieve message from the queue.
  5. RabbitMQ: Remove message from the queue
Communication with RabbitMQ can be simplified through the library amqplib that implements the machinery needed to make clients for AMQP 0-9-1.
Messaging queue

Steps
  1. Install RabbitMQ
  2. Configure RabbitMQ
  3. Add RabbitMQ package in a Laravel project
  4. Create a service of Laravel jobs or other automated function
  5. Create Laravel controller to publish and consume messages
  6. Tinker to test Producer
  7. Tinker to test Consumer

Install RabbitMQ

Lets imagine following environment;
  1. RabbitMQ server: IP 10.1.1.101
  2. Producer server: IP 10.1.1.102
  3. Consumer server: IP 10.1.1.103
On RabbitMQ, ensure PHP is installed, including the package socket. On this example, SELINUX is enabled.

On RabbitMQ, install the server application. 

curl -s https://packagecloud.io/install/repositories/rabbitmq/rabbitmq-server/script.rpm.sh | sudo bash
curl -s https://packagecloud.io/install/repositories/rabbitmq/erlang/script.rpm.sh | sudo bash
sudo yum makecache -y --disablerepo='*' --enablerepo='rabbitmq_rabbitmq-server'
sudo yum -y --disablerepo='*' --enablerepo='rabbitmq_rabbitmq-server' --enablerepo='rabbitmq_erlang'  install rabbitmq-server
rpm -qi rabbitmq-server
Name        : rabbitmq-server
Version     : 3.13.0
Release     : 1.el8
Architecture: noarch

Configure the server

By default, RabbitMQ uses port 5672, and for the web administration port 15672. Update the server hosts file with its domain name and enable the web based management
echo "127.0.0.1 rabbitmq.demo" | sudo tee -a /etc/hosts
sudo systemctl enable --now rabbitmq-server.service
sudo rabbitmqctl status 
sudo rabbitmq-plugins enable rabbitmq_management
ss -tunelp | grep 15672
sudo firewall-cmd --add-port={5672,15672}/tcp --permanent
sudo firewall-cmd --reload
Verify access: Open URL http://rabbitmq.demo:15672 on a web browser. Then ensure tall feature flags are viewable.

rabbitmqctl list_feature_flags
rabbitmqctl enable_feature_flag all

Create users

Create the initial administrator user as admin and a password.

sudo rabbitmqctl add_user admin SECRETPASSWORD

sudo rabbitmqctl set_user_tags admin administrator
sudo yum -y  --disablerepo='pgdg*'  install mlocate 
sudo updatedb

Create user to access from Producer and Consumer.
sudo rabbitmqctl add_user user1 SECRETPASSWORD
sudo rabbitmqctl set_user_tags user1 management,monitoring

Web console users
Create a virtual host, then click on username user1 and set permissions as required. Example, add to Topic permission with read/write regexp value as .*

Laravel support for rabbitmq

Create or use an existing laravel project.
composer require php-amqplib/php-amqplib
composer update
sudo semanage port -a -t http_port_t -p tcp 5672

Edit Laravel's .env file:
RABBITMQ_HOST=mem.hqcloak
RABBITMQ_IP=10.1.1.101
RABBITMQ_PORT=5672
RABBITMQ_VHOST="/"
RABBITMQ_LOGIN=user1
RABBITMQ_PASSWORD=SECRETPASSWORD
RABBITMQ_QUEUE="queue1"

Laravel rabbitmq service 

Create the file in app\Services\RabbitMQService.php . No examples is provided for usage of this service.
<?php
namespace App\Services;
use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Connection\AMQPSSLConnection;
use PhpAmqpLib\Message\AMQPMessage;
use PhpAmqpLib\Exchange\AMQPExchangeType;
use Illuminate\Support\Facades\Log;

class RabbitMQService
{
    protected $connection;
    protected $channel;
    protected $exchange = 'amq.topic';
    protected $queue = null;
    protected $routingKey = 'routing_key';
    protected $status = true;

    public function __construct()
    {
        $this->connection = new AMQPStreamConnection(
            env('RABBITMQ_HOST'),
            env('RABBITMQ_PORT'),
            env('RABBITMQ_LOGIN'),
            env('RABBITMQ_PASSWORD'),
            env('RABBITMQ_VHOST')
        );
        $this->channel = $this->connection->channel();
        /*
            name: $exchange
            type: direct
            passive: false // don't check if an exchange with the same name exists
            durable: false // the exchange will not survive server restarts
            auto_delete: true // the exchange will be deleted once the channel is closed.
        */
        $this->channel->exchange_declare($this->exchange, 'topic', false, true, false);
        /*
            name: $queue    // should be unique in fanout exchange. Let RabbitMQ create
                            // a queue name for us
            passive: false  // don't check if a queue with the same name exists
            durable: false  // the queue will not survive server restarts
            exclusive: true // the queue can not be accessed by other channels
            auto_delete: true // the queue will be deleted once the channel is closed.
        */
        $queue = env('RABBITMQ_QUEUE', 'queue1');
        $this->init($queue, 'routing_key');
    }

    public function init($queue, $routing)
    {
        $this->queue = $queue;
        $this->routingKey = $routing;
        $this->channel->queue_declare($this->queue, false, true, false, false);
        $this->channel->queue_bind($this->queue, $this->exchange, $this->routingKey);
    }

    /**
     * custom message format: code | value | extradata
     */
    public function publish($message)
    {
        if (null == $this->queue) {
            return;
        }
        $msg = new AMQPMessage($message);
        $this->channel->basic_publish($msg, $this->exchange, $this->routingKey);
    }

    public function stop()
    {
        $this->status = false;
    }

    public function consume($callback)
    {
        if (null == $this->queue) {
            return;
        }
        /*
            queue: Queue from where to get the messages
            consumer_tag: Consumer identifier
            no_local: Don't receive messages published by this consumer.
            no_ack: If set to true, automatic acknowledgement mode will be used by this consumer. See https://www.rabbitmq.com/confirms.html for details.
            exclusive: Request exclusive consumer access, meaning only this consumer can access the queue
            nowait: don't wait for a server response. In case of error the server will raise a channel
                    exception
            callback: A PHP Callback
        */
        $this->channel->basic_consume($this->queue, 'test', false, true, false, false, $callback);
        while ($this->channel->is_consuming()) {
            if (false == $this->status) {
                break;
            }
            $this->channel->wait();
        }
    }

    public function __destruct()
    {
        $this->channel->close();
        $this->connection->close();
    }

}


Create Laravel Controller

On the server Producer and Consumer create controller that can publish or consume, with the file app\Http\Controllers\RabbitMQController.php

<?php
namespace App\Http\Controllers;
use App\Services\RabbitMQService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class RabbitMQController extends Controller
{
    public function publishMessage(Request $request)
    {
        $message = $request->message;
        $result = $this->publish($message);
        return response('Message published to RabbitMQ');
    }

    public function publish($message)
    {
        $rabbitMQService = new RabbitMQService();
        $rabbitMQService->publish($message);
        return response('Message published to RabbitMQ');
    }

    public function consumeMessage()
    {
        $rabbitMQService = new RabbitMQService();
        $callback = function ($msg) {
            echo "Received message: " . $msg->body . "\n";
        };
        $rabbitMQService->consume($callback);
    }

    public function consume()
    {
        $rabbitMQService = new RabbitMQService();
        $callback = function ($msg) {
            $data = $msg->body;
            echo "Received:".$data;
        };
        $rabbitMQService->consume($callback);
    }
}

Create a tinker to test Producer

On server Producer, create the file ./tinker-producer.php
$controller = app()->make('App\Http\Controllers\API\RabbitMQController');
$results = app()->call([$controller, 'publish'], ['message'=>'1001|ACTION|VALUE'] );
print( "$results");

Run tinker

more tinker-producer.php | php artisan tinker

On RabbitMQ web console, observer creation of the queue and the message.

Create a tinker to test Consumer

On server Consumer, create the file ./tinker-consumer.php
$controller = app()->make('App\Http\Controllers\RabbitMQController');
$results = app()->call([$controller, 'consume'],[] );
print( "$results");

Run tinker

more tinker-consumer.php | php artisan tinker

On RabbitMQ web console, observer queue and message consumed.



Thursday, March 21, 2024

Cockpit Login Error on Centos

Cockpit provides a web interface to manage Centos Linux servers. E.g. https://10.1.1.123:9090/ 

However, users have found login error on Centos that mentions 

This web browser is too old to run the Web Console (missing selector(:is():where()))

Cockpit login error

This is due to updates in the web browser engine. Following is a suggestion to fix;


Step 1: Update cockpit package to current version of above version 280.

    dnf update cockpit

Step 2: Replace the javascript code.

    sed -i 's/is():where()/is(*):where(*)/' /usr/share/cockpit/static/login.js


Reference: 

https://cockpit-project.org/blog/login-issues.html


Friday, January 26, 2024

Handling date and time with carbon

In PHP and Laravel, date and time can be managed using Carbon. Default PHP uses the Date object, which does not have as many flexibility as Carbon object. To start using Carbon on Laravel, add at top, along with other "use" statements. 

use Carbon\Carbon

Here are examples of its usage. Declare current date and time

$currentDateTime = Carbon::now();

The current value can be printed with 

print_r($currentDateTime);


Format to user specific output.

$now = Carbon::now()->format('d-m-Y'); // 1-1-2024

$now->toDateString(); // 2024-01-01

$now->toFormattedDateString(); // Jan 1, 2024

$now->toTimeString(); // 00:00:00

$now->toDateTimeString(); // 2024-01-01 00:00:00

$now->toDayDateTimeString(); // Mon, Jan 1, 2024 12:00 AM

$now->toCookieString(); // Monday, 01-Jan-2024 00:00:00 UTC

$now->toIso8601String(); // 2024-01-01T00:00:00+00:00


Other ways of creating a Carbon object

Carbon::parse('2023-03-10'); // Carbon instance for 2023-01-01 00:00:00

Carbon::parse('Monday of this week'); // Monday of this week

Carbon::parse('first day of January 2024'); // first day of January 2024

Carbon::parse('first day of this month'); // first day of this month

Carbon::parse('first day of next month'); // first day of next month

Carbon::parse('first day of last month'); // first day of last month

Carbon::parse('last day of last month'); // last day of last month


Retrieve values of a carbon in various formats;

$now->year; 

$now->month; 

$now->dayOfWeek; 

$now->englishDayOfWeek; 

$now->englishMonth; 

$now->tzName; 

$now->dst;


Subtract one hour

Carbon::now()->subHour();

Subtract more than 1 hour

Carbon::now()->subHours(2);


Add one hour

Carbon::now()->addHour();

Add more than 1 hour

Carbon::now()->addHours(2);


Add one day

Carbon::now()->addDay();

Add more than 1 day

Carbon::now()->addDays(2);


This can also be applied to subWeeks(), addWeeks().


Set to a specific date by altering day or month or year

$currentDateTime = $currentDateTime->setMonth(2);

$currentDateTime = $currentDateTime->setDay(18);

$currentDateTime = $currentDateTime->setYear(2025);

Example that applies a specific day and month.

$currentDateTime = $workDayStart->setDay($calcCreatedDate->format('d'))->setMonth($calcCreatedDate->format('m'))->setYear($calcCreatedDate->format('Y'));


Retrieve the difference between 2 Carbon dates $start and $now.

$start->diff($now); \\ returns DateInterval

$start->diffInMinutes($now); \\ returns difference in minutes

$start->diffInMinutes($now); \\ returns difference in

$start->diffForHumans($now);

Friday, December 1, 2023

Manage services on Centos Linux

On Centos Linux (in this case version 8), the command systemctl allows administration of services on Linux. The version of systemctl in use is displayed with command

systemctl --version

systemd 239 (239-58.el8)

+PAM +AUDIT +SELINUX +IMA -APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD +IDN2 -IDN +PCRE2 default-hierarchy=legacy


Check status of services

systemctl status httpd

systemctl status containerd

systemctl status kubelet

systemctl list-unit-files


Background services is list with

systemctl list-jobs


View service information

systemctl show httpd

systemctl show containerd


Start and stop a service

systemctl start httpd

systemctl stop httpd


On some services, there is the command to restart or reload. Reload, reads the updated configuration for a service without stopping the service.

systemctl start httpd

systemctl reload httpd


Boot target

On linux, the run levels describe what the server should do after a startup. Where runlevel and the numeric equivalent of target. Here is a list of runlevel and in brackets are the systemctl commands for it.

Runlevel 0 - poweroff.target (systemctl isolate poweroff.target)
Runlevel 1 - rescue.target  (systemctl isolate rescue.target)
Runlevel 2 - text based multi-user.target without network  (systemctl isolate runlevel2.target)
Runlevel 3 - text based multi-user.target with network  (systemctl isolate runlevel3.target)
Runlevel 5 - graphical graphical.target  (systemctl isolate graphical.target)
Runlevel 6 - reboot.target (systemctl isolate reboot.target)

Default boot target is set by /etc/systemd/system/default.target and can be easily viewed with the command 'ls'.

Or the command systemctl get-default
multi-user.target

View available targets
systemctl list-units --type target --all

To change a default boot target,
systemctl set-default multi-user.target

Troubleshooting

List dependencies of the service

systemctl list-dependencies httpd


Unit files are list as

systemctl list-unit files


When a service is mask, it cannot be started until it is unmask. This can be done with

systemctl unmask httpd


Wednesday, October 18, 2023

Configure L5 Swagger and documention for GET and POST

Here, I will describe usage of Swagger, list the L5 Swagger basic configurations, provide templates to document POST and GET API (Application Programming Interface).

What does L5 Swagger provide?

For PHP developers, here in particular those using Laravel framework, L5 Swagger provide the means to document your API and have it presented in the form of a web page for quick browsing of available APIs and testing its results.

Currently here are good to know facts

  1. Its is developed as a wrapper on swagger-php and swagger-api specifically for Laravel framework.
  2. It supports OpenAPI (formerly known as Swagger), a specification for documentation of RESTful API irrespective of technology, like PHP, Java or .Net.
  3. L5-Swagger currently supports OpenAPI version 3.0 and 3.1. Its project page is https://github.com/DarkaOnLine/L5-Swagger
  4. It supports at least PHP version 7.2. PHP 8.1 introduces the use of attributes.
  5. An online swagger editor is available at swagger.io
My example hinges on PHP 7.4 with darkaonline/l5-swagger version 8.5.1. Will just dump example of code and configurations here. Details will be explained at another time. Good luck.

Quick notes to setup of Swagger in a ready Laravel version 7 or 10 project;

composer require "darkaonline/l5-swagger"
php artisan vendor:publish --provider "L5Swagger\L5SwaggerServiceProvider"
php artisan l5-swagger:generate

Customisation can be done by editing config/swagger.php, which can be continued in future articles.

Security

Security options are;
  • None - no security is set to access API
  • Basic Auth - Username and password is set for each request
  • API Key - A key is set for each request
  • OATH - An authorisation scheme for each request

Example 1 - API to login

Request 

Headers:
App-Key: SOmeVeryLongKey

Body form-data:
username: example@some.email.example
password: password

API returns with HTTP code 200

{
    "user_id": 4142,
    "token": "173892|HxOQJBfDgDgDgaqgCpSS1rh7UY7HWdurtanHhq7"
}

API returns with HTTP code 400

{
    "message": "These credentials do not match our records."
}

Example 2 - API to retrieve user profile

Request 

Headers:
App-Key: SOmeVeryLongKey

API returns with HTTP code 200

{
  "status": 0,
  "message": null,
  "data": [
    {
      "id": 385,
      "name": "Bintulu",
      "address1": "no.3 River side, Sarawak",
      "address2": null,
      "introduction": "Software architect and Postgresql architect",
      "phone": "1234512345",
      "email": "bintulu@some.email.example",
      "notes": "Call by phone"
    }
  ],
  "timestamp": "2023-03-17T10:00:09"
}

Swagger documentation

Swagger group for Login

Swagger group for login


Swagger for login

Added example to submit with multi/form-data (which is not necessary for login)




Swagger for user profile

Swagger user profile

Swagger user profile


The Code

Our example api.php and UserController.php

routes/api.php

Route::post('/login', 'API\UserController@login');
Route::get('/user/profile', 'API\UserController@login');

Function login in app/Http/Controllers/API/UserController.php

    /**
     * @OA\Post(
     *     path="/api/login",
     *      tags={"Login"},
     *      security={{"appkey":{}}},
     *      @OA\RequestBody( required=true, description="Login",
     *           @OA\MediaType(
     *             mediaType="multipart/form-data",
     *             @OA\Schema(
     *                 required={"username","password"},
     *                 @OA\Property(
     *                     property="username",
     *                     type="string",
     *                     description="user login id of type email"
     *                 ),
     *                 @OA\Property(
     *                     property="password",
     *                     type="password"
     *
     *                ),
     *             ),
     *          ),
     *
     *     ),
     *     @OA\Response(response="200", description="An example endpoint",
     *          @OA\JsonContent(
     *               @OA\Property(property="id", type="number", example="1957"),
     *               @OA\Property(property="token", type="string", example="173892|HxOQJBfDgDgDgaqgCpSS1rh7UY7HWdurtanHhq7"),
     *          ),
     *     ),
     *     @OA\Response(response="400", description="The id or password incorrect.",
     *           @OA\JsonContent(
     *               @OA\Property(property="message", type="string", example="These credentials do not match our records."),
     *           ),
     *     ),
     * )
     */

Function getUserProfile in app/Http/Controllers/API/UserController.php
    /**
     * @OA\Get(
     *     path="/api/user/profile",
     *     tags={"Login"},
     *     summary="Retrieve user profile",
     *     description="Retrieve user profile based on user auth detected. No parameters are required",
     *     operationId="getUserProfile",
     *     security={{"bearer_token":{}}},
     *      @OA\Parameter(
     *         name="App-Key",
     *         in="header",
     *         description="App-Key",
     *         example=L5_SWAGGER_APPKEY
     *      ),
     *
     *     @OA\Response(response=401, description="User not authenticated",
     *           @OA\JsonContent(
     *               @OA\Property(property="status", type="number", example="1"),
     *               @OA\Property(property="message", type="string", example="Not authenticated"),
     *               @OA\Property(property="data", type="string", example=null),
     *               @OA\Property(property="timestamp", type="string", example="2023-03-17T10:00:09"),
     *           ),
     *     ),
     *       @OA\Response(
     *         response=200,
     *         description="Success",
     *         @OA\JsonContent(
     *           @OA\Property(property="status", type="number"),
     *           @OA\Property(property="message", type="string", example=null),
     *           @OA\Property(property="data", type="array",
     *               @OA\Items(
     *                  @OA\Property(property="id", type="number", example=385),
     *                  @OA\Property(property="name", type="string", example="Bintulu"),
     *                  @OA\Property(property="address1", type="string", example="no.3 River side, Sarawak"),
     *                  @OA\Property(property="address2", type="string", example=null),
     *                  @OA\Property(property="introduction", type="string", example="Software architect and Postgresql architect"),
     *                  @OA\Property(property="phone", type="string", example="1234512345"),
     *                  @OA\Property(property="email", type="string", example="bintulu@some.email.example"),
     *                  @OA\Property(property="notes", type="string", example="Call by phone"),
     *              ),
     *           ),
     *           @OA\Property(property="timestamp", type="string", example="2023-03-17T10:00:09"),
     *         ),
     *       ),
     *  ),
     */


Tuesday, October 17, 2023

Laravel Helper class

Programming is made more systematic with a large number of helper classes in Laravel. Examples are the Arr::last, Arr::add, Arr::get, asset, route, secure_url, url, dd, collect, env)

Lots of documentations are available at Laravel (see Laravel 7). 

Example of usage

Helper url( )

Returns a fully qualified URL

$url = url('user/profile');

Creating your first helper class

The following illustrates a function named "courier" that will be available to all controllers. It typically returns data in a predefined format.

Step 1: Create a helper file in app/Helpers with the name myHelpers.php


/app/Helpers/myHelpers.php

Step 2: Create the function in the file myHelpers.php


<?php
use Carbon\Carbon;

if (! function_exists('courier')) {
function courier($status, $message, $data){
$now = carbon::now();
$status = $status??0;
$package = [
'status'=>$status,
'message'=>$message,
'data'=>$data,
'timestamp'=>$now,
];
return $package;
}
}

Step 3: Edit [autoload] in composer.json


"autoload": {
        "files": [
            "app/Helpers/myHelpers.php",
        ],

Step 4: Reload Laravel


composer dump-autoload

Usage of "courier" helper 

In any of the function in Controller classes, call the helper function. Example

public function getUsers( ){
$users = User::where('status','active')->get();
$status=0; // success
$message=null;
if(count($users)>0){
$status=1; // success but not users available
$message="None";
}
return response(courier($status, $message, $users), 200);
}




Thursday, October 12, 2023

Laravel 10 - User API authentication with Sanctum

Laravel 10 and User API authentication with sanctum

Laravel 10 is available to create restful API where it provides (1)process to issue API tokens to users AND (2)authentication of single page applications(SPA).

This tutorial requirements of system;

  • laravel/sanctum version 3.3.1
  • PHP version 8.2.11
  • Node version 18.12.1
  • Composer version 2.6.3
  • Npm version 8.19.2
  • PostgreSQL database version 15

Laravel application is successfully installed will all recommended PHP extensions.

Create the database and assign user hello assign to that database, which I name as demo. Use hello, or any other user you have created in the database.


create database demo;
grant all privileges on database demo to hello;
ALTER DATABASE demo OWNER TO hello;


Lets create the Laravel application and add sanctum support


composer create-project laravel/laravel demo
cd demo


Configure the .env file to access the database that was declared as demo.


DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=demo
DB_USERNAME=hello
DB_PASSWORD=

composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"


Identify and inspect the following folders and files;


config/sanctum.php
database/migrations/2019_12_14_000001_create_personal_access_tokens_table.php


Create database for Sanctum and enable Sanctum


php artisan migrate


Edit app/Http/Kernel.php


'api' => [
    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
],


Configure sanctum by editing model, service provider and auth config. Edit app/Models/User.php


use Laravel\Sanctum\HasApiTokens;
...
use HasApiTokens;


Add API to register and login


Edit routes/api.php

  

Route::controller(RegisterController::class)->group(function(){
    Route::post('register', 'register');
    Route::post('login', 'login');
});


php artisan make:controller BaseController
php artisan make:controller RegisterController


Edit RegisterController 


use App\Http\Controllers\BaseController as BaseController;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Validator;
use Illuminate\Http\JsonResponse;


public function register(Request $request): JsonResponse
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'email' => 'required|email',
            'password' => 'required',
            'c_password' => 'required|same:password',
        ]);
   
        if($validator->fails()){
            return $this->sendError('Validation Error.', $validator->errors());       
        }
   
        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);
        $success['token'] =  $user->createToken('MyApp')->plainTextToken;
        $success['name'] =  $user->name;
   
        return $this->sendResponse($success, 'User register successfully.');
    }
   
    /**
     * Login api
     *
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request): JsonResponse
    {
        if(Auth::attempt(['email' => $request->email, 'password' => $request->password])){ 
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')->plainTextToken; 
            $success['name'] =  $user->name;
   
            return $this->sendResponse($success, 'User login successfully.');
        } 
        else{ 
            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
        } 
    }


Retrieve the registration api 


{
    "success": true,
    "data": {
        "token": "1|R8qfygjItwjleo23QwdqqS5ZcVLZwaRH72iJjiEqd4d85583",
        "name": "admin@example.com"
    },
    "message": "User register successfully."
}


Retrieve login api


{
    "success": true,
    "data": {
        "token": "2|IyNnxOU0N1cc0s2bADqzASxzwc8kl7z5UbqZ2oARd68aa58b",
        "name": "admin@example.com"
    },
    "message": "User login successfully."
}


Ref: https://www.itsolutionstuff.com/post/laravel-10-rest-api-authentication-using-sanctum-tutorialexample.html#google_vignette

https://laravel.com/docs/10.x/sanctum#token-ability-middleware


Next, add a appkey token.

https://laravel.com/docs/10.x/middleware

Monday, October 2, 2023

MySQL group by unix timestamp

Drupal CMS includes a webform where each form has an ID. An example to retrieve number of user access of a Drupal database for a given node id. The column ws.created is stored with a unix timestamp (looks like many digits number). Use MySQL function from_unixtime to format into something like 2023-10-02. The node in this example have an ID=940.

select count(ufd.name) submissions, DATE_FORMAT(from_unixtime(ws.created), "%Y-%m-%d")
from webform_submission ws 
left join users_field_data ufd 
on ws.uid = ufd.uid
left join node_field_data nfd 
on ws.entity_id = nfd.nid
where ws.in_draft = 0
and ws.entity_type like 'node'
and ws.entity_id = 940
group by DATE_FORMAT(from_unixtime(ws.created), "%Y-%m-%d")

Here is a query to list all the associated users who accessed the webform

select ufd.name name, ufd.mail email, from_unixtime(ws.created) accepted_at, from_unixtime(ws.changed) changed_at, ws.remote_addr 
,nfd.title, ws.uri URL
from webform_submission ws 
left join users_field_data ufd 
on ws.uid = ufd.uid
left join node_field_data nfd 
on ws.entity_id = nfd.nid 
where ws.in_draft = 0
and ws.entity_type like 'node'
and ws.entity_id = 940

Tuesday, September 19, 2023

R language basics

The R programming language can be downloaded then installed from https://cran.r-project.org/index.html

Next download and install R Studio from https://posit.co/download/rstudio-desktop/

Install the R tutorial by opening R Studio, in a console install the package swirl and start the tutorial.

install.packages("swirl")

library(swirl)

swirl()

Following are the initial list of commands learnt from Swirl in lesson 1 to 4

skip(), play(), nxt(), bye(), main(), info()

c(), sqrt(), info()

help commands ?c , ?`:`

getwd(), ls(), list.files(), dir(), args(), getwd(), dir.create(), setwd(), file.create(mytest.R), file.exists(), file.info(), file.rename(from, to), file.path(),setwd(),unlink("testdir",recursive=TRUE)

seq(), seq(1,10, by=0.5), length(), rep(0, times=40),rep(c(0,1,2), times=10)

rep(c(0,1,2), each=10)


Happy R gramming!

Thursday, September 14, 2023

Centos 7 monitoring with cockpit

Monitor Centos Linux 7 servers through a web browser. On Centos Stream 8, Cockpit is installed by default on the most parts.

Steps to install cockpit and start the service

These require Linux Administrative user access at the command line.

sudo yum install cockpit cockpit-storaged

sudo systemctl enable --now cockpit.socket

sudo firewall-cmd --permanent --zone=public --add-service=cockpit

sudo firewall-cmd --reload

OR with iptables

sudo iptables -A INPUT -i eth0 -s 0/0 -p tcp --dport 9090 -j ACCEPT

sudo systemctl start cockpit

Access Cockpit

On web browser access URL http://<serverip>:9090

Cockpit layout




Wednesday, September 13, 2023

How to add remote MySQL user access.

Users created in MySQL should be for localhost access. In order for a user to be connected from a remote computer, the IP address must be mentioned in its user record. Removing a user access is a matter of deleting that user from the user record.

How to add remote user access

Example, user with login "developer" wants to access MySQL database at server 10.1.1.100 from a laptop at the IP address 10.1.2.23.

The network and database administrator received approval to allow any user to access remotely from the IP address 10.1.2.1 to 10.1.2.224 to the existing database name "tutorial". Here is how its done.

Step 1: Login as server administrator and ensure MySQL can accept connections from remote servers.

MySQL community , edit the file /etc/my.cnf

MariaDB community , edit the file /etc/my.cnf.d/server.cnf

Add the following line, save.

bind-address=0.0.0.0

Restart the MySQL server.

Ensure the server firewall allows access to MySQL port, where default is port 3306.

Example for Centos;

sudo firewall-cmd --new-zone=public --permanent

sudo firewall-cmd --reload

sudo firewall-cmd --permanent --zone=public --add-source=133.155.44.103

sudo firewall-cmd --permanent --zone=public --add-port=3306/tcp

sudo firewall-cmd --reload

sudo firewall-cmd --list-all-zones

sudo firewall-cmd --get-services


Step 2: Login to MySQL database as administrator. Add login for remote user and list users.

mysql -u root -p

> CREATE USER 'developer'@'10.2.%' IDENTIFIED BY 'password';

> SELECT user,host FROM mysql.user;


Step 3: Assign login to access database

> GRANT ALL PRIVILEGES ON 'tutorial'.* to 'developer'@'10.2.%';

> FLUSH PRIVILEGES;

> SHOW GRANTS FOR 'developer'@'10.2.%';


Step 4: Monitor connection;

> SELECT user,host, command FROM information_schema.processlist;


How to connect remotely

On the remote server, run the following client command 

mysql -u developer -p -h 10.1.1.100

The MySQL client, it should have the same configuration for SSL as the server to avoid SSL issues.


How to remove remote user access

Login as database administrator and delete login of user and its host as recorded in database;

> DELETE FROM mysql.user WHERE User='developer' AND Host NOT IN ('localhost', '127.0.0.1', '::1');

> FLUSH PRIVILEGES;

Monday, September 11, 2023

How to add datasource to reportserver.net?

Extracting from MySQL and PostgreSql database can be done via Reportserver.net. Other relational databases are also supported as of Reportserver.net version 4.

Configuration

Step 1: Login as administrator user

Step 2: In the menu choose "Datasources", then right click "Datasource Root" and right click to choose "Insert" ->"Relational Database".

Step 3: Enter the following and click "Apply"

  • Name
  • Description
  • Database
  • Username
  • Password
  • URL
The Permission tab provides better control for user to access.

Postgresql database URL

jdbc:postgresql://10.1.1.102/customers

MySQL database without SSL URL

jdbc:mysql://10.1.1.100:3306/customers?useSSL=false

MySQL database URL

jdbc:mysql://10.1.1.100:3306/customers


Details for other databases can be found at https://reportserver.net/en/guides/admin/chapters/Datasources/

Troubleshooting

Host 'host_name' is blocked in MySQL

Too many attempts made to the database can be caused by having or not having ssl. 
Solution:
Try to disable SSL protocol for the client.

Missing Relational Database Driver

Reportserver.net comes with several drivers. To customise datasource, 
Login as administrator and click "File System".
Click "Fileserver Root"->"etc"->"datasources"->"datasources".
Click on tab "Edit file".

It defaults to the following:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
   <datasource>
      <defaultDatasourceName>Demo Data</defaultDatasourceName>
      <!-- or access via ID -->
      <!-- <defaultDatasource>14</defaultDatasource> -->
   </datasource>
</configuration>


Friday, September 8, 2023

How to read excel data with PhpSpreadsheet

PhpSpreadsheet provides a PHP library of classes to read and write formats such as LibreOffice Calc, Microsoft Office and CSV. The default encoding uses UTF-8.

Ref: https://phpspreadsheet.readthedocs.io/en/latest/faq/

In Laravel 5, 6 and 7, this is available through the Composer. 

composer require phpoffice/phpspreadsheet niklasravnsborg/laravel-pdf mpdf/mpdf:8.1.6 league/csv

OR

composer require phpoffice/phpspreadsheet niklasravnsborg/laravel-pdf mpdf/mpdf league/csv

Here is an example of how to read the first three columns of an xlsx file, where the first row is considered as headers.

Step 1: Import the class for LibreOffice

use PhpOffice\PhpSpreadsheet\Reader\Ods;

Or for Microsoft Excel

use PhpOffice\PhpSpreadsheet\Reader\Xlsx;

Step 2: In the function that is to retrieve the data, declare object for LibreOffice

$reader = new Ods();

OR for Microsoft Excel

$reader = new Xlsx();

Step 3: Load the spreadsheet data 

$spreadsheet = $reader->load($path);
$sheet = $spreadsheet->getActiveSheet();

OR, load a sheet with specified name
$spreadsheet = $reader->setLoadSheetsOnly(["Sheet1"])->load($path);
$sheet = $spreadsheet->getActiveSheet();

Step 4: Process rows, and skip header in first row

$users = new Users();
if(!empty($sheet)) {
    foreach ($sheet->getRowIterator() as $row) {
      if ($row->getRowIndex() === 1) {
         continue; //Skip heading
      }
      $cells = iterator_to_array($row->getCellIterator("A", "H"));
      $data = [
            "Column A" => $cells["A"]->getValue(),
            "Column B" => $cells["B"]->getValue(),
            "Column C" => $cells["C"]->getValue(),
      ];
      $users->add($data);
}


The example can be said to retrieve the first 3 columns of the spreadsheet row as fields to create a new user.

Thursday, September 7, 2023

Display GIT branch in linux

It is useful to have the current Git branch appear at user prompt. This can be done for Centos Linux BASH by updating the user's configuration file .bashrc in the user's home directory.

Add these lines

git_branch() {

    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/(\1)/'

}

export PS1="\u@\h \[\e[32m\]\w \[\e[91m\]\$(git_branch)\[\e[00m\]$ "


This will produce a user prompt like this

login@hostname current_directory(git.branch.name)$


Wednesday, September 6, 2023

How to add remote to GIT repo

Git remote provide information to sync with a Git repository to do stuff like git fetch, git push, git pull.

This information is stored in .git/config. In the case of a new directory, that does not have git, start by configuring it with the command git init. Managing remote can be done by the following commands.

Adding a remote

git remote add <name> <url>


Example

git remote add git_user1 user1@git.myserver.local/repo/package.git

git remote add ssh_user1 ssh://user1@10.1.1.100/repo/package.git


View the current remote and detailed remote information

git remote

git remote -v


Remove a remote

git remote remove <name>

git remote rm <name>


Example

git remote rm remote_user1


Push changes of the specific remote

git push <name>


Example

git push ssh_user1

or to push as a new branch

git push -u ssh_user1 new_branch


Show log of the remote

git remote show <name>


Example

git remote show ssh_user1


Show status of CURRENT branch

git status


Change url of an existing remote

git remote set-url <name> <new url>


Example

git remote set-url remote_user1 ssh://user1@10.1.1.23/repo/package.git


Thursday, August 3, 2023

Basic of SQL joins

SQL join statements are used to combine rows from two or more tables, based on related column(s) between those tables.  These statements assist user to extract data from tables which have one-to-many or many-to-many relationships between them.

Here is a basic list of join command examples as used in PostgreSQL database.

SQL join command examples


Tuesday, March 28, 2023

GIT tag and retag

Working with GIT allows tagging specific points along the repository that have some importance. Commonly, tag is used when a version is released. Here are examples of listing tags, adding and deleting a tag.

List tags

List tag on local

git tag -l "v1.*"

git tag

List tag on repository

git ls-remote --tags

Display details of a tag

git show v1.0.2


Add tag to current branch

git tag -a v1.0.2 HEAD -m "Update for version 1.0.2"

git push origin --tags

Tag can be added to a specific commit.

git tag -a v1.0.2 f8c3501-m "Update for version 1.0.2" 


Retagging

This requires deleting current tag, then publish changes to remote repository.

git tag -d v1.0.2

git push origin :refs/tags/v1.0.2


Tuesday, March 21, 2023

How to create a dynamic object from standard class

 PHP provides a class to create a temporary object where no specific class and members are required.


The class stdClass is the empty class in PHP used to cast other types to object. Among the example of stdClass usage;

  1. Directly access the members by calling them
  2. Dynamic objects can be provided for temporary usage
E.g. 
An array can be treated as an object by using stdClass. 

$tmpStudent = array(
"name" => "John Doe"
);

To access data, 
$tmpStudent['name']

$tmpStudent = new stdClass;
$tmpStudent->name = "John Doe";

Using the stdClass, this can be done as an object
$tmpStudent->name


Thursday, February 16, 2023

Reportserver query with wildcards

The community edition of Reportserver.net provide a large number of useful functions. This include managing user access, download in different formats, user freedom to customise the report and access from different databases.

Here is an example of string query with wildcard and parameters. The $P{email} is a parameter where you can enter a value.


SELECT user_id, email, registration_id, date, venue, type, status

FROM student_registration

WHERE email LIKE '%'||$P{email}||'%'

Another example to apply parameter ${timezone} which is the default handling of variable, in this case to add with date from created_at

SELECT user_id, email, registration_id, created_at::timestamp + ${timezone}::interval as created_at

FROM student_registration

Blog Archive