asd

There might be a time where you might bee locked out of your admin account because you either forgot the password and and reseting the is not an option because you no longer have access to that email. Or the website has been hacked and you have to create an admin account.

The only option is to create a user via the MySQL. But remembering the long sql query is difficult.

An exaple query would be like the following example:

Create User account

INSERT INTO `wp_users` (`user_login`, `user_pass`, `user_nicename`, `user_email`, `user_status`,`user_registered`)
VALUES ('admin', MD5('changeme'), 'Mr Admin', 'admin@example.com', '0','2019-12-27');

Add user permissions

   
INSERT INTO `wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) 
VALUES (NULL, (Select max(id) FROM wp_users), 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
INSERT INTO `wp_usermeta` (`umeta_id`, `user_id`, `meta_key`, `meta_value`) 
VALUES (NULL, (Select max(id) FROM wp_users), 'wp_user_level', '10');

That is the reason I created WPAdmin (I know it is an original name) a tool to help that will generate the SQL query for you.

 Just created a plugin for Gridsome, a source plugin to retrieve posts from using dev.to API.
You are able to find the plugin on the NPM registry here

What is Gridsome?

Ok, hold on a second! What is Gridsome?

Glad you asked!

Gridsome is a static site generator similar to Gatsby (though still new so not as feature-rich) for the Vue framework. Gridsome makes it easy for developers to build modern JAMstack websites & PWAs that are fast by default.

Why Gridsome?

If you are going to use gridsome you have following by default:

For more in-depth information about Gridsome please read the docs.

How to use this plugin?

Installation

To install this plugin you just need to add it as a dependency on your gridsome project. You can do it by running the following command on your terminal using yarn.

yarn add @perlatsp/gridsome-source-devto

or if you prefer npm

npm install @perlatsp/gridsome-source-devto

When the installation finishes you should be ready for the next step, which is configuring the plugin.

Configuration

Before we continue configuring the plugin, what we need to do first is getting an API key from https://dev.to. To do so, we need to go to dev.to website, go to account->settings and then you should see an input box, add a description for the token and smash that Generate Token button. After doing so, this might take a while for the token to be generated for you (circa 200ms depending on your internet connection 🤪).

dev.to settins

Configurration file

When you get your token we can proceed to the next step. Adding the configuration to the gridsome.config.js file. This file is where most of the gridsome configurations live. Open the configuration file and add the following to the plugins array. Like the following

...other gridsome plugins
   {
      use: '@perlatsp/gridsome-source-devto',
      options: {
        typeName: 'Article',
        username:'DEVTO_USERNAME',
        apiKey: process.env.DEVTO_API_KEY,
        route: '/:slug',
      }
    }
... rest of config file

What we did here is to tell gridsome to use our plugin use: '@perlatsp/gridsome-source-devto' with an options object. The options object is pretty straight forward, we are assigning a typeName: 'Article', this is the name of our ‘post model’ we will use this later to query the posts.

We have username:'DEVTO_USERNAME' which is the author’s username we want to retrieve from the API.

ENV File

API key variable, apiKey: process.env.DEVTO_API_KEY which is getting the value from the .env file for security reasons so don’t have this in our codebase. We need to create a .env file in our project root directory and add the following DEVTO_API_KEY=THE_API_KEY_FROM_DEVTO_SITE. And the last configuration we need to do is the route. this will be the single post’s URL display type. More about gridsome routing here.

Now we are ready to roll to the next step displaying the posts.

Display Posts

To display the posts we need to head over to the Index.vue file and modify the component (if the component does not exist, create one) to reflect the following:

<page-query>
query Home {
    allArticle {
      edges {
        node {
          id
          title
          published_at
          path
          description
          tag_list
          canonical_url
          cover_image
        }
      }
    }
  }
</page-query>

This is a GraphQL query.

GraphQL is a declarative query language especially useful for retrieving only the data you ask for. Which again will result in smaller bundles.

We are registering entities named allArticle (all + the typeName we registered in our config file).

There is no need to get all the data from our articles, so we are requesting some of the nodes (fields) like id, title, description, etc.

Ok, we have our loop query. now what? Is that it?

Of course not! Now we need somehow to display the date we have. to do so, scroll up to the ` component. and modify it to reflect the following :

