Add user to group - change group ownership

 https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-lamp-amazon-linux-2.html

  1. Add your user (in this case, ec2-user) to the apache group.

    [ec2-user ~]$ sudo usermod -a -G apache ec2-user
  2. Log out and then log back in again to pick up the new group, and then verify your membership.

    1. Log out (use the exit command or close the terminal window):

      [ec2-user ~]$ exit
    2. To verify your membership in the apache group, reconnect to your instance, and then run the following command:

      [ec2-user ~]$ groups ec2-user adm wheel apache systemd-journal
  3. Change the group ownership of /var/www and its contents to the apache group.

    [ec2-user ~]$ sudo chown -R ec2-user:apache /var/www
  4. To add group write permissions and to set the group ID on future subdirectories, change the directory permissions of /var/www and its subdirectories.

    [ec2-user ~]$ sudo chmod 2775 /var/www && find /var/www -type d -exec sudo chmod 2775 {} \;
  5. To add group write permissions, recursively change the file permissions of /var/www and its subdirectories:

    [ec2-user ~]$ find /var/www -type f -exec sudo chmod 0664 {} \;

Now, ec2-user (and any future members of the apache group) can add, delete, and edit files in the Apache document root, enabling you to add content, such as a static website or a PHP application.

What is the www-data user?

 https://askubuntu.com/questions/873839/what-is-the-www-data-user

www-data is the user that web servers on Ubuntu (Apache, nginx, for example) use by default for normal operation. The web server process can access any file that www-data can access. It has no other importance.

From the base-passwd documentation (/usr/share/doc/base-passwd/users-and-groups.txt.gz):

Some web servers run as www-data. Web content should not be owned by this user, or a compromised web server would be able to rewrite a web site. Data written out by web servers will be owned by www-data.

Access first item of array using async pipe in Angular 2

 https://stackoverflow.com/questions/42614267/access-first-item-of-array-using-async-pipe-in-angular-2

Found an even easier way of doing it (without creating a custom pipe): add a map to the observable.

component.ts

this.activeTab$ = this.pageTabs$.map(x => x[0]);

component.html

<nav-tabs
   [tabs]="(pageTabs$ | async)"
   [activeTab]="(activeTab$ | async)">
</nav-tabs>

[CentOS 7 Apache]: Permission denied: file permissions deny server access

 https://techglimpse.com/apache-webserver-permission-denied-error/

[CentOS 7 Apache]: Permission denied: file permissions deny server access

Updated on March 15, 2022

Whenever I configure Apache on CentOS 7, most of the time I get “(13) Permission denied: file permissions deny server access” error as below:

[Fri Nov 12 06:29:24.901157 2021] [core:error] [pid 8287] (13)Permission denied: [client 192.168.10.12:15979] AH00132: file permissions deny server access: /var/www/html/admin/images/logo.png

How to fix file permissions deny server access in Apache

Step 1: Check for the below Apache configuration which will block access to all files and URLs.

<Directory />
     Order deny,allow
     Deny from all
 </Directory>

Instead, it should be like:

<Directory />
     Order allow,deny
     Allow from all
 </Directory>

Step 2: Check Read/Write Permissions of your website’s root folder and files required by Apache. To provide permissions for Apache to read/write to the files/folders, run the below command:

# chmod -R 755 /var/www/html
-R option in the above command

will recursively update the user permissions of all files & folders in your webite’s root location.

Step 3: Check for the website’s root folder/file ownership. The ownership should be of Apache(www-data or apache). First, find out the user used by Apache process on your system by the following command:

# egrep -iw --color=auto '^user|^group' /etc/httpd/conf/httpd.conf

or

# ps aux | egrep '([a|A]pache|[h|H]ttpd)' | awk '{ print $1}' | uniq | tail -1

Now change the ownership accordingly using the below command:

# chown -R www-data:root /var/www/html

or

# chown -R apache:root /var/www/html

Step 4: Check for SELinux (Security-Enhanced Linux). You may need to use chcon command to set the security context of your website’s root directory as below:

# chcon -R -h -t httpd_sys_content_t /var/www/html

How to Implement Push Notification with Nodejs and Service Worker

 https://blog.mensaiah.com/How-to-Implement-Push-Notification-with-Nodejs-and-Service-Worker-FkEm8H

Push notification has become an integral part of the web whether you are building a complex social media platform or you are building a simple blog, push notification just makes it easier to get messages across to users on the web easy.

We would be building a mini project to show how push notifications works on the server and client side

Content

So...

What are Push Notifications

Push Notifications are messages sent to a users device whether or not they are currently interacting with your website or application.

How It Works

For push notification to work over the web we need something called Service Workers

Service Worker is a script that works on browser background without user interaction independently.If you need more info on that Click Here

Prequisites

Basic Knowledge of

Let's Begin

We would be starting on the server side Create a folder for your project let's call our folder my-push-notifier and

Open your terminal and navigate to the folder created then run these commands

npm init -y

npm install express web-push

Create an app.js file

Appjs Setup

In the package.json file generated add this to the script object

"start": "node app.js",

Start your server with npm run start or node app.js your server should be running if everything was done correctly

Generating Vapid Keys

Vapid keys are needed before we can send push notifications. Why ?

Well two reasons

The first is to restrict the validity of a subscription to a specific application server (so, by using VAPID, only your server will be able to send notifications to a subscriber).

