General

Generating Subresource Integrity (SRI)

Posted on

Since launching my online recruitment platform and job vacancy portal. I became interested in rolling out my own content delivery network (CDN) to host my portal’s images, javascript and CSS. Thanks to NGINX, implementing a CDN is easy. Of course we need to ensure that our digital assets are not compromised during transport so we need to add Subresource Integrity (SRI) to our files.

openssl dgst -sha384 -binary site.css | openssl base64 -A

Using openssl is fine but I want to try writing a golang base program to generate the SRI hash for me. You can find the snippet below and code at my github https://github.com/mrprintedwall/srigen

package main

import (
	"crypto/sha512"
	b64 "encoding/base64"
	"fmt"
	"io/ioutil"
	"os"
)

func main() {
	args := os.Args[1:] // Fetch the program arguments excluding the program name
	if len(args) == 0 {
		fmt.Println("Usage: srigen \"filename\"")
	} else {
		b, err := ioutil.ReadFile(args[0])
		if err != nil {
			panic(err)
		}
		hash := sha512.New384()

		hash.Write(b)
		hashResult := hash.Sum(nil)

		result := b64.StdEncoding.EncodeToString(hashResult)
		fmt.Printf("sha384-%s\n", result)
	}
}
Subresource Integrity used in CDN
Subresource Integrity used in CDN
MySQL

Using MySQL TIMESTAMPDIFF to delete unverified user records

Posted on

Building a public website with user registration and email verification is typical. It will require users to validate their email by clicking a unique generated URL link.
Sometimes, user registration with pending verification will grow exponentially and needs an automated cleanup of records.

In this example I created a simple MySQL stored procedure to delete users with “pending-email-verification” status for more than five days.

TIMESTAMPDIFF(unit, datetime1, datetime2)

CREATE DEFINER=`dbuser`@`localhost` PROCEDURE `delete_unverified_users`()
BEGIN
	DELETE FROM user WHERE user.status='pending-email-verification' AND TIMESTAMPDIFF(DAY,user.modifiedDateTime,NOW()) > 5;
	SELECT ROW_COUNT() AS 'count';
END
Tutorials

How to stop Mailtrack from tracking you

Posted on

Mailtrack is an online service that provides email tracking capability and analytics. Using its services the sender can track when the receiver read the email, when it was viewed and where is the reader’s location. It is a great tool for marketing but I feel that this is invading privacy and I would like to share to you how to stop getting tracked by mailtrack or other similar services. Internet surveillance and tracking are now more prevalent than ever which is why we have to ensure that our privacy is upheld.

How mail tracking service like Mailtrack works?

Mailtrack uses a transparent, 1×1 pixel size external reference image inserted into the email. When the unsuspecting person opens the email, the image will be loaded from and external server which then can identify that the email has been opened and read.

Steps on how to stop Mailtrack from tracking you

Procedures for

Gmail

1. Go to Gmail settings
1. Go to Gmail settings

2. From the menu, select Settings
2. From the menu, select Settings

3. Inside Gmail settings, Go to Images section and select Ask before displaying external images
3. Ask before loading external images

Linux

How to connect to a Cisco VPN in Ubuntu 18.04 LTS

Posted on

Here’s the simple steps for you to connect to a Cisco VPN in Ubuntu 18.04 LTS.

Cisco, an American company is the leading provider and manufacturer of enterprise network devices, telecommunication hardware, networking security and networking software.
According to computer profile as of April 2018, Cisco holds a 73.9% market which makes it the undisputed leader in its industry. Without further ado here
are the steps.

1. Install vpnc and network-manager-vpnc-gnome


sudo apt install vpnc network-manager-vpnc-gnome


2. Enter your password



3. Confirm installation



4. After successfully installing the required software it is time to configure it.



5. Add a new VPN connection



6. From the VPN type options, select Cisco Compatible VPN (vpnc)



7. Enter your VPN credentials and press Add



Linux

Bash string manipulation in program arguments

Posted on

In this code snippet, I would like to run an application with a URL payload based on date and time. This
code will be executed in a specific schedule everyday and I would like to dynamically inject the date and time in
the program argument when the program executes.


