Friday, September 11, 2020

How to Install Apache2 + PHP 7.2 + Joomla on Ubuntu 20.04

In this post, you will learn how to install Apache2 + PHP 7.2 + Joomla 3.9.21, for write this post i get two references, you checks links in the end post. let's start. 

1. Update and upgrade system packages

 sudo apt-get update && sudo apt-get upgrade

2. Install apache 

sudo apt install apache2

The comands below, you need to stop, start, status, reload and enable apache2 service.

sudo systemctl start apache2.service

sudo systemctl enable apache2.service


3. Install PHP 7.2 is not be avaible in ubuntu default repositories, for that run next commands.

sudo apt-get install software-properties-common

sudo add-apt-repository ppa:ondrej/php

sudo apt-get update && sudo apt-get upgrade

sudo apt install libapache2-mod-php7.2 openssl php-imagick php7.2-common php7.2-curl php7.2-gd php7.2-imap php7.2-intl php7.2-json php7.2-ldap php7.2-mbstring php7.2-mysql php7.2-pgsql php-smbclient php-ssh2 php7.2-sqlite3 php7.2-xml php7.2-zip

sudo systemctl start apache2.service

sudo systemctl enable apache2.service


4. Check version PHP 

php -v

Go to browser type this (localhost or your_ip)

http://localhost/
















5. Install MariaDB

sudo apt install mariadb-server

In this command, Set the password for the root and you choose the other options that it will ask you according to what you need.

sudo mysql_secure_installation

6. Create Database for joomla

sudo mysql -u root -p


CREATE DATABASE YOUR_DATABASE_NAME;

GRANT ALL ON YOUR_DATABASE_NAME.* TO 'YOUR_USER'@'localhost' IDENTIFIED BY 'YOUR_PASSWORD';

FLUSH PRIVILEGES;

EXIT;

7.  Download Joomla 3-9-21

sudo wget https://downloads.joomla.org/cms/joomla3/3-9-21/Joomla_3-9-21-Stable-Full_Package.zip

sudo mkdir /var/www/html/joomla

sudo unzip Joomla_3-9-21-Stable-Full_Package.zip -d /var/www/html/joomla

Change the permissions

sudo chown -R www-data:www-data /var/www/html/joomla

sudo chmod -R 755 /var/www/html/joomla

8. Restar apache2

sudo systemctl restart apache2

9. Configure apache for joomla

sudo nano /etc/apache2/sites-available/joomla.conf


Copy the lines into file and then crtl + o and ctrl + x.

<VirtualHost *:80>
     ServerAdmin admin@example.com
     DocumentRoot /var/www/html/joomla/
     ServerName example.com
     ServerAlias www.example.com

     ErrorLog ${APACHE_LOG_DIR}/error.log
     CustomLog ${APACHE_LOG_DIR}/access.log combined

     <Directory /var/www/html/joomla/>
            Options FollowSymlinks
            AllowOverride All
            Require all granted
     </Directory>
</VirtualHost>

10. Enable Virtual host

sudo a2ensite joomla.conf

sudo a2enmod rewrite

sudo systemctl restart apache2


11. Great the joomla stand up on Ubuntu 20, check

http://YOUR_IP/joomla

First configuration general add your Site Name, Description, email, username i recomend wrote the same and the last add password



















Second Database configuration, choose MySQLI, Hostname: localhost, username: YOUR_USER, password: YOUR_PASSWORD, Database Name: YOUR_DATABASE_NAME 



















And in the end, only check your configuration, and then click 'install' 

































12. If the installation is success then you will get notification.
















13. Click Remove installation folder, is mandatory. 
























14. Click on button 'Administrator'















Open the login, write your username and your passoword.













Great, you install joomla on ubuntu 20.
























References: 
https://www.tecmint.com/install-joomla-on-ubuntu/
https://websiteforstudents.com/apache2-with-php-7-1-support-on-ubuntu-18-04-lts-beta-server/
                    




Monday, September 7, 2020

Basic Login ReactJs - OAuth2 - Axios

React - OAuth2 - Axios

I share basic example how to integrate React, OAuth2 and Axios, in this example i just share code how to implement on  front end of course you need to add css  if you want customize , if you want to know how to implement on backend, you can get example on my github, i used Kotlin or Java for backend. check in the end the post.

Create proyect react:

npx create-react-app login-react-oauth2-axios







Install Axios:

cd login-react-oauth2-axios

npm i axios




Create next folder and files, below of struct and check image

- components
        -login
             Files:
                    Login.js
        -menu
             Files:
                    Menu.js
-services 
        -auth
             Files:
                AuthService.js
        -util
             Files:
                Util.js

















I used class but you prefered, you can use Hooks .

Util.js: Is most import because when you sent request POST, GET, DELETE or something like that add on header your token, for open your web service on backend.

Add next code. (change the url)

For example in my code, my context of my backend is services, i created two const because the first const restApi i used for call all my web services, when i call web service automatically inject header authorization with interceptors, and second const authUrl i used for get my first token from backend.


import axios from "axios";

const restApi = axios.create({
    baseURL: 'http://localhost:9000/services'
})

