Friday, 31 March 2023

Setup nuxtjs with typescript

>> Url source on Github

1. Three packages Nuxt Typescript support

- @nuxt/types: contains Nuxt Typescript type definition

- @nuxt/typescript-build: for use Typescript in pages, layouts, comopents, plugins, middlewares.

- @nuxt/typescript-runtime: to provide Typescript runtime support for nuxt.config.js file, local modules and serverMiddlewares (^Nuxt 2.15 no longer needed)

2. Install Typescript for Nuxtjs

- with "nuxt": "^2.15.8", using: "@nuxt/types": "^2.15.8", "@nuxt/typescript-build": "^2.1.0",

yarn add --dev @nuxt/typescript-build@2.1.0
yarn add --dev @nuxt/types@2.15.8
 

3. Configuration

- edit nuxt.config.js to add module that are used during the build process, Nuxt.js will install the necessary dependencies (including TypeScript itself) and configure the build process to include TypeScript files

import type { NuxtConfig } from '@nuxt/types'

export default {
.....
buildModules: ['@nuxt/typescript-build']
.....
}

- add tsconfig.json to configure the TypeScript compiler, which is used to transpile TypeScript code into JavaScript

{
"compilerOptions": {
"target": "ES2018",
"module": "ESNext",
"moduleResolution": "Node",
"lib": [
"ESNext",
"ESNext.AsyncIterable",
"DOM"
],
"esModuleInterop": true,
"allowJs": true,
"sourceMap": true,
"strict": true,
"noEmit": true,
"baseUrl": ".",
"paths": {
"~/*": [
"./*"
],
"@/*": [
"./*"
]
},
"types": [
"@nuxt/types",
"@nuxt/typescript-build",
"@types/node"
]
},
"exclude": [
"node_modules"
]
}

-  add vue-shim.d.ts to provide TypeScript type information for Vue.js components

declare module "*.vue" {
import Vue from 'vue'
export default Vue
}

Thank you

Reference:

- https://typescript.nuxtjs.org/guide/setup/



Wednesday, 29 March 2023

Two ways to call Api in Nuxtjs

* Notice: this post apply for nuxtjs with typescipt

1. Method 1: using axios directly

- Install axios

yarn add @nuxtjs/axios

- Create file ./plugins/axios.ts

import axios from 'axios'

const api = axios.create({
baseURL: 'http://api.example.com',
headers: {
'Content-Type': 'application/json'
}
})

export default api

- Using to call Api

<template>
<div class="container">
<h1>Call Api</h1>
</div>
</template>

<script lang="ts">
import Vue from 'vue'
import api from '@/plugins/axios'

export default Vue.extend({
name: 'IndexPage',
created() {
this.asyncData();
},

methods: {
async asyncData() {
const response = await api.get('/products')
console.log(response)
}
}
})
</script>

2. Method 2: create plugin inject to context

- Install axios

yarn add @nuxtjs/axios

- Create file ./plugins/axios.ts

import { Plugin } from '@nuxt/types'
import axios from 'axios'

const axiosPlugin: Plugin = (context, inject) => {
// Set baseURL for Axios
axios.defaults.baseURL = process.env.API_URL || 'http://api.example.com'

// Inject axios instance to the context as $axios
inject('axios', axios)
}

export default axiosPlugin

- Edit file nuxt.config.js

plugins:
'~/plugins/axios.ts'
],

- Using to call Api

<template>
<div class="container">
<h1>Call API</h1>
</div>
</template>

<script lang="ts">
import Vue from 'vue'

export default Vue.extend({
name: 'IndexPage',
created() {
this.fetchData();
},

methods: {
async fetchData() {
try {
const response = await this.$axios.get('/products')
console.log(response.data)
} catch (error) {
console.error(error)
}
}
}
})
</script>

3. Change config when call API

- example change baseUrl

const response = await this.$axios.get('/members/products',{
  baseURL: 'https://localhost/api' 
})

Thank you


Tuesday, 28 March 2023

Manage incoming and outgoing traffic requests with Burp Suite Community Edition

 1. Install 

- Url download Burp Suite Community Edition (free version)

# set exc for file instal
chmod +x burpsuite_community_linux_v2023_2_4.sh
# install burp
./
burpsuite_community_linux_v2023_2_4.sh

- change port Proxy: Proxy/ Proxy settings / Edit port