./json2csv rules.json "ncp" "http://localhost:8080/api/zget?eid=get-ncp-mv-by-starttime-endtime&starttime=$(date --date='yesterday' +\%Y-\%m-\%d)+00:00:00&endtime=$(date --date='yesterday' +\%Y-\%m-\%d)+23:59:00&container=false" > $(echo "nercc_mv_$(date --date='yesterday' +\%Y-\%m-\%d).csv")

The way to do this is using the Bash String Manipulation

Inside a string, the bash will evaluate statement inside “$()” in this example:

$(date --date='yesterday' +\%Y-\%m-\%d)


"http://localhost:8080/api/zget?eid=get-ncp-mv-by-starttime-endtime&starttime=$(date --date='yesterday' +\%Y-\%m-\%d)+00:00:00&endtime=$(date --date='yesterday' +\%Y-\%m-\%d)+23:59:00&container=false"

The resulting string after bash string manipulation will be like this

http://localhost:8080/api/zget?eid=get-ncp-mv-by-starttime-endtime&starttime=2018-09-27+00:00:00&endtime=2018-09-27+23:59:00&container=false
Code Snippet

Standardizing SQLite in Spring framework Project

Posted on

My approach in standardizing SQLite in a Spring framework project

In a software development world were rapid project delivery is needed. The only way for us, developer having a sense of sanity is to build standardize code for future development. In doing so, it shortens the development time but having tested and functioning code base.

ISqliteObjectAssembler.java

This interface will serve as my IOC to have my own implementation of parsing from resultset to my specific Object

/**
 * Created by mrprintedwall on 11/02/17.
 */

public interface ISqliteObjectAssembler
{
	T assemble(ResultSet resultSet) throws SQLException;
}
ISqliteRepository.java
/**
 * Created by mrprintedwall on 11/02/17.
 */

public interface ISqliteRepository
{
	//region CONNECTION

	Connection getConnection() throws SQLException;

	//endregion

	//region ROW METHODS

	/**
	 * INSERT INTO SQLITE AND RETURNS THE GENERATED PRIMARY ID
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws SQLException
	 */
	int insert(String sql, Map parameters) throws SQLException;

	/**
	 * UPDATE ROWS IN SQLITE AND RETURN AFFECTED NUMBER OF ROWS
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws SQLException
	 */
	int update(String sql, Map parameters) throws SQLException;

	/**
	 * DELETE ROWS IN SQLITE AND RETURN DELETED NUMBER OF ROWS
	 * @param sql
	 * @param parameters
	 * @return
	 * @throws SQLException
	 */
	int delete(String sql, Map parameters) throws SQLException;