const authUrl  = 'http://localhost:9000/services/oauth/token';

restApi.interceptors.request.use(function(config){
    console.log("request send");
    let token = sessionStorage.getItem('token');
    config.headers.Authorization = `Bearer ${token}`;
    return config;
})
export {restApi, authUrl}


AuthService.js: I save first token, you have to add YOUR_CLIENT and YOUR SECRET of your backend on btoa.

import { Component } from "react";
import axios from "axios";
import { authUrl } from "../util/Util";

class AuthService extends Component {
  login(json) {
    const headers = {
      Authorization: "Basic " + btoa("YOUR_CLIENT:YOUR_SECRET"),
      "Content-type": "application/x-www-form-urlencoded",
    };

    return axios({
      method: "POST",
      url: authUrl,
      params: {
        username: json.username,
        password: json.password,
        grant_type: "password",
      },
      headers: headers,
    });
  }

  user(accessToken) {
    const payload = this.getDataToken(accessToken);
    return payload.username;
  }

  saveToken(accessToken) {
    sessionStorage.setItem("token", accessToken);
  }

  getDataToken(accessToken) {
    if (accessToken) {
      console.log(JSON.parse(atob(accessToken.split(".")[1])));
      return JSON.parse(atob(accessToken.split(".")[1]));
    }
    return null;
  }

  isAuthenticated() {
    let token = sessionStorage.getItem("token");
    const payload = this.getDataToken(token);
    if (payload != null && payload.username && payload.username.length > 0) {
      return true;
    }
    return false;
  }
}

const authService = new AuthService();

export default authService;



Menu.js: If you login with credetencial correct and display your username.

import React, { Component } from "react";
import authService from "../../services/auth/AuthService";

class Menu extends Component {
  constructor(props) {
    super(props);

    this.state = {
      username: "",
    };
  }

  componentWillMount() {
    let token = sessionStorage.getItem("token");
    let username = authService.user(token);
    this.setState({
      username: username,
    });
  }
  render() {
    return <div>Welcome {this.state.username}</div>;
  }
}

export default Menu;


Login.js: add next code on login.

import React, { Component } from "react";

import Menu from "../menu/Menu";

import authService from "../../services/auth/AuthService";

class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      username: "",
      password: "",
      authenticated: false,
    };
  }

  changeHandler = (event) => {
    this.setState({ [event.target.name]: event.target.value });
  };

  submitHandler = (e) => {
    e.preventDefault();

    authService
      .login(this.state)
      .then((response) => {
        authService.saveToken(response.data.access_token);
        this.setState({
          authenticated: true,
        });
      })
      .catch((error) => {
        console.log(error);
      });
  };

  render() {
    if (this.state.authenticated) {
      return (
        <div>
          <Menu></Menu>
        </div>
      );
    } else {
      const { username, password } = this.state;
      return (
        <div>
          <form onSubmit={this.submitHandler}>
            <div>
              <input
                type="text"
                name="username"
                value={username}
                onChange={this.changeHandler}
              ></input>
            </div>
            <div>
              <input
                type="password"
                name="password"
                value={password}
                onChange={this.changeHandler}
              ></input>
            </div>
            <button type="submit">Login</button>
          </form>
        </div>
      );
    }
  }
}

export default Login;


And the last

App.js:  Add the next code.

import React, { Component } from "react";
import Login from "./components/login/Login";
import Menu from "./components/menu/Menu";
import authService from "./services/auth/AuthService";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      authenticated: false,
    };
  }

  componentWillMount() {
    let isAuth = authService.isAuthenticated();
    console.log(isAuth);

    this.setState({
      authenticated: isAuth,
    });
  }

  render() {
    if (this.state.authenticated) {
      return (
        <div>
          <Menu></Menu>
        </div>
      );
    } else {
      return (
        <div>
          <Login></Login>
        </div>
      );
    }
  }
}

export default App;


Test:

npm start








Code on GitHub:















Friday, August 28, 2020

Encoding as Base64 in Kotlin

 I share three examples Encoding as Base64 in Kotlin.


Example 1: from path.

import org.apache.commons.codec.binary.Base64
import org.apache.commons.io.FileUtils
import java.io.File
import java.nio.charset.StandardCharsets

fun main(args: Array<String>) {
val file = File("PATH_YOUR_FILE")
val encoded: ByteArray = Base64.encodeBase64(FileUtils.readFileToByteArray(file))
println("*****************************start ****************")
println(String(encoded, StandardCharsets.US_ASCII))
println("*****************************end *****************")

}

Example 2:  from String

import org.apache.commons.codec.binary.Base64
import java.nio.charset.StandardCharsets

fun main(args: Array<String>) {
val encoded = Base64.encodeBase64("Test".toByteArray())
println("*****************************start ****************")
println(String(encoded, StandardCharsets.US_ASCII))
println("*****************************end *****************")
}

Example 3: from WS -> file: MultipartFile

import org.apache.commons.codec.binary.Base64
import org.springframework.web.multipart.MultipartFile
import java.nio.charset.StandardCharsets