2. Using with browser

- open Burp / Temporary project / Use Burp defaults / Start Burp
- Using with browser: Target/ open browser / enter address...
-> results in: Target/ Site map

3. Using with Postman

- Open Postman/ File/ Setting/
+ tab: General / SSL certificate vertitication -> Off
+ tab: Proxy/ Checked Add a custom proxy configration: Checked HTTP, HTTPS, Proxy server: 127.0.0.1:8080 (port of Burp proxy)
+ Call Api in Postman => Result in Proxy/ HTTP history.

Thank you. 

Sunday, 26 March 2023

Configure basic authentication in Nginx for Telescope in Laravel

1. Create User/Password for authentication

# Install Apache Utils
sudo apt install apache2-utils
# create user
htpasswd /etc/nginx/conf.d/.htpasswd dev
# case file .htpasswd not exit
htpasswd -c /etc/nginx/conf.d/.htpasswd dev

2. Config nginx for Telescope in Laravel

# open file config
sudo nano /etc/nginx/sites-available/example.com

# config for
telescope
location /telescope {
try_files $uri $uri/ /index.php?$query_string;
auth_basic "dev";
auth_basic_user_file /etc/nginx/conf.d/.htpasswd;
}

# config for swagger-ui
location /swagger-ui {
try_files $uri $uri/ /index.php?$query_string;
auth_basic "dev";
auth_basic_user_file /etc/nginx/conf.d/.htpasswd;
}

Thank you.

 

Saturday, 25 March 2023

Install and manage Supervisor with example

1. Install supervisor

# install supervisor
sudo apt update && sudo apt install supervisor 
# check supervisor status
sudo systemctl status supervisor

2. Add demo program runDate.sh

# create file runDate.sh
nano runDate.sh 
 
# with content
#!/bin/bash
while true
do
# Echo current date to stdout
echo $(date)
sleep 1
done
 
# set exec for runDate.sh
chmod +x ~/
runDate.sh

3. Configure supervison for program runDate.sh

# create & open runDate.conf
sudo nano /etc/supervisor/conf.d/runDate.conf
 
# content file runDate.conf
[program:runDate]
command=/bin/bash /home/phong/runDate.sh
autostart=true
autorestart=true
stderr_logfile=/home/phong/runDate.err.log
stdout_logfile=/home/phong/runDate.out.log

- autostart = true; // the program started when system boots
- autorestart = true; // restart program after it exits
- stderr, stdout // write err, out for program

4. Using supervisor

# reload the configuration file
sudo supervisorctl reread 
# applies the changes made to the supervisor configuration file
sudo supervisorctl update

# view the last few lines of runDate.out.log
sudo tail /var/log/runDate.out.log 
# show all processes suppervisor managing
sudo supervisorctl
# start mange process of program
supervisor> start runDate
 
# stop mange process of program
supervisor> stop runDate
# show all processes
supervisor> status

# exit the supervisorctl
supervisor> quit
# show all cmd in supervisor
supervisor> help

Thank you 



Four ways to secure a VPS

1. Using a non-root user

# add new user
adduser phong
new password:...
# check group info user
id phong
# add user phong to sudo group
usermod -aG sudo phong
# switch to the user account name "phong"
su - phong
# logout accout
exit 

- Configure SSH for the new user

# create ssh dirctory
mkdir ~/.ssh

# chnage the pemissions of ~/.ssh to 'rwx------',
# mean owner has read, write, excute, orther users have no permissions at all

chmod 700 ~/.ssh

# authorized_keys is used to store public keys that are authorized
# to access the current uesr's account

nano ~/.ssh/authorized_keys
 
# copy the content id_rsa.pub to clipboard
.ssh pbcopy < id_rsa.pub 

# past content to ~/.ssh/authorized_keys and save
Ctrl S > Ctrl X 

# change the permissions of authorized_keys file to 'rw----'
# only onwner has read, write permissions

chmod 600 ~/.ssh/authorized_keys

- SSH to vps with new user

ssh phong@vps-ip

2. Disable password and root login

# open the sshd_config
sudo nano /etc/ssh/sshd_config 
 
# change content
PermitRootLogin yes => no 
PasswordAuthentication  yes => no
 
# reload sshd
sudo systemctl reload sshd 
 
# now we can not login as root  

3. Block incoming traffic on non-public ports

sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https 
sudo ufw enable 
 