html
<template>
<Layout>
<h1> Gridsome source plugin for
<img src="https://d2fltix0v2e0sb.cloudfront.net/dev-badge.svg" height="30"
width="30"></h1>
<div v-for="{ node } in $page.allArticle.edges" :key="node.id">
<h2> {{node.title}}</h2>
{{node.description}}
<div>
<g-link :to="node.path" class="single-post-link">Read More</g-link>
</div>
</div>
</Layout>
</template>

And voila we can now see our posts! Open your terminal and run yarn developto compile and create a dev server. your project should be available on http://localhost:8080.

If you followed the previous steps you should have something similar to the following picture. Navigation on top, a heading and the loop with the posts displaying the title, description and the link to the post.

postsindex

Personally, I don’t like how it is visually. Let us add some styles.

postscards

A bit better 😄 with simple cards. We have now finished the project and we can run yarn build to generate all the static files and ready to deploy! ⛴

This plugin is still in development and more work needs to be done. Such us displaying more data for the single article page. PRs more than welcome on github

The aim of this article is to learn what is npm what do we need to run/install npm packages and we will learn how we can create and publish a package to the npm registry and feel like a cool and badass developer 😎.

Table of Contents

  1. What is NPM
  2. Requirements
  3. Our NPM Package

What is NPM

What is npm again ? Well, NPM stands for Node Package Manager and as the authors define it on their website :

Our Package

For the scope of this article, we will get step by step of the process of creating an npm package and publish it on the npm registry so other developers around the world can use our package.

The package we are going to create is a simple CLI app that will accept an email as an argument and will check if that email has been found in public data breaches. To achieve this we will be making HTTP requests to an external API, the haveibeenpawned.com website’s API. The name of our package? pawnhub 🙄 😉

Requirements

To build our package we need the following

Getting Started

Install NodeJS

To install NodeJS on our system we can do it in many ways, i will demonstrate 2 of them.

Install from official website

Visit the official NodeJs website https://nodejs.org, press the download button

nodejs

When the download is finished, open the file and follow the instructions to complete the installation. Doing so will install node and npm.

Install using homebrew

Homebrew is a package manager for MacOS or Linux.

First, we need to install Homebrew (if not already installed).

Open the terminal and run the following command:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

This will download and install Homebrew for us.

Then run brew update to make sure Homebrew is up to date.

To install Node we just simply run the below command:

brew install node

To confirm we have installed Node and NPM on our system, we can run the following commands:

node -v and npm -v it will display the version we have just installed .

nodeinstalled

Creating the Package

First, we need to create a directory for our project. I like to have all my projects in the ~/projects directory 🗂. Open the terminal and run mkdir pawnhub this will create a folder named pawnhub, then enter the directory cd pawnhub.

NPM Init

Now that we are inside our project directory, we need to initialize an npm project. We can do that by running npm init. This will start the interactive clip and ask us some information about our new package, such as the name, version, description, author, and license.

npminit

When we fill all the info we will be asked to confirm the information we have just entered.

npmconfirm

Next, we need to open the project in our code editor. With Visual Studio Code we can run the command code . which will open the current directory or we can open the Visual Studio Code and press COMMAND+O and open the dir.

You will find that we have only 1 file the package.json. More about the package.json file here!

opendir

Main File

Our next step is to create the main file we are going to use, the index.js file.

create the file in our root dir touch index.js. Open the file and copy-paste the following :

let message = 'Hello World!';console.log(message)

Running the file is pretty straightforward. Open the terminal and run node index.js this will tell Node to run the index.js file. We should see the following on our terminal.

nodeindexjs

Cool huh? But, it is not dynamic. we cannot change the outputted message! We will learn how to do so in the next section using arguments.

Node Arguments

Normally, when we want to pass arguments we do the following:

node filename argument1 argument2 argumentN.... But the question is, how can you access these arguments ?

The simplest way of retrieving arguments in Node.js is via the process.argv array. This is a global object that we can use without importing any additional libraries to use it. These arguments can be accessed within the application via the process.argv array. Let us start using arguments!