fun encodeBase64(file: MultipartFile) {
val encoded: ByteArray = Base64.encodeBase64(file.bytes)
println("*****************************start ****************")
println(String(encoded, StandardCharsets.US_ASCII))
println("*****************************end *****************")
}


Wednesday, August 5, 2020

Start, enable, stop and disable firewalld on Centos


Start firewalld  service run nex commands:

systemctl unmask --now firewalld

systemctl enable firewalld

systemctl start firewalld

Stop firewalld  service run nex commands:

systemctl stop firewalld

sudo systemctl disable firewalld

sudo systemctl mask --now firewalld









References:
https://linuxize.com/post/how-to-stop-and-disable-firewalld-on-centos-7/
https://bobcares.com/blog/failed-to-start-firewalld-service-unit-is-masked/


Tuesday, August 4, 2020

Determine SSL cert expire date from the cert file (.p12)

1. Use openssl to extract the certificate from the .p12 file to a .pem file
openssl pkcs12 -in certificate.p12 -out certificate.pem -nodes

2.  You can extract the expiration date from the certifcate in the .pem file 
cat certificate.pem | openssl x509 -noout -enddate




References:https://stackoverflow.com/questions/28373771/how-to-determine-ssl-cert-expire-date-from-the-cert-file-itself-p12


Saturday, August 1, 2020

How to detect OS in kotlin

In kotlin also you can use System.getProperty("os.name") for detect type OS.

Check example class test.kt

fun main(args: Array<String>) {

val OS = System.getProperty("os.name").toLowerCase()

when {
OS.indexOf("win") >= 0 -> {
print("Windows")
}
OS.indexOf("mac") >= 0 -> {
print("Mac")
}
(OS.indexOf("nix") >= 0
|| OS.indexOf("nux") >= 0
|| OS.indexOf("aix") > 0) -> {
print("Unix or Linux")
}
OS.indexOf("sunos") >= 0 -> {
print("Solaris")
}
else -> print("Others")
}


}






References:
http://lopica.sourceforge.net/os.html
https://mkyong.com/java/how-to-detect-os-in-java-systemgetpropertyosname

How to execute shell command from Kotlin

In Kotlin, also we can use ProcessBuilder or Runtime.getRuntime().exec to execute external shell command :

ProcessBuilder

This class is used to create operating system processes. Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. The start() method can be invoked repeatedly from the same instance to create new subprocesses with identical or related attributes.

fun processBuilder() {
val processBuilder = ProcessBuilder()
// -- Linux --

// Run a shell command
//processBuilder.command("bash", "-c", "ls /home/your_user/")

// Run a shell script
//processBuilder.command("path/to/hello.sh");

// -- Windows --
// Run a command
processBuilder.command("cmd.exe", "/c", "dir C:/Users/your_user");

// Run a bat file
//processBuilder.command("C:/Users/your_user/file.bat");

try {

val process: Process = processBuilder.start()
val reader = BufferedReader(InputStreamReader(process.inputStream))
val line = reader.readText();
println(line)

val exitVal = process.waitFor()
if (exitVal == 0) {
println("Success!")
//exitProcess(0)
} else {
//else...
}
} catch (e: IOException) {
e.printStackTrace()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}

Runtime.getRuntime().exec()

Every Java application has a single instance of class Runtime that allows the application to interface with the environment in which the application is running. The current runtime can be obtained from the getRuntime method.

fun runtimeExec() {

try {
// -- Linux --

// Run a shell command
//val process = Runtime.getRuntime().exec("ls /home/your_user/")

// Run a shell script
//val process = Runtime.getRuntime().exec("path/to/hello.sh")

// -- Windows --

// Run a command
val process = Runtime.getRuntime().exec("cmd /c dir C:/Users/your_user")

//Run a bat file
//val process = Runtime.getRuntime().exec(
// "cmd /c hello.bat", null, File("C:/Users/your_user/"))

val reader = BufferedReader(
InputStreamReader(process.inputStream))

val line = reader.readText();
println(line)

val exitVal = process.waitFor()
if (exitVal == 0) {
println("Success!")
// exitProcess(0)
} else {
//else...
}

} catch (e: IOException) {
e.printStackTrace()
} catch (e: InterruptedException) {
e.printStackTrace()
}

}

Run & Test


hello.sh
#!/bin/sh
echo Hello World

fun main(args: Array<String>) {
val processBuilder = ProcessBuilder()

// -- Linux --
// Run a shell command
processBuilder.command("bash", "-c", "sh /home/hello.sh")

try {

val process: Process = processBuilder.start()
val reader = BufferedReader(InputStreamReader(process.inputStream))
val line = reader.readText();
println(line)

val exitVal = process.waitFor()
if (exitVal == 0) {
println("Success!")
//exitProcess(0)
} else {
//else...
}
} catch (e: IOException) {
e.printStackTrace()
} catch (e: InterruptedException) {
e.printStackTrace()
}

}

Output






















References:

https://mkyong.com/java/how-to-execute-shell-command-from-java/
https://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html
https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

🔐AWS → Google Cloud Workload Identity Federation with Terraform

  Eliminating Service Account Keys for Cross-Cloud Workloads Managing identities across cloud providers is often more challenging than manag...