# confirm ufw
sudo ufw status 

4. Enable automatic security updates

# open sshd_config
# unattended-upgrades package is responsibile for automaticlly
# downloading and installing security opdates for the system
# --priority=low mean other packages and processes given higher priority 
# when system resources are limited
sudo dpkg-reconfigure --priority=low unattended-upgrades
choose yes
 
# displays the current config value for APT::Periodic::Unattended-Upgrade
# which is used to control the behavior for the unattended-upgrade
apt-config dump APT::Periodic::Unattended-Upgrade 

Thank you.

Automated deployments your application from github with webhook, nginx

- example for app example.com
- i assume you installed nginx

1. Add a repository webhook on Github

- Settings > Webhooks > Add webhook: add a webhook with settings:
+ Payload UR: https://example-app.com/hooks/example-webhook
+ Content type: application/json
+ Secret: your-secret-key
+ SSL verification: enabled
+ Which events would you like to trigger this webhook: Default option: "Just the push event."
+ Active — Uncheck this option. We will activate later after we create the endpoin

2. Install Webhook server to listen incoming request from Github

- install Webhook server

curl -LJO https://github.com/adnanh/webhook/releases/download/2.8.0/webhook-linux-amd64.tar.gz
tar -xzf webhook-linux-amd64.tar.gz
sudo systemctl stop webhook.service
sudo cp webhook-linux-amd64/webhook /usr/bin/
sudo systemctl start webhook.service
webhook --version
# must be version 2.8.0
# webhook will start default port 9000, location in /usr/bin
# cmd for webhook
which webhook -version
# url guide webhook
https://github.com/adnanh/webhook
# webhook version 2.6.9 not working

- create /var/www/hook.json in

# create hooks.json
nano hooks.json
 
# add content for hooks.json
[
{
"id": "example-webhook",
"execute-command": "/var/www/auto_deploy/autodeploy-example.sh",
"command-working-directory": "/var/www/example.com",
"trigger-rule":
{
"and":
[
{
"match":
{
"type": "payload-hmac-sha1",
"secret": "your-secret-key",
"parameter":
{
"source": "header",
"name": "X-Hub-Signature"
}
}
},
{
"match":
{
"type": "value",
"value": "refs/heads/master",
"parameter":
{
"source": "payload",
"name": "ref"
}
}
}
]
}
}
]
 
# refs/heads/master: master is your branch commit

- create /var/www/auto_deploy/autodeploy-example.sh

#!/bin/sh

# 1. Fetch the latest code from remote
git pull -f origin master

# 2. Install dependencies
yarn install

# 3. (Optional) Build step that compiles code, bundles assets, etc.
# yarn build

# 4. Restart application
pm2 restart [app-name]

- make it executable for autodeploy-example.sh

chmod +x autodeploy-example.sh

- start Webhook

# to run webhook
/path/to/webhook -hooks hooks.json -verbose
webhook -hooks hooks.json -verbose

3. Config nginx for webhook

- configure nginx that redirects all requests with destination https://example.com/hooks/..... to Webhook.  

# open file virtual host file: example.com
sudo nano /etc/nginx/sites-available/example.com
# add following code
# Webhook reverse proxy
location /hooks/ {
proxy_pass http://127.0.0.1:9000/hooks/;
}
# Check NGINX config
sudo nginx -t
# reload nginx
sudo systemctl restart nginx

* some errors can happen

- [webhook] error in exec: "...autodeploy-example.sh": permission denied

# reason forget set excutive
chmod +x
autodeploy-example.sh

Thank you.



Thursday, 23 March 2023

Deployment Laravel with Nginx, SSL with Lets Encrypt

In this tutorial, i build vps for subdomain api.example.com

1. Access your Vps

ssh user@ip

2. Install PHP 8.1

sudo add-apt-repository ppa:ondrej/php -y
sudo apt install -y php8.1 php8.1-{cli,gd,curl,mysql,ldap,zip,fileinfo,fpm,xml,mbstring,exif,pspell,imagick,bcmath} 
 
# or install one by one modules
sudo apt install -y php8.1 php8.1-curl php8.1-mysql
 
# cmd for check status php
sudo nano /etc/php/8.1/fpm/php.ini 
sudo systemctl restart php8.1-fpm
 

3. Install composer