Modify the file to the following:

let message = 'Hello World!';console.log(process.argv)

and run node index.js argument we will have something like the following image.

nodeargs

You will have noticed that we have an array with 3 string items. I marked them with 0,1 and 2.

The argument with key0 is the node itself, argument 1 is the file being executed and the last (2) argument is the argument that we will be using in this tutorial.

Ok, so now we need to do something with the last argument. Let’s display a customized message on the console.

change the code to the following:

let name = process.argv[2];let message = `Hello ${name}`;console.log(process.argv)

What we did here is we initialize a variable called name have a value from the third (key 2 as we start counting from 0 ) argument of the current process. Let’s run node index.js Perlat (Perlat is my name, so you can change this accordingly)

helloname

Make it Executable

So far so good, we have created our simple app, and we can run it by running node index.js name but we need to be inside the directory for this to work. and we need to run every time the node and then the file, and then add an argument.

How can we create an executable that will allow us to run the command from whatever directory?

The answer is node binaries! And we can easily do this by adding a new field in the package.json file, the bin field. More info about the bin field here. Now, add this inside your package.json, I usually add this just after the main field.

"bin":{  "pawnhub":"./index.js"},

By doing so, we say to node that we want to register a command named pawnhub that will execute the ./index.js file upon running it. We can add multiple executables inside the bin file by specifying the name and the file to execute.

If you are impatient and already ran the command pawnhub name you will get an error command not found: pawnhub this is because the command is not linked. We can do this by running npm link inside our directory, and voila! our package is available symlinked globally on our system! Go ahead an try it. It will fail!

Reason is because we need to add #!/usr/bin/env node at the very top of the index.js file.

By adding it , we are telling *nix systems that the interpreter of our JavaScript file should be /usr/bin/env node which looks up for the locally-installed nodeexecutable.

In Windows, that line will just be ignored because it will be interpreted as a comment, but it has to be there because npm will read it on a Windows machine when the NodeJS command-line package is being installed. Now try again and it should be working fine!

pawnhubname

Now we have a package that is acceptin arguments and can be accessed globally. We need to start working on our final package, making the http requests to haveibeenpawned.com website.

Install Axios

What is Axios?

Axios is a promise based HTTP client for the browser and node.js. We can make requests such as GET, POST, DELETE or PUT. we are going to use only the GET request.

More information about axios here.

Because Axios is an npm package we can install it by running npm install axios and it will be installed on our project. Axios can be used in browser applications as well by using a CDN or the path to the file like:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Using Axios

This is a simple GET request using axios! (modified from the example on the official docs)

const axios = require('axios');​// Make a request for a user with a given IDaxios.get('ENDPOINT')  .then(function (response) {    // handle the response when it is a success    console.log(response);  })  .catch(function (error) {    // handle when error ocurrs (eg: 404)    console.log(error);  })

Using Haveibeenpawned.com API

Go ahead and try the https://haveibeenpwned.com website (HIBP for abbreviation) and check if you have an account that has been compromised in a data breach. We will be using their API to achieve the functionality we desire.

The docs for using the API, for a reference.

Ok, now let’s make a request to HIBP API. Modify the index.js to reflect the bellow code

#!/usr/bin/env node

const axios = require('axios');

axios.get(`https://haveibeenpwned.com/api/v2/breachedaccount/admin@test.com`)
.then(response=>{
     console.log(response.data)
})
.catch(err=>{
    console.log(err)
})

We are calling the API to search the breachedaccount for admin@test.com email.

Now run pawnhub and you should get a big JSON object like the following sample.

bigjson

But we don’t need every information from that JSON object…

Lets edit the file to reflect the following:

#!/usr/bin/env node

const axios = require('axios');

axios.get(`https://haveibeenpwned.com/api/v2/breachedaccount/admin@test.com`)
.then(response=>{
let breaches=[]; //create empty array 
    console.log(`admin@test.com was found in ${ response.data.length} breaches!`) 
    //iterate each breaches to get only specific attributes
    response.data.forEach(breach => {
        breaches.push({
            Name:breach.Name,
            Domain:breach.Domain,
            BreachDate:breach.BreachDate,
            AccountsHacked:breach.PwnCount,
        })
    });
    console.table(breaches) //display in pretty table! :D 
})
.catch(err=>{
    console.log(err)//display error
})


Now we should have a better representation of the data we got it should similar to the following:

breachtable

Great, but this is not dynamic, we have hardcoded the email… How can we change this? Of course by using arguments!

Lets modify the code to the following:

#!/usr/bin/env node

const axios = require('axios');
const email = process.argv[2] || 'admin@test.com'; //get the email from the arguments or set a default value
axios.get(`https://haveibeenpwned.com/api/v2/breachedaccount/${email}`)
.then(response=>{
let breaches=[]; //create empty array 
    console.log(`${email} was found in ${ response.data.length} breaches!`) 
    //iterate each breaches to get only specific attributes
    response.data.forEach(breach => {
        breaches.push({
            Name:breach.Name,
            Domain:breach.Domain,
            BreachDate:breach.BreachDate,
            AccountsHacked:breach.PwnCount,
        })
    });
    console.table(breaches) //display in pretty table! :D 
})
.catch(err=>{
    console.log(err)//display error
})

We did it!

We can now query the API for any email we want by running pawnhub THE_EMAIL@DOMAIN.TLD and check if that email has been compromised! So now what? Well, now we need to do our final step, publish the package on the NPM registry!

Publish the Package

Authenticate

Well, for obvious reasons you need to create an account to be able to publish to the NPM registry!

To create an account in the NPM registry click here.

After creating an account, you need to authenticate our self by running the command npm login, you would be prompted to provide our details, you need to enter the required details and you should log in!

To test that the login was successful, enter the command npm whoami, your username should be displayed to the CLI.

Publish

Now the final step for our package to be available for the global community! Open the terminal and run the following inside the project directory npm publish --access public this will publish the package with public access. and will be available on the npm registry. for this example, I have chosen the name to be @perlatsp/pawnhub and is now available here. Make sure that you change the name inside the package.json file!

npm publish

Boom!💥 Mission accomplished! ✅

We have just learned how to create and publish an NPM package to the NPM registry. The next step is to improve our package by adding more features or fixing any bugs… 🐞

Test the Package

Ok, we have published our package..how can we be sure that everything went as intended?

Now on your terminal run npm unlink to remove the symlink we have created on this step and install our brand new package by running npm install -g YOURPACKAGENAME I am using npm install -g @perlatsp/pawnhub. We just installed our package and is globally available via pawnhub (remember this is the package name that I set, yours should be different. Test it by running pawnhub any@email.com and check the results. For the purpose of this tutorial, we have not done anything for error handling, so in case the email is not valid or does not exist in any databreakch you might get non handled errors.

Now we have just finished this tutorial.

Go and make some create tools and packages! 🙆‍♂️

Let me know if you have any questions! ❓

If you have followed this tutorial please do comment below the awesome tools you have created!

I’ve always been using WAMP as my local dev environment for a quite amount of time while i was using Windows OS, then I switched to Mac OS and used MAMP for a while. That was the case until one of my colleagues recommended devilbox. I gave it a try, and since then I’ve been using it as my local dev environment.

What is the Devilbox

No, it does not has to do anything with the devil. As the author describes it in the official website

The Devilbox is a modern and highly customisable dockerized PHP stacksupporting full LAMP and MEAN and running on all major platforms. The main goal is to easily switch and combine any version required for local development.

You don’t have to worry if your Operating System will support it. The Devilbox supports LinuxMac, and Windows OS!

The Devilbox is running

Requirements

I do believe I do not need to go through the first 2 requirements 😃.

To use the Devilbox you will need to have Docker installed on your computer. For the sake of this article and because I am using Mac OS I will show you how to download and install Docker for Mac.

Install Docker

There are many ways to install Docker for Mac

One way is to head to https://docs.docker.com/v17.12/docker-for-mac/install/#download-docker-for-macand click Get Docker for Mac (the preferable version is always stable). When the download is finished open the Docker.dmg the file you just downloaded and follow the instructions to complete the installation.

The second is to install it via homebrew the MacOS package manager. To install it open your terminal and type the following command

bash
~ brew install docker

Next step is to run docker and the easiest way to do it is by pressing CMD + SPACE and type docker and then ENTER. You should get a notification when docker is running.

Install Devilbox

The Devilbox does not come with any install package to install it you have it clone the repository to your local machine. To achieve this, we use the command git clone REPOSTIORY_URL.git the project’s repo is hosted on GitHub. Let’s proceed to install devilbox.
Open a terminal window, and type git clone https://github.com/cytopia/devilbox and wait for the cloning process to finish.

When the clone finishes you need to enter the devilbox directory by typing cd devilbox you should see the following.

.ENV file

Because the Devilbox is configurable via a .env file, our next step is to copy the env-example file to .envto so we can run the following command:

cp env-example .env

Start Devilbox

The time has come, to launch the devilbox!

To launch the devilbox you need to run the following command on your terminal while you are instead the devilbox directory. docker-compose upnow it will pull all the required containers! The first time you run this it might take a while, depends on your internet connection. But once you have all the images, you should be able to start all the containers in a matter of seconds (~4-5 seconds).

TIP! Run docker-compose up -d to run the containers in the background detached from your current terminal window.

When all the images are pulled, you should be able to access devilbox localhost URL. By default, The Devilbox is listening to port 80 which means you can access it by visiting http://localhost

Starting and stopping containers is done via docker-compose. If you have never worked with it before, have a look at their documentation for overviewupstopkillrmlogs and pull commands.

More about starting The Devilbox here

Configuring Devilbox .ENV FIle

Devilbox is configurable and you can easily switch between dev environments like (PHP, APACHE, MySQL) or (PHP, NGINX, MariaDB).
just open the .env file with your favorite editor and configure it to match your taste environment. I am using Visual Studio Code

Every configuration is self-explanatory, the most common configuration will be the following where you change the PHP_SERVER version, HTTPD_SERVERand MYSQL_SERVER. As you can see, I am running PHP 7.2 NGINX stable and MariaDB 10.3 Go through the .env file to discover other settings.

Read more about configuring the env file here

Projects Directory

The devilbox’s projects directory is located inside the devilbox directory ./devilbox/data/www it should be empty by default. Here is where all your projects will live.

For each project, you will need to create a folder.

Read more here

Docroot Directory

The docroot directory is a directory within each project directory from which the webserver will serve the files.

By default this directory must be named htdocs. This can be changed as well but is outside the scope of this tutorial.

Local domain suffix

The default domain suffix (TLD_SUFFIX variable in .env file) is loc. That means that all your projects will be available under the following address: http://<project-directory>.loc. This can be changed as well in the .envfile TLD_SUFFIX!

WordPress Installation

Let us take an example of a WordPress installation from start to the end.

Open the terminal and run the following:

The next step is now to add the record in our hosts file. To do so, run sudo nano /ets/hosts to edit it with the nano editor and add the following line

`127.0.0.1 testwp.loc`

hit save. Navigate again to http://testwp.loc/ and now you should see the WordPress install page.

Next step now, is to create a database for WordPress to use. We can do it by using the terminal or by using PHPMyadmin which comes with the devilbox. To access phpMyAdmin first navigate to http://localhost/index.php> Tools > phpMyAdmin in case it asks for credentials enter root as user and leave the password field empty.

No create a new database from the sidebar, I will name it wp_testdb.

Once done that head back to WordPress Install Page and continue and add the freshly created database.

Note! For the Database host instead of localhost you need to enter mysql as this is the name of the MySQL server (container)running in the devilbox environment!

Everything should have run smoothly and you should see the new WordPress site up and running on http://testwp.loc

Conclusion

The Devilbox is a free and open source project very very easy to set up and run an PHP,Nginx MySQL dev environment and a WordPress installation read following this tutorial should take approximately 10 minutes! I have been using Devilbx for about 1 year now, and I am pretty happy with it and find it very convenient when I am working on a project with PHP 7, and I have to switch to a project running on PHP 5.6 it takes me less than 15seconds! ⏲

Have you used The Devilbox before? Would you give it a try?