	/**
	 * GET SINGLE ITEM FROM RESULTSET USES INJECTED OBJECT MAPPER FOR RESULTBINDING
	 * @param sql
	 * @param sqliteObjectAssembler
	 * @param 
	 * @return
	 * @throws SQLException
	 */
	 T getSingle(String sql, ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException;

	/**
	 * GET LIST OF ITEMS FROM RESULTSET USES INJECTED OBJECT MAPPER FOR RESULTBINDING
	 * @param sql
	 * @param sqliteObjectAssembler
	 * @param 
	 * @return
	 * @throws SQLException
	 */
	 List getList(String sql, ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException;
	
	/**
	 * GET SINGLE ITEM USING MAP OF PARAMETERS FROM RESULTSET USES INJECTED OBJECT MAPPER FOR RESULTBINDING
	 * @param sql
	 * @param parameters
	 * @param sqliteObjectAssembler
	 * @return
	 * @throws SQLException
	 */
	 T getSingle(String sql, Map parameters, ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException;

	/**
	 * GET LIST OF ITEMS USING MAP OF PARAMETERS FROM RESULTSET USES INJECTED OBJECT MAPPER FOR RESULTBINDING
	 * @param sql
	 * @param parameters
	 * @param sqliteObjectAssembler
	 * @return
	 * @throws SQLException
	 */
	 List getList(String sql, Map parameters, ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException;
	//endregion

	//region TABLE METHODS

	void createTable(String sql) throws SQLException;
	void alterTable(String sql) throws SQLException;
	void dropTable(String sql) throws SQLException;

	//endregion

}
SqliteDbRepository.java
/**
 * Created by mrprintedwall on 11/02/17.
 */

@Service
public class SqliteDbRepository implements ISqliteRepository
{
	private static final Logger logger = LoggerFactory.getLogger(SqliteDbRepository.class);

	private AppConfig appConfig;

	@Autowired
	public SqliteDbRepository(AppConfig appConfig)
	{
		this.appConfig = appConfig;
	}

	@Override
	public Connection getConnection() throws SQLException
	{
		try
		{
			Class.forName("org.sqlite.JDBC");
			Connection connection = DriverManager.getConnection(appConfig.getSqliteConnectionString());
			PreparedStatement preparedStatement = connection.prepareStatement("PRAGMA foreign_keys=ON");
			preparedStatement.execute();
			return connection;
		}
		catch (ClassNotFoundException classNotFoundException)
		{
			logger.error(classNotFoundException.getMessage());
		}
		return null;
	}

	@Override
	public int insert(String sql, Map parameters) throws SQLException
	{
		try(Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sanitizeSqlString(sql));
			if (parameters != null)
			{
				injectParameterToPreparedStatement(parameters, preparedStatement);
			}
			preparedStatement.executeUpdate();
			return getLastInsertedId(connection);
		}
	}

	@Override
	public int update(String sql, Map parameters) throws SQLException
	{
		try (Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sanitizeSqlString(sql));
			if (parameters != null)
			{
				injectParameterToPreparedStatement(parameters, preparedStatement);
			}
			return preparedStatement.executeUpdate();
		}
	}

	@Override
	public int delete(String sql, Map parameters) throws SQLException
	{
		try (Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sanitizeSqlString(sql));
			if (parameters != null)
			{
				injectParameterToPreparedStatement(parameters, preparedStatement);
			}
			return preparedStatement.executeUpdate();
		}
	}

	@Override
	public T getSingle(String sql, ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException
	{
		try (Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sql);
			ResultSet resultSet = preparedStatement.executeQuery();
			if (resultSet != null)
			{
				return (T) sqliteObjectAssembler.assemble(resultSet);
			}
		}
		return null;
	}

	@Override
	public List getList(String sql, ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException
	{
		try (Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sql);
			ResultSet resultSet = preparedStatement.executeQuery();
			if (resultSet != null)
			{
				List results = new ArrayList<>();
				while (resultSet.next())
				{
					try
					{
						results.add((T) sqliteObjectAssembler.assemble(resultSet));
					}
					catch (Exception exception)
					{
						logger.error(exception.getMessage());
					}
				}
				return results;
			}
		}
		return new ArrayList<>();
	}

	@Override
	public  T getSingle(String sql, Map parameters, ISqliteObjectAssembler sqliteObjectAssembler)
			throws SQLException
	{
		try (Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sanitizeSqlString(sql));
			if (parameters != null)
			{
				injectParameterToPreparedStatement(parameters, preparedStatement);
			}
			ResultSet resultSet = preparedStatement.executeQuery();
			if (resultSet != null)
			{
				return (T) sqliteObjectAssembler.assemble(resultSet);
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	@Override
	public  List getList(String sql, Map parameters,
	                           ISqliteObjectAssembler sqliteObjectAssembler) throws SQLException
	{
		try (Connection connection = getConnection())
		{
			PreparedStatement preparedStatement = connection.prepareStatement(sanitizeSqlString(sql));
			if (parameters != null)
			{
				injectParameterToPreparedStatement(parameters, preparedStatement);
			}
			ResultSet resultSet = preparedStatement.executeQuery();
			if (resultSet != null)
			{
				List results = new ArrayList<>();
				while (resultSet.next())
				{
					try
					{
						results.add((T) sqliteObjectAssembler.assemble(resultSet));
					}
					catch (Exception exception)
					{
						logger.error(exception.getMessage());
					}
				}
				return results;
			}
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
	
	@Override
	public void createTable(String sql) throws SQLException
	{
		tableSqlExecutor(sql);
	}

	/*

	ALTER TABLE EXAMPLE:

	ALTER TABLE table RENAME TO temp_table;

	 */

	@Override
	public void alterTable(String sql) throws SQLException
	{
		tableSqlExecutor(sql);
	}

	@Override
	public void dropTable(String sql) throws SQLException
	{
		tableSqlExecutor(sql);
	}

	/**
	 * GENERIC TABLE CREATE/ALTER/DROP SQL EXECUTOR/HANDLER
	 *
	 * @param sql
	 * @throws SQLException
	 */
	private void tableSqlExecutor(String sql) throws SQLException
	{
		try (Connection connection = getConnection())
		{
			Statement statement = connection.createStatement();
			statement.execute(sql);
		}
	}

	/**
	 * THIS INJECTS THE HASH MAP INTO THE PREPARED STATEMENT
	 *
	 * @param parameters
	 * @param preparedStatement
	 * @throws SQLException
	 */
	private void injectParameterToPreparedStatement(Map parameters, PreparedStatement preparedStatement) throws SQLException
	{
		if (parameters != null && preparedStatement != null)
		{
			for (Map.Entry entry : parameters.entrySet())
			{
				preparedStatement.setObject((int) entry.getKey(), entry.getValue());
			}
		}
	}

	/**
	 * A LITTLE BIT OF RAINBOW, AND SUGAR STRING SANITATION
	 *
	 * @param sql
	 * @return
	 */
	private String sanitizeSqlString(String sql)
	{
		if (sql != null)
		{
			return sql.trim();
		}
		return "";
	}

	/**
	 * THIS WILL RETRIEVE THE LAST GENERATED ID IN SQLITE
	 *
	 * @param connection
	 * @return
	 * @throws SQLException
	 */
	private int getLastInsertedId(Connection connection) throws SQLException
	{
		if (connection != null)
		{
			Statement statement = connection.createStatement();
			ResultSet resultSet = statement.executeQuery("SELECT last_insert_rowid()");
			if (resultSet != null)
			{
				return resultSet.getInt(1);
			}
		}
		return 0;
	}

}
Code Snippet

Golang mgo sort number inside a string

Posted on
// Get List
func (z *DocumentTagService) GetDocumentTags() ([]models.DocumentTag, error) {
	z.DatabaseService.Connect()
	var o []models.DocumentTag
	err := (*z.DatabaseService.Db).C(z.Collection).Find(bson.M{}).Sort("-$natural", "-documentReference").All(&o)
	return o, err
}

Result

[
    {
        "idDocumentTag": "5b1390f29ebea41854dcc0dc",
        "documenReference": "MCTU/2018/16",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390f09ebea41854dcc0db",
        "documenReference": "MCTU/2018/15",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390d19ebea41854dcc0da",
        "documenReference": "MCTU/2018/14",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390d09ebea41854dcc0d9",
        "documenReference": "MCTU/2018/13",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390cf9ebea41854dcc0d8",
        "documenReference": "MCTU/2018/12",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390cd9ebea41854dcc0d7",
        "documenReference": "MCTU/2018/11",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390b29ebea41854dcc0d6",
        "documenReference": "MCTU/2018/10",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390b19ebea41854dcc0d5",
        "documenReference": "MCTU/2018/9",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390b09ebea41854dcc0d4",
        "documenReference": "MCTU/2018/8",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b1390ae9ebea41854dcc0d3",
        "documenReference": "MCTU/2018/7",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b13900c9ebea41854dcc0d2",
        "documenReference": "MCTU/2018/6",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b13900c9ebea41854dcc0d1",
        "documenReference": "MCTU/2018/5",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b13900b9ebea41854dcc0d0",
        "documenReference": "MCTU/2018/4",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b13900a9ebea41854dcc0cf",
        "documenReference": "MCTU/2018/3",
        "company": "MCTU"
    },
    {
        "idDocumentTag": "5b138b449ebea41854dcc0ce",
        "documenReference": "MCTU/2018/2",
        "company": "MCTU"
    }
]

General

Replacing My Macbook Pro 2013 trackpad

Posted on

Background

I would like to share my experience in replacing my broken MacBook Pro late 2013 trackpad. One day, when I started using my MacBook pro I realize that the trackpad doesn’t work and my keyboard acting strange when I am moving my fingers across the trackpad. I tried doing the PRAM and SMC reset but to no avail. Then I when online and did my research. My research concluded in 3 possible scenarios. My keyboard still works fine so the keyboard is out of the equation.

1. Trackpad cable might be damaged
2. Trackpad got damaged
3. Mainboard issue (MAJOR)

I initially purchased the trackpad cable and installed it. Installing it is pretty easy but that didn’t resolve the problem. I then proceed with replacing the trackpad and my MacBook is now back in working condition. Replacing a trackpad requires some effort especially in removing the adhesive that binds the battery into the laptop casing.

Laptop parts from

http://www.laptopspecialist.com.my