The second is to add more information to the push notification, so that the push service operator knows who is sending the notifications. If something is going wrong with your notifications, the operator knows who you are and can contact you. Moreover, they can offer you some kind of interface to monitor your push notifications.

Vapid keys can be generated online using

Vapid Keys Generator

OR

In your terminal run this command to install web-push

npm install web-push

Then generate your keys with this command

./node_modules/.bin/web-push generate-vapid-keys

Generated Vapid Keys

Copy the keys generated and save it somewhere.

In the app.js file set up the webpush with your keys

Set Up

Replace {YOUR_EMAIL} with your any email you want to set up with

Registering Push Notification

In our app.js file we would be creating an endpoint that allows users subscribe for push notification, Create a subscribers.json file, in file add an empty array [], The endpoint gets the subscriber's detail from the request body and saves it to a file

app.post("/subscribe", async (req, res) => {
    try {
        // Subscription Details From the client side , We would get back to this
        const subscription = req.body;
        subscribers.push(subscription);

        // Save the new subscrber to the subscribers file
        fs.writeFileSync("./subscribers.json", JSON.stringify(subscribers));

        res.status(201).send("Subscription Saved");
    } catch (error) {
        console.error(error);
    }
});

Subscribing To Push Notification

Now on the client side, create a client folder in our project folder and create the following files in the client folder

  1. index.html with the following code
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Push Notifications Using Node</title>
    </head>

    <body>
        <h1>Push Notifications Using Node</h1>
    </body>
    <script src="client.js"></script>
</html>
  1. client.js
  2. worker.js

Before we move forward add the following code to your app.js on the server side so html is rendered from the server

const path = require("path")
app.use(express.static(path.join(__dirname, 'client')))

Fist we would be creating a function in client.js that subscribes for push notification on our server for we would be using the browser window navigator


const publicVapidKey = "{VAPID_PUBLIC_KEY}";



async function subscribeToPush() {
    console.log("Registering service worker...");
    const register = await navigator.serviceWorker.register("/worker.js", {
        scope: "/"
    });
    console.log("Service Worker Registered...");

    console.log("Registering Push...");
    const subscription = await register.pushManager.subscribe({
        userVisibleOnly: true,
        applicationServerKey: urlBase64ToUint8Array(publicVapidKey)
    });
    console.log("Push Registered...");

    console.log("Subscribing for Push ...");
    await fetch("http://localhost:1999/subscribe", {
        method: "POST",
        body: JSON.stringify(subscription),
        headers: {
            "Content-Type":"application/json"
        }
    });
}



function urlBase64ToUint8Array(base64String) {
    const padding = "=".repeat((4 - base64String.length % 4) % 4);
    const base64 = (base64String + padding)
        .replace(/\-/g, "+")
        .replace(/_/g, "/");

    const rawData = window.atob(base64);
    const outputArray = new Uint8Array(rawData.length);

    for (let i = 0; i < rawData.length; ++i) {
        outputArray[i] = rawData.charCodeAt(i);
    }
    return outputArray;
}

Sending Push Notification

For the tutorial we would be sending notifications every minutes to our subscribers to do that we would create a function in our app.js on the server side

// Sending push notification to subscribers
const subscribers = require("./subscribers.json")
const fs = require("fs")
async  function sendPushNotificaiton() {
    for (let i = 0; i < subscribers.length; i++) {
        const subscription = subscribers[i];
        //Notification Payload, this could contain more information about the notification
        const payload = {
            title: "Push Test", 
            body: " Push Notification Message",
            icon: "https://blog.mensaiah.com/assets/round_logo.png",
        };

        //Pass object into sendNotification
        await webpush.sendNotification(subscription, JSON.stringify(payload));
    }

}

//Send Notification Every Minute
const durationInMillisecond  = 60 * 1000
setInterval(sendPushNotificaiton,durationInMillisecond);

Recieving and Displaying Push Notification

Remember our worker.js file created on the client side. We would be listen for a push notification so it can be displayed


self.addEventListener("push", e => {

    // Data from service
    const data = e.data.json();
    console.log("Push Recieved...");
    self.registration.showNotification(data.title, {
        body: data.body,
        icon: data.icon,
    });
});

You can find more information on displaying push notification here;

Run Application

In our client.js call the subscribeToPush function we created above, NB: Not all browsers support service workers so we would be doing this

// Only subscribe to push notification when browser supports service worker
if ('serviceWorker' in navigator) {
    subscribeToPush().catch(console.log);
}

On your browser (I recommend using chrome), visit http://localhost:1999/ to start recieving notification form the server. Click on allow when a prompt ask if you want to show notifications

Conclusion

This tutorial does not exhaust all possibilities of service workers, so I suggest reading and trying out more on the topic. Below are articles I recommend

error Building static HTML failed for path

https://stackoverflow.com/questions/66097033/error-building-static-html-failed-for-path-post-combiningmarriagewithlove-m 

I got the same error and the way I was able to fix it was by changing one of my style components to the proper react style

style={{maxWidth: "540px"}}

(before it was this:)

style="max-width: 540px;"

This wasn't picked up by my linter (ESLint) but if you don't have a linter installing one might help and it could highlight the problem

anti-pattern là gì

  Trong công nghệ và lập trình, Anti-pattern (mẫu phản diện) là những giải pháp bề ngoài có vẻ hiệu quả để giải quyết một vấn đề phổ biến, ...