Sunday, December 25, 2022

How to enable HTTPS in Laravel Homestead

 Link 1: https://inspector.dev/how-to-enable-https-in-laravel-homestead/

Link 2: https://medium.com/dinssa/ssl-certificates-laravel-homestead-windows-https-f83ec8b3198


In this article I’ll show you how to enable HTTPS for your local applications served by Homestead, the official development environment for Laravel developers.

I met the need to enable HTTPS because I am working to implement browser notifications for Inspector using Pusher/Beams. But Beams requires that the application be necessarily served over HTTPS. It is required also in the local development environment. 

Laravel Homestead comes to the rescue.

I adopted Laravel Homestead as my local development environment for three years. It radically changed my development experience creating a faithful replica of the production environment separated for each project.

If you are looking for a step by step guide to use Laravel Homestead to supercharge your development experience take a look at this article I wrote for Homestead beginners: 

https://inspector.dev/how-and-why-to-use-laravel-homestead-for-local-development-real-life-tips/

What is an SSL certificate?

An SSL certificate is a digital certificate that authenticates a website’s identity and enables an encrypted connection. SSL stands for Secure Sockets Layer, a security protocol that creates an encrypted link between a web server and a web browser.

In short: SSL keeps internet connections secure and prevents criminals from reading or modifying information transferred between client and server. That’s why it is a mandatory requirement to work with many web technologies.

Since its inception about 25 years ago, there have been several versions of SSL protocol, all of which at some point ran into security troubles. A revamped and renamed version followed — TLS (Transport Layer Security), which is still in use today.

However, the initials SSL stuck, so the new version of the protocol is still usually called by the old name.

Trust Laravel Homestead SSL Certificates

By default, Laravel Homestead generates a security certificate for all sites you register.

If you attempt to access your application using https://… instead of http://…, the browser and the web server (Homestead) establish an SSL connection using a process called “SSL Handshake”.

Since the Homestead certificates are generated locally, not released from a public Certificates Authority, the browser will warn you every time you visit the local site.

To get your browser to trust Homestead’s self-signed certificates, you have some options:

  • Click through the privacy warning every time you visit a local site;
  • Add each generated certificate one by one (not sure this will persist through reprovisioning);
  • Import Homestead’s root CA to your browser’s trusted authorities.

The last one is by far the most long-term solution, so I’ll show you how to do this below.

Add Homestead’s Certification Authority to Trusted Certificates in your browser

These instructions are specific to Chrome, but adding a certificate to other browsers should just be a quick Google search away.

The gist is to grab the root CA file from the Homestead Vagrant box, and copy it in your project directory. The project directory is accessible from your host machine. So you will be able to import it into Chrome.

  • First, ssh into your running Vagrant machine (vagrant ssh);
  • Navigate to /etc/ssl/certs (in Homestead versions < 11, you want to go to /etc/nginx/ssl);
  • Copy ca.homestead.homestead.pem from this directory into the project’s directory (usually /home/vagrant/code), so the command should be cp ca.homestead.homestead.pem /home/vagrant/code (in Homestead versions < 11, this file is ca.homestead.homestead.crt);
  • Open Chrome’s settings (via the menus or just visit chrome://settings in the navigation bar);
  • Go to “Manage certificates / Manage HTTPS/SSL certificates and settings”. This will open a new window (set “all files”);
  • Start the Import process, and browse for that file we just copied over;
  • When selecting the certificate store on the next screen or so, use “Place all certificates in the following store“. Browse, and select “Trusted Root Certification Authorities
  • Finish, and restart Chrome (chrome://restart in the navigation bar)

That’s it! You should be able to visit your various local sites using https without issues.

To avoid bringing the certificate file to your repository you can add the filename to your .gitignore.

For any other browser (or your OS itself), you should be able to find instructions specific to your browser for actually importing the certificate we copied in step 3.

Conclusion

Homestead is a really good tool to work with. It lets you focus on the code and not the server, and allows you to perfectly replicate the production environment.

Thank you so much for reading it, share this article with your network if you think it can be helpful for other developers too.

Thursday, December 22, 2022

[2022] How to set up your SSH key for GitLab on macOS

 https://medium.com/devops-with-valentine/2021-how-to-setup-your-ssh-key-for-gitlab-on-macos-dfccec6904fb#:~:text=In%20GitLab%2C%20go%20to%20your,can%20easily%20identify%20it%20later.

Set up Laravel Homestead on Mac – Step by step

 

Step 1

Download and install Vagrant

https://www.vagrantup.com/downloads.html

Scroll down, download the version for macOS.

Run the package installer

 

Step 2

Download and install VirtualBox

Vagrant cannot run without VirtualBox

https://www.virtualbox.org/wiki/Downloads

Download the version for OSX, Run the package installer

 

Step 3

Add Homestead to Vagrant Box

Open terminal and run the following command

vagrant box add laravel/homestead

You may get a response like this:

This box can work with multiple providers! ...
1) hyperv
2) parallels
3) virtualbox
4) vmware_desktop

We are using VirtualBox, so enter the option 3.

This will take quite a while. It may even take up to 2 hours.

Run this command to check if it has been successfully added to our box.