sudo wget -O composer-setup.php https://getcomposer.org/installer
sudo php composer-setup.php --install-dir=/usr/bin --filename=composer

4. Clone, build Laravel app

- install laravel project

composer create-project --prefer-dist laravel/laravel api.example.com
cd api.example.com
php artisan
nano .env
 
sudo mv ~/api.example.com /var/www/api.example.com
sudo chown -R www-data.www-data /var/www/api.example.com/storage
sudo chown -R www-data.www-data /var/www/api.example.com/bootstrap/cache
 

- Provide access for composer and install packages

sudo chmod -R 775 /var/www/api.example.com/storage
sudo chmod -R 775 /var/www/api.example.com/bootstrap/cache

- create file .env

cp -a .env.example .env
nano .env
php artisan key:generate 

4. Config Laravel app in Nginx

- I consume you installed Nginx

- Set Up Nginx Server Blocks (Virtual Hosts) for api.example.com

sudo cp /etc/nginx/sites-available/default /etc/nginx/sites-available/api.example.com
sudo nano /etc/nginx/sites-available/api.example.com

- Config for /etc/nginx/sites-available/api.example.com

server {
listen 80;
listen [::]:80;
server_name api.example.com; 
root /var/www/api.example.com/public;
  
add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";
 
    index index.html index.htm index.php;
  
    charset utf-8;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
 
location = /favicon.ico { access_log off; log_not_found off; }
location = /robots.txt { access_log off; log_not_found off; }
 
    error_page 404 /index.php;
 
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
include fastcgi_params;
fastcgi_read_timeout 3600;
}
location ~ /\.(?!well-known).* {
deny all;
}
}

* Now that we have our server block file, we need to enable it. We can do this by creating symbolic link from this file to the sites-enabled directory, which Nginx reads from during startup.

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/ 

- Check nginx config status

# Check NGINX config site-avaiable
sudo nginx -t

# Restart NGINX
sudo service nginx restart 

7. Add record for domain

* This config for subdomain api.example.com

 Host    Type Value   TTL 
 api
 A
 your-vps-ip 
 3600

8. Using Supervisor (process manager for Linux)

- file supervisord.conf

[unix_http_server]
file=/run/supervisord.sock

[supervisord]
nodaemon=true
logfile=/dev/null
logfile_maxbytes=0
pidfile=/run/supervisord.pid

[rpcinterface:supervisor]
supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface

[supervisorctl]
serverurl=unix:///run/supervisord.sock

[program:php-fpm]
command=/usr/local/sbin/php-fpm -F
autostart=true
autorestart=true
priority=5
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
# stdout_events_enabled=true
# stderr_events_enabled=true

[program:nginx]
command=/usr/sbin/nginx -g 'daemon off;'
autostart=true
autorestart=true
priority=10
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
# stdout_events_enabled=true
# stderr_events_enabled=true

[include]
files = /etc/supervisor.d/*.conf

9. Add SSL with LetsEncrypt

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx -d api.example.com
 
# check certbot auto renew  
sudo systemctl status certbot.timer  
 
# or manually renew ssl (90 day will expired)
sudo certbot renew --dry-run 

* more option features

(1) install PostgreSQL

# install pgsql extension for php8.1
sudo apt-get install php8.1-pgsql

# install postgresSql
sudo apt update
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
echo "deb http://apt.postgresql.org/pub/repos/apt/ $(lsb_release -cs)-pgdg main" | sudo tee /etc/apt/sources.list.d/postgresql-pgdg.list > /dev/null
sudo apt update
sudo apt install postgresql-14
sudo ss -atnp | grep 5432
dpkg -l | grep postgresql
sudo systemctl restart postgresql
sudo systemctl enable postgresql
sudo systemctl status postgresql
sudo -u postgres psql --version

# using postgre
sudo -i -u postgres
sudo -u postgres psql
sudo -u postgres createuser --interactive
sudo -u postgres createdb sammy
# example create myUser & myDB
sudo -u postgres psql
CREATE USER myUser WITH PASSWORD 'myPassword';
CREATE DATABASE mydb;
GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser

# show all DB, all users
\l  
\du

# export db
pg_dump -U postgres -d {dbname} -F p -f /{path-to-db}y/DB_backup.sql

# copy file to local
rsync -avz {user}@{IP}:/{path-to-db}y/DB_backup.sql /{path_to_store}

Thank you.

Golang Advanced Interview Q&A