vagrant box list

You should see something like this

laravel/homestead (virtualbox, 9.4.0)

 

Step 4

Start installing Homestead

Now we need to download the laravel files into our computer. Choose a location where you would like to place it and modify the path in the code accordingly. For me, I have chosen a new folder named laravel inside my Documents folder.

git clone https://github.com/laravel/homestead.git ~/Documents/laravel/Homestead

After successful cloning, navigate inside this folder.

cd Documents/laravel/Homestead

and run this command to initialise Homestead

bash init.sh

You should see a response like this

Homestead initialized!

 

Step 5

Create Keys

Navigate to the Homestead folder that was created under Documents/laravel. Open the file named Homestead.yaml

You will see these lines in the file.

authorize: ~/.ssh/id_rsa.pub

keys:
- ~/.ssh/id_rsa

These are the keys that we need to create before we can get it to run.

So go back to your terminal and run this command to create it.

ssh-keygen -t rsa -C "you@homestead"

You will be prompted to set the location. Hit enter to let it remain in the default root location.

You will be again be prompted to enter a passphrase. Hit enter to leave it blank, as we are simply running on our computer and not on a server.

You will get a response like this

Your identification has been saved in /Users/technofreek/.ssh/id_rsa.
Your public key has been saved in /Users/technofreek/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:xxxxxxxxxxxxxxxxxxxxxxxxxxx you@homestead
The key's randomart image is:
+---[RSA 2048]----+
[image]
+----[SHA256]-----+

Step 6

Configure Homestead

Now navigate back one step so that you are inside Documents/laravel folder.

cd ..

And run this command to create a folder named code. This folder will hold your projects.

mkdir code

Now you should have this folder structure

Documents
 - laravel
   - code
   - Homestead

Go back to your text editor or IDE where you opened the Homestead.yaml file. Locate the folders tree and modify it to map to the folder that you just created.

folders:
    - map: ~/Documents/laravel/code
    to: /home/vagrant/code

Save the file.

Step 7

Start Homestead machine

Go back to your terminal and run this command. This will get the vagrant machine up and running.

vagrant up

If you make any changes to the Homestead.yaml file, you can restart the server by calling these commands

vagrant halt

and then

vagrant up

Alternatively, this one command also suffices to reprovision your server:

vagrant provision

or

vagrant up --provision

Now run this command to ssh into the machine. This uses the key that we generated to login into the machine.

vagrant ssh

This should bring up the command line.

vagrant@homestead:~$

Note: Enter exit command to logout from the machine.

Enter the command ls to check if our configuration was correct and you should see our newly created code directory listed there.

vagrant@homestead:~$ ls
code

 

Step 8

Install Laravel in Homestead

Make sure you are still logged in to the vagrant machine.

Navigate into the code directory

cd code

Following the steps from Laravel installation page now,

First, download the Laravel installer using Composer:

composer global require laravel/installer

 

Step 9

Create first project

Now the ‘new’ command will use this installer to create a new project with a fresh installation of laravel and all its dependencies.

So in the command line, still inside code folder,

vagrant@homestead:~/code$

Enter the command to create your first project

laravel new myproject1

This takes a little while. Once successfully completed, check the folder that was just created. As you can see, the entire project structure was generated.

 

Step 10

Configure the project

Now we configure this new project in our Homestead.yaml file.

Firstly, Add the names of the new project site and database to the respective places.

sites:
    - map: myproject1.test
    to: /home/vagrant/code/myproject1/public

databases:
    - myproject1

Secondly, go to myproject1/.env file, in the code/myproject1 folder, and change the following values to set the database name and set the default username and password used by homestead.

DB_DATABASE=myproject1
DB_USERNAME=homestead
DB_PASSWORD=secret

Save the file. Your project is configured now.

But you cannot visit the website in your browser just yet. You need to map the hosts file so that the server recognizes the components,

 

Step 11

Map the hosts file

The domain that we have set which is ‘myproject.test‘. In order to be able to open this in our browser we need to add it to the system hosts file.

Open a new window in your terminal, and type the following command.

sudo nano /etc/hosts

This will open up the hosts file in your terminal in edit mode. It will look like below code. At the end of the file, add a line with the local address and our project site domain that we have set.

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##

127.0.0.1       localhost
255.255.255.255 broadcasthost
::1             localhost

127.0.0.1       myproject1.test

The last line is the one that we added.

Save and close the file. Ctrl+O -> Enter to save, and Ctrl+X to close.

 

Step 12

Run

Open your browser and open the website address, postfixed with :8000

http://myproject1.test:8000/

You should see a basic LARAVEL website.

 

Step 13

Setting up multiple projects/sites

First, (same as step 9) let us create the second project from laravel machine. Log in to it and navigate to code folder and simply create the new project. We’ll name it as proj2.

vagrant ssh
cd code
laravel new proj2

Second, for configuring the new project, (same as step 10) go to Homestead.yaml file and make new entries for sites and databases, and give the names.

sites:
    - map: myproject1.test
    to: /home/vagrant/code/myproject1/public
    - map: proj2.demo
    to: /home/vagrant/code/proj2/public

databases:
    - myproject1
    - proj2

And, go to proj2/.env file, which is inside code/proj2 folder and change the following values:

DB_DATABASE=proj2
DB_USERNAME=homestead
DB_PASSWORD=secret

Third, (same as in step 11), open a new terminal window, edit hosts file, and add an entry for the new site.

127.0.0.1       myproject1.test
127.0.0.1       proj2.demo

That’s all. Open your browser and try both URLs, they should work fine and the basic laravel site page should appear.

http://proj2.demo:8000/
http://myproject1.test:8000/

But these look the same for now. Let us change the title for both websites.

Go to the code folder of the first project, in my case its Documents/laravel/code/myproject1.

Open the file

myproject1/resources/views/welcome_blade.php

Change the heading text in the body

<div class="title m-b-md">
My first project
</div>

Save and close. Run the reset provision command

vagrant up --provision

And refresh the websites. You should be able to see different headings.

https://fabcoding.com/2020/04/20/set-up-laravel-homestead-on-mac-step-by-step/

Thursday, November 10, 2022

Loop object best approches

combine Object.keys() and Array.prototype.forEach():

var obj = { first: "John", last: "Doe" };

Option One: 

Object.keys(obj).forEach(function(key) {
    console.log(key, obj[key]);
});

Option Two: 


for (const key of Object.keys(obj)) {
    console.log(key, obj[key]);
}

Option Three: 

Object.entries(obj).forEach(
    ([key, value]) => console.log(key, value)
);


Option Four: 

for (const [key, value] of Object.entries(obj)) {
    console.log(key, value);
}

Vue.js — Three common approaches to organize your API calls

 When building a single page application, it is very common to make API calls to communicate with the server side, such as fetching data, submitting form, etc. Yet, Vue doesn’t provide an official practice for making API calls. Hence, I have summarized three common ways people are using to organize their APIs.

Concept of Programming and Software Development — by Andrey Suslov

1. Centralize all API calls in Vuex action

This approach is heavily inspired by the React-Redux model. Instead of having separated API calls in different components, you keep everything in Vuex action. Components know only actions but not endpoints. After the API call is returned, you do some data massage and business logic. After that, you update the state and notify components about the state change.

export default new Vuex.store({
state: {
account: null
},
mutations: {
setAccount(state, account) {
state.account = account;
}
},
actions: {
async signin({ commit }, { username, password }) {
let data = await axios.get('/api/signin', {
username,
password
});
commit('setAccount', data)
}
}
}

Then somewhere in your component:

export default {
computed: {
account() {
return this.$store.state.account
}
},
...
methods: {
submit(username, password) {
this.$store.dispatch('signin', { username, password })
},
...
},
...
}

The major advantage is that this is probably one of the most organized approach so far. You encapsulate not only the endpoints, but also the logic. It is extremely clean for components as they only need to care about the state change. Yet, the drawback is also quite obvious. It relies on the model of single direction of data flow from the store to components. It works well on project with concurrent and shared data. Yet, for application that is consisted of many different pages with totally different functionalities and local states, you may find this approach a bit crunky.

2. Manage API calls with plain JavaScript objects

This approach is more straight forward comparing with the previous one. You just make a file with one or more objects, and put all your API calls there. Here is a simplest example:

const signin = async (username, password) => {
let data = await axios.get('/api/signin', {
username,
password
});
let massageData = .... //Some data massage
return massageData
}
export {
signin
}

Then somewhere in your component:

import { signin } from '@/api';export default {
...
methods: {
submit(username, password) {
signin(username, password).then(account => {
...do something
})
},
...
},
...
}

The major pros of this approach is that it is not coupled with any data model. It is easy to learn and flexible enough to work in almost any application. It provides good readability without a great impact on your application architecture. The drawback is things happen outside the Vue instance. It can be quite messy when you need to trigger some Vue actions inside your isolated objects instead of the components, such as changing states, pushing routes, etc.

3. Keep APIs in components with boilerplate caller

This is the most casual one. You define some boilerplate callers and keep the endpoints in your components. You may use a separated file to store those callers:

const postForm = (url, params = {}) => {
let formData = new FormData();
Object.entries(params).forEach(([key, value]) => {
formData.set(key, value);
});
return axios({
method: 'post',
url: url,
data: formData,
headers: {'Content-Type': 'multipart/form-data' }
})
}
export default { postForm };

And somewhere in your component:

import { postForm } from '@/api';export default {
...
methods: {
submit(username, password) {
postForm('/api/signin', { username, password })
.then(account => {
...do something
})
},
...
},
...
}

Or you may even use a mixin:

export default {
methods: {
$_apiCaller_postForm(url, params = {}) => {
...
})
}
}

The rationale behind is that scalability is not always the major concern. Sometimes you know you are working on a short term project, and the endpoints are very unlikely to have change. This approach suits best for these kind of one-off developments.

This article aims to provide a short introduction on some common approaches people use to make API calls in Vue. There is no right or wrong answer. No approach is definitely better than the others. It totally depends on the situation. Also, I believe there are many other approaches that are not listed in this article. Please feel free to leave a comment and let me know if you know something interesting. :)