<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Web-Application &#8211; Digitaldocblog</title>
	<atom:link href="https://digitaldocblog.com/tag/web-application/feed/" rel="self" type="application/rss+xml" />
	<link>https://digitaldocblog.com</link>
	<description>Various digital documentation</description>
	<lastBuildDate>Wed, 15 Feb 2023 06:30:35 +0000</lastBuildDate>
	<language>de</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9</generator>

<image>
	<url>https://digitaldocblog.com/wp-content/uploads/2022/08/cropped-website-icon-star-500-x-452-transparent-32x32.png</url>
	<title>Web-Application &#8211; Digitaldocblog</title>
	<link>https://digitaldocblog.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Node.js series Part 4. Express Website with authentication and authorization in a Mac Production Environment</title>
		<link>https://digitaldocblog.com/mac/nodejs-series-part-4-express-website-with-authentication-and-authorization-in-a-mac-production-environment/</link>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Thu, 18 Jun 2020 07:00:00 +0000</pubDate>
				<category><![CDATA[Mac OS]]></category>
		<category><![CDATA[Web-Development]]></category>
		<category><![CDATA[Webdesign]]></category>
		<category><![CDATA[Webserver]]></category>
		<category><![CDATA[Blog]]></category>
		<category><![CDATA[Blog-Application]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[Express.js]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Mongoose]]></category>
		<category><![CDATA[Node.js]]></category>
		<category><![CDATA[NPM Node package manager]]></category>
		<category><![CDATA[Role Based Access Control]]></category>
		<category><![CDATA[Web-Application]]></category>
		<guid isPermaLink="false">https://digitaldocblog.com/?p=117</guid>

					<description><![CDATA[In a real production environment the app runs as a service in the background and this service is managed by a process manager. And the app should run behind a&#8230;]]></description>
										<content:encoded><![CDATA[
<p>In a real production environment the app runs as a service in the background and this service is managed by a process manager. And the app should run behind a reverse proxy server. This reverse proxy server manage the TLS encryption, receives the requests from the client and route any request to the app running in the background. So the connection from the client to the reverse proxy server is TLS encrypted. Therefore the data transferred between client and the reverse proxy are secured. </p>



<p>How to setup such a <strong>production environment</strong> will be shown in the <strong>first chapter</strong> of this documentation. </p>



<p>The express app itself also contains some <strong>security features</strong>. The app contains a session based user authentication and HTTP headers which help to further secure the app. This is explained of the <strong>second chapter</strong> of this documentation.</p>



<p>Finally the express app should use the <strong>template engine PUG</strong> to render the HTML for us. This is describes of the <strong>third chapter</strong> of this documentation. </p>



<h3 class="wp-block-heading">1. Setup the production environment</h3>



<h4 class="wp-block-heading">Installation of mongodb</h4>



<p>The command <code>brew tap</code> without any arguments lists the GitHub repositories that are currently linked to your Homebrew installation. </p>



<pre class="wp-block-code"><code>Patricks-MBP:~ patrick$ brew tap
homebrew/cask
homebrew/core
homebrew/services
</code></pre>



<p>The formula mongodb has been removed from homebrew-core. But fortunately the MongoDB Team is maintaining a custom <a href="https://github.com/mongodb/homebrew-brew">Homebrew tap on GitHub</a>. Read the instructions in the README.md file. </p>



<p>Add the custom tap in the Mac OS terminal and install mongodb.</p>



<pre class="wp-block-code"><code>Patricks-MBP:~ patrick$ brew tap mongodb/brew

Patricks-MBP:~ patrick$ brew tap
homebrew/cask
homebrew/core
homebrew/services
mongodb/brew

Patricks-MBP:~ patrick$ brew install mongodb-community@4.2

</code></pre>



<p>After the installation the relevant paths are.</p>



<pre class="wp-block-code"><code>the configuration file (/usr/local/etc/mongod.conf)
the log directory path (/usr/local/var/log/mongodb)
the data directory path (/usr/local/var/mongodb)

</code></pre>



<p>Check the services with homebrew</p>



<pre class="wp-block-code"><code>brew services list

Name              Status  User    Plist
mongodb-community started patrick /Users/patrick/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist
  
</code></pre>



<p>Start and stop mongodb.</p>



<pre class="wp-block-code"><code>brew services start mongodb-community

brew services stop mongodb-community

</code></pre>



<h4 class="wp-block-heading">Setup mongodb for the project</h4>



<p>Setup an admin user</p>



<pre class="wp-block-code"><code>:# mongo

&gt; use admin
switched to db admin

&gt; db
admin

&gt; db.createUser({ user: "adminUser", pwd: "adminpassword", roles: &#91;{ role: "userAdminAnyDatabase", db: "admin" }, {"role" : "readWriteAnyDatabase", "db" : "admin"}] })

&gt; db.auth("adminUser", "adminpassword")
1

&gt; show users
{
    "_id" : "admin.adminUser",
    "userId" : UUID("5cbe2fc4-1e54-4c2d-89d1-317340429571"),
    "user" : "adminUser",
    "db" : "admin",
    "roles" : &#91;
        {
            "role" : "userAdminAnyDatabase",
            "db" : "admin"
        },
        {
            "role" : "readWriteAnyDatabase",
            "db" : "admin"
        }
    ],
    "mechanisms" : &#91;
        "SCRAM-SHA-1",
        "SCRAM-SHA-256"
    ]
}

&gt; exit

</code></pre>



<p>Enable authentication with <code>security: authorization: enabled</code></p>



<pre class="wp-block-code"><code>#&gt; nano /usr/local/etc/mongod.conf

systemLog:
  destination: file
  path: /usr/local/var/log/mongodb/mongo.log
  logAppend: true
storage:
  dbPath: /usr/local/var/mongodb
net:
  port: 27017
  bindIp: 127.0.0.1
security:
  authorization: enabled


</code></pre>



<p>Login and authenticate with admin</p>



<pre class="wp-block-code"><code>#&gt; mongo

MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("b3e7f48a-a05c-4894-87db-996cb34eb1fb") }
MongoDB server version: 4.2.3

&gt; show dbs
&gt; db
test
&gt; use admin
switched to db admin
&gt; db
admin
&gt; show dbs
&gt; db.auth("adminUser", "adminpassword")
1
&gt; show dbs
admin               0.000GB
config              0.000GB
local               0.000GB

&gt; 

</code></pre>



<p>If you login you dont see any databases when you call <code>show dbs</code>. The default database you are connected to is <code>test</code>. </p>



<p>Then you connect to admin database. For admin you setup the admin user with the roles <code>userAdminAnyDatabase</code> and <code>readWriteAnyDatabase</code>. With these permissions the admin user can manage users for any database and has read and write access to any database. </p>



<p>So wehen you logon to admin database with the admin user you are able to see all databases with <code>show dbs</code>. </p>



<p>Mongodb comes with 3 standard dbs pre installed:</p>



<ul class="wp-block-list"><li>admin </li><li>config</li><li>local<br></li></ul>



<p>Create a new database for our express-security app (authenticated as admin user &#8211; see above)</p>



<pre class="wp-block-code"><code>&gt; use express-security
switched to db express-security
&gt; db
express-security
&gt; show dbs
admin               0.000GB
config              0.000GB
local               0.000GB
&gt; 

</code></pre>



<p>The DB which you&#8217;ve created is not listed here. We need to insert at least one collection into it for displaying that database in the list. </p>



<pre class="wp-block-code"><code>&gt; db
express-security

&gt; db.createCollection("col_default")
{ "ok" : 1 }

&gt; show dbs
admin               0.000GB
config              0.000GB
express-security    0.000GB
local               0.000GB

&gt; exit

</code></pre>



<p>Create an owner user for express-security database using the admin user</p>



<pre class="wp-block-code"><code>#&gt; mongo

MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("79f79b63-9d08-489f-9e6c-bfc10d8cc09e") }
MongoDB server version: 4.2.3

&gt; db
test

&gt; show dbs

&gt; use admin
switched to db admin

&gt; db.auth("adminUser", "adminpassword")
1

&gt; db
admin

&gt; show dbs
admin               0.000GB
config              0.000GB
express-security    0.000GB
local               0.000GB

&gt; use express-security
switched to db express-security

&gt; db.createUser({ user: "owner_express-security", pwd: "passowrd", roles: &#91;{ role: "dbOwner", db: "express-security" }] })
Successfully added user: {
	"user" : "owner_express-security",
	"roles" : &#91;
		{
			"role" : "dbOwner",
			"db" : "express-security"
		}
	]
}

&gt; db
express-security

&gt; show users
{
	"_id" : "express-security.owner_express-security",
	"userId" : UUID("7a0bafb2-d2ed-4d18-9aba-e2f15a503ec5"),
	"user" : "owner_express-security",
	"db" : "express-security",
	"roles" : &#91;
		{
			"role" : "dbOwner",
			"db" : "express-security"
		}
	],
	"mechanisms" : &#91;
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}

&gt; exit 
</code></pre>



<p>Connection string to connect to express-security db using the owner_express-security user:</p>



<pre class="wp-block-code"><code>mongodb://owner_express-security:password@localhost/express-security
</code></pre>



<h4 class="wp-block-heading">Installation of PM2</h4>



<p>PM2 is a process manager for Node.js applications. It can daemonize applications to run them as a service in the background.</p>



<p>I install pm2 as a global npm package on my Mac.</p>



<pre class="wp-block-code"><code>Patricks-Macbook Pro:~ patrick$ npm install pm2 -g
</code></pre>



<p>Then navigate to your project directory.</p>



<pre class="wp-block-code"><code>Patricks-Macbook Pro:~ patrick$ cd Software/dev/node/articles/2020-05-15-express-security/express-security

Patricks-Macbook Pro:~ patrick$ ls -l 
total 112
drwxr-xr-x    5 patrick  staff    160 30 Mai 05:28 database
drwxr-xr-x  115 patrick  staff   3680 30 Mai 19:35 node_modules
-rw-r--r--    1 patrick  staff  34366 30 Mai 19:35 package-lock.json
-rw-r--r--    1 patrick  staff    339 30 Mai 19:35 package.json
-rw-r--r--@   1 patrick  staff  12343 30 Jun 05:00 secserver.js
drwxr-xr-x    3 patrick  staff     96 30 Mai 05:03 static

Patricks-Macbook Pro:express-security patrick$ 

</code></pre>



<p>Start your app using pm2</p>



<pre class="wp-block-code"><code>Patricks-Macbook Pro:express-security patrick$ pm2 start secserver.js

Patricks-Macbook Pro:~ patrick$ pm2 list
┌─────┬──────────────┬─────────────┬─────────┬─────────┬──────────┬────────┬──────┬───────────┬──────────┬──────────┬──────────┬──────────┐
│ id  │ name         │ namespace   │ version │ mode    │ pid      │ uptime │ ↺    │ status    │ cpu      │ mem      │ user     │ watching │
├─────┼──────────────┼─────────────┼─────────┼─────────┼──────────┼────────┼──────┼───────────┼──────────┼──────────┼──────────┼──────────┤
│ 0   │ secserver    │ default     │ 1.0.0   │ fork    │ 640      │ 16h    │ 0    │ online    │ 0%       │ 48.6mb   │ patrick  │ disabled │
└─────┴──────────────┴─────────────┴─────────┴─────────┴──────────┴────────┴──────┴───────────┴──────────┴──────────┴──────────┴──────────┘

Patricks-Macbook Pro:~ patrick$ 

</code></pre>



<p>Other comands to control the process manager. </p>



<pre class="wp-block-code"><code>pm2 start secserver.js

pm2 start &lt;id&gt;

pm2 list

pm2 stop &lt;id&gt;

pm2 restart &lt;id&gt;

pm2 show &lt;id&gt;

</code></pre>



<h4 class="wp-block-heading">Installation of nginx</h4>



<p><a href="https://nginx.org/en/">nginx</a> is an open source HTTP and an HTTP Reverse Proxy Server (also mail proxy and load balancer etc.). I install nginx on my Mac with Homebrew. </p>



<pre class="wp-block-code"><code>brew install nginx

</code></pre>



<p>You can list the brew services with the following command.</p>



<pre class="wp-block-code"><code>Patricks-MBP:digitaldocblog-V3 patrick$ brew services list

Name              Status  User    Plist
mongodb-community started patrick /Users/patrick/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist
nginx             started patrick /Users/patrick/Library/LaunchAgents/homebrew.mxcl.nginx.plist
Patricks-MBP:digitaldocblog-V3 patrick$
</code></pre>



<p>You can start and stop the brew services as follows.</p>



<pre class="wp-block-code"><code>brew install nginx

brew services start nginx

brew services stop nginx

</code></pre>



<h4 class="wp-block-heading">Setup nginx with TLS/SSL</h4>



<p>SSL/TLS works by using the combination of a public certificate and a private key. </p>



<p>The <strong>SSL key (private key)</strong> is kept secret on the server. It is used to encrypt content sent to clients. </p>



<p>The <strong>SSL certificate</strong> is publicly shared with anyone requesting the content. It can be used to decrypt the content signed by the associated SSL key.</p>



<p><strong>create private key</strong></p>



<pre class="wp-block-code"><code>Patricks-MBP:express-security patrick$ cd /usr/local/etc/nginx

Patricks-MBP:nginx patrick$ ls -l
total 144
-rw-r--r--  1 patrick  admin  1077  5 Apr 13:18 fastcgi.conf
-rw-r--r--  1 patrick  admin  1077  5 Apr 13:18 fastcgi.conf.default
-rw-r--r--  1 patrick  admin  1007  5 Apr 13:18 fastcgi_params
-rw-r--r--  1 patrick  admin  1007  5 Apr 13:18 fastcgi_params.default
-rw-r--r--  1 patrick  admin  2837  5 Apr 13:18 koi-utf
-rw-r--r--  1 patrick  admin  2223  5 Apr 13:18 koi-win
-rw-r--r--  1 patrick  admin  5231  5 Apr 13:18 mime.types
-rw-r--r--  1 patrick  admin  5231  5 Apr 13:18 mime.types.default
-rw-r--r--  1 patrick  admin  3106 15 Mai 05:19 nginx.conf
-rw-r--r--  1 patrick  admin  2680  5 Apr 13:18 nginx.conf.default
-rw-r--r--  1 patrick  admin  3091 21 Jan 05:40 nginx.conf.working
-rw-r--r--  1 patrick  admin   636  5 Apr 13:18 scgi_params
-rw-r--r--  1 patrick  admin   636  5 Apr 13:18 scgi_params.default
drwxr-xr-x  3 patrick  admin    96 21 Jan 06:02 servers
-rw-r--r--  1 patrick  admin   664  5 Apr 13:18 uwsgi_params
-rw-r--r--  1 patrick  admin   664  5 Apr 13:18 uwsgi_params.default
-rw-r--r--  1 patrick  admin  3610  5 Apr 13:18 win-utf

Patricks-MBP:nginx patrick$ mkdir ssl

Patricks-MBP:nginx patrick$ ls -l
total 152
-rw-r--r--  1 patrick  admin  1077  5 Apr 13:18 fastcgi.conf
-rw-r--r--  1 patrick  admin  1077  5 Apr 13:18 fastcgi.conf.default
-rw-r--r--  1 patrick  admin  1007  5 Apr 13:18 fastcgi_params
-rw-r--r--  1 patrick  admin  1007  5 Apr 13:18 fastcgi_params.default
-rw-r--r--  1 patrick  admin  2837  5 Apr 13:18 koi-utf
-rw-r--r--  1 patrick  admin  2223  5 Apr 13:18 koi-win
-rw-r--r--  1 patrick  admin  5231  5 Apr 13:18 mime.types
-rw-r--r--  1 patrick  admin  5231  5 Apr 13:18 mime.types.default
-rw-r--r--@ 1 patrick  admin   373 18 Mai 05:38 nginx.conf
-rw-r--r--  1 patrick  admin  2680  5 Apr 13:18 nginx.conf.default
-rw-r--r--  1 patrick  admin  3091 21 Jan 05:40 nginx.conf.working
-rw-r--r--@ 1 patrick  admin  1390 17 Mai 05:19 nginx_old.conf
-rw-r--r--  1 patrick  admin   636  5 Apr 13:18 scgi_params
-rw-r--r--  1 patrick  admin   636  5 Apr 13:18 scgi_params.default
drwxr-xr-x  5 patrick  admin   160 18 Mai 05:20 servers
drwxr-xr-x  4 patrick  admin   128 16 Mai 05:41 ssl
-rw-r--r--  1 patrick  admin   664  5 Apr 13:18 uwsgi_params
-rw-r--r--  1 patrick  admin   664  5 Apr 13:18 uwsgi_params.default
-rw-r--r--  1 patrick  admin  3610  5 Apr 13:18 win-utf

Patricks-MBP:nginx patrick$ cd ssl

Patricks-MBP:ssl patrick$ pwd
/usr/local/etc/nginx/ssl

Patricks-MBP:ssl patrick$ openssl genrsa -out privateKey.pem 4096

Patricks-MBP:ssl patrick$ ls -l
total 16
-rw-r--r--  1 patrick  admin  3247 16 Mai 05:22 privateKey.pem

</code></pre>



<p><strong>create certificate signing request (CSR)</strong></p>



<pre class="wp-block-code"><code>Patricks-MBP:ssl patrick$ pwd
/usr/local/etc/nginx/ssl

Patricks-MBP:ssl patrick$ openssl req -new -key privateKey.pem -out csr.pem

Patricks-MBP:ssl patrick$ ls -l
total 16
-rw-r--r--  1 patrick  admin  1740 16 Mai 05:23 csr.pem
-rw-r--r--  1 patrick  admin  3247 16 Mai 05:22 privateKey.pem

</code></pre>



<p>In case I would like to request an official certificate I must send this csr to the certificate authority. This authority would then create an <strong>authority signed certificate</strong> from the CSR and send it back to me.</p>



<p>This step is done by ourselves and this is the reason why we create a <strong>self signed certificate</strong>. This self signed certificate is not a official certificae and not trusted by any browser. It is not useful to use a self signed certificate in production because it produces error messages in the browsers. But for local development a self signed certificate is ok. </p>



<p>So create the self signed certificale. The csr file can then be removed. </p>



<p><strong>create the self signed certificate</strong></p>



<pre class="wp-block-code"><code>Patricks-MBP:ssl patrick$ pwd
/usr/local/etc/nginx/ssl

Patricks-MBP:ssl patrick$ openssl x509 -in csr.pem -out selfsignedcertificate.pem -req -signkey privateKey.pem -days 365

Patricks-MBP:ssl patrick$ ls -l
total 24
-rw-r--r--  1 patrick  admin  1740 16 Mai 05:23 csr.pem
-rw-r--r--  1 patrick  admin  3247 16 Mai 05:22 privateKey.pem
-rw-r--r--  1 patrick  admin  1980 16 Mai 05:39 selfsignedcertificate.pem

Patricks-MBP:ssl patrick$ rm csr.pem

Patricks-MBP:ssl patrick$ ls -l
total 24
-rw-r--r--  1 patrick  admin  3247 16 Mai 05:22 privateKey.pem
-rw-r--r--  1 patrick  admin  1980 16 Mai 05:39 selfsignedcertificate.pem
 
</code></pre>



<p><strong>show certificate details</strong></p>



<pre class="wp-block-code"><code>Patricks-MBP:ssl patrick$ pwd
/usr/local/etc/nginx/ssl

Patricks-MBP:ssl patrick$ openssl x509 -in selfsignedcertificate.pem -text -noout

</code></pre>



<h4 class="wp-block-heading">Configure nginx Servers with SSL</h4>



<p>In our configuration we enforce ssl. Therefore we create a <strong>default Webserver</strong> listening on Port 80 with the server name  <code>servtest.rottlaender.lan</code>. </p>



<p>Any request to <code>servtest.rottlaender.lan:80</code> is redirected to my <strong>Reverse Proxy Server</strong> which is listening on <code>servtest.rottlaender.lan:443</code>.<br></p>



<p>The <strong>default Webserver</strong> is configured in <code>/usr/local/etc/nginx/nginx.conf</code>.</p>



<pre class="wp-block-code"><code># /usr/local/etc/nginx/nginx.conf
# default Webserver

worker_processes  1;
error_log  /usr/local/etc/nginx/logs/error.log;

events {
    worker_connections  1024;
}

http {
    include       		mime.types;
    default_type  		application/octet-stream;
    sendfile        	on;
    keepalive_timeout  	65;

    access_log  /usr/local/etc/nginx/logs/access.log;

    # default Webserver redirect from port 80 to port 443 ssl
    
    server {
      	listen 80;
    	listen &#91;::]:80;
    	server_name servtest.rottlaender.lan;
    	return 301 https://$host$request_uri;
    }
    
    include servers/*;
    
}
</code></pre>



<p>The <strong>Reverse Proxy Server</strong> is configured in <code>/usr/local/etc/nginx/servers/reverse</code>.</p>



<pre class="wp-block-code"><code>// /usr/local/etc/nginx/servers/reverse
// reverse Proxy Server

server {

    listen      443 ssl;
    server_name servtest.rottlaender.lan;

    ssl_certificate      ssl/selfsignedcertificate.pem;
    ssl_certificate_key  ssl/privateKey.pem;
    ssl_session_cache    shared:SSL:1m;
    ssl_session_timeout  5m;
    ssl_ciphers  HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers  on;

    location / {
       proxy_pass http://localhost:3300;
       proxy_set_header X-Forwarded-For $remote_addr;
    }
}

</code></pre>



<p>The server name servtest.rottlaender.lan is linked in /private/etc/hosts to the ip 192.168.178.20 which is the ip of my computer in my local network.</p>



<pre class="wp-block-code"><code>Patricks-MBP:digitaldocblog-V3 patrick$ cat /private/etc/hosts
##
# 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
192.168.178.20 		servtest.rottlaender.lan
</code></pre>



<h3 class="wp-block-heading">2. Express Secure App (Security Features HTML version)</h3>



<p>This is a very simple application but show the basic security features you should use when you run a node app in a production environment. </p>



<p>The app is a website with a simple layout and navigation. </p>



<p>The Home page contain static information and can be accessed by everyone. </p>



<p>On the register page, users can find a form to register. The user data entered here are saved in the database and the user is logged in at the same time. Known users can log in with their email and password after successful registration on the login page. The login and register page can only be accessed if the user is not logged in. If a user is logged in and tries to access the login or register, he will be redirected to the dashboard page.</p>



<p>The dashboard is a personalized area of the website. This area can only be accessed if the user is logged in. If a user is not logged in, he will be redirected to the login page.</p>



<p>Logout is not really a page but a link that contains a logout function. Users who are logged in can log out using this link. Users who are not already logged in will be redirected to the login page.</p>



<h4 class="wp-block-heading">Download the code from GitHub</h4>



<p>Pls. <a href="https://github.com/prottlaender/node-part-4-express-security-with-db-html">go to my GitHub site</a> and clone the code. Here you find a some inline documentation in the code. The details are explained in this chapter. </p>



<h4 class="wp-block-heading">Create your app home directory express-security</h4>



<p>My app home directory is different to the one that is available after you cloned the code from GitHub. </p>



<pre class="wp-block-code"><code>Patricks-MBP:2020-05-15-express-security patrick$ pwd
/Users/patrick/software/dev/node/articles/2020-05-15-express-security

Patricks-MBP:2020-05-15-express-security patrick$ mv node-part-5-express-security-with-db-pug express-security

Patricks-MBP:2020-05-15-express-security patrick$ cd express-security

Patricks-MBP:express-security patrick$ pwd
/Users/patrick/software/dev/node/articles/2020-05-15-express-security/express-security
</code></pre>



<h4 class="wp-block-heading">Manage environment variables</h4>



<p>To manage environment variables for my app I use <code>envy</code>. First you need the files <code>.env</code> and <code>.env.example</code> in the root of your project directory. In <code>.env.example</code> you create a list of all potential environment variables without any values and in <code>.env</code> you use the defined variables and assign the values to them. </p>



<pre class="wp-block-code"><code>Patricks-MBP:express-security patrick$ ls -al
total 152
drwxr-xr-x   14 patrick  staff    448 23 Jun 05:29 .
drwxr-xr-x    4 patrick  staff    128 26 Mai 05:40 ..
-rw-------    1 patrick  staff    181 23 Jun 05:59 .env
-rw-r--r--    1 patrick  staff     53 23 Jun 05:59 .env.example
....

Patricks-MBP:express-security patrick$ cat .env.example
port=
mongodbpath=
sessionsecret=
sessioncookiename=

Patricks-MBP:express-security patrick$ cat .env
port=&lt;YOUR_PORT&gt;
mongodbpath=&lt;YOUR_CONNECTION_STRING&gt;
sessionsecret=&lt;YOUR_SESSION_SECRET&gt;
sessioncookiename=&lt;YOUR_SESSION_COOKIE_NAME&gt;

Patricks-MBP:express-security patrick$ 

</code></pre>



<p>Envy must be installed as dependency and required in the main application file <em>secserver.js</em>. Then you can set the environment variables as follows. </p>



<pre class="wp-block-code"><code>// secserver.js

....

// envy module to manage environment variables
const envy = require('envy');

// set the environment variables
const env = envy()
const port = env.port
const mongodbpath = env.mongodbpath
const sessionsecret = env.sessionsecret
const sessioncookiename = env.sessioncookiename
....
</code></pre>



<h4 class="wp-block-heading">Start the MongoDB Server</h4>



<p>To run the db server we install <code>mongoose</code> as dependency and require it in the db.js configuration file. The database connection will be initiated with <code>mongoose.connect</code> and the StartMongoServer function will be exported to be called in the main application file <em>secserver.js</em>.</p>



<pre class="wp-block-code"><code>const envy = require('envy')
const env = envy()

const mongodbpath = env.mongodbpath

const mongoose = require('mongoose');
mongoose.set('useNewUrlParser', true);
mongoose.set('useUnifiedTopology', true);

const StartMongoServer = async function() {
  try {

    await mongoose.connect(mongodbpath)
    .then(function() {
      console.log(`Mongoose connection open on ${mongodbpath}`);
    })
    .catch(function(error) {
      console.log(`Connection error message: ${error.message}`);
    })

  } catch(error) {
    res.json( { status: "db connection error", message: error.message } );
  }

};

module.exports = StartMongoServer;
</code></pre>



<h4 class="wp-block-heading">Authentication and authorization</h4>



<p>For user authentication we use the module <code>express-session</code> and to store session data in the session store in our database we use <code>connect-mongodb-session</code>. Therefore we install these modules as dependencies in our project and require the modules in our <em>secserver.js</em> main application file.</p>



<p>Then we create with <code>new MongoDBStore</code> a session storage in our MongoDB to store session data in collection <code>col_sessions</code>. errors are catched with <code>store.on</code>. </p>



<p>We use the session in our app with <code>app.use( session({...}) )</code>. With every request to our site a new session object is created with a unique session ID which include a session cookie object. The session object has keys options and the values for each key define how to deal with the session object. The session ID is created and signed using the <code>secret</code> option. We use <code>name</code> to provide a session cookie name and <code>store</code> to define where the session object should be stored (in case we store the session). </p>



<p>We can access the session object with <code>req.session</code> and the session ID with <code>req.session.id</code>. With every request we have a new session and this new session will be created but not stored anywhere so far. We say the session is <em>uninitialized</em>. The <code>saveUninitialized</code> false option ensure that a session will only be written to the store in case it has been modified. What does this mean?<br></p>



<p>We can modify the session when we store additional data into it. We always do this when the user is logging in via the <code>login</code> or the <code>register</code> route. When we post the data from the <em>login-</em> or from the <em>registration-form</em> to the server we call <em>loginUser</em> or the <em>createUser</em> module which is defined in <code>database/controllers/userC.js</code>. Both modules do basically the same thing: They create a userData Object and store the userData object into the session object and redirect the user to the dashboard when login or registration was successful. </p>



<pre class="wp-block-code"><code>....

var userData = { 
	userId: user._id, 
	name: user.name, 
	lastname: user.lastname, 
	email: user.email, 
	role: user.role 
	}

    req.session.userData = userData

    res.redirect('/dashboard')

....

</code></pre>



<p>If the user is successfully logged in the session is <em>initialized</em> (modified), the session object incl. the userData object are stored into the store and a cookie is stored into the requesting browser. The content of the cookie is only a hash of the session Id and with each request of a logged in user the session on the server is looked up. </p>



<p>The cookie in the browser will live max 1 week as we defined in the cookie object <code>maxAge</code> set to 1 week. Because of the cookie option <code>sameSite</code> true the cookie scope is limited to the same site. </p>



<p>Then the <code>resave</code> false option ensures that the session will not be updated with every request. This mean the session ID that has been created when the user has logged in will be kept until the user is logged out again.<br></p>



<pre class="wp-block-code"><code>// secserver.js

....

// server side session and cookie module
const session = require('express-session');
// mongodb session storage module
const connectMdbSession = require('connect-mongodb-session');

....

// Create MongoDB session storage
const MongoDBStore = connectMdbSession(session)
const store = new MongoDBStore({
  uri: mongodbpath,
  collection: 'col_sessions'
});

// catch errors in case store creation fails
store.on('error', function(error) {
  console.log(`error store session in session store: ${error.message}`);
});

// Create the express app
const app = express();

....

// use session to create session and session cookie
app.use(session({
  secret: sessionsecret,
  name: sessioncookiename,
  store: store,
  resave: false,
  saveUninitialized: false,
  // set cookie to 1 week maxAge
  cookie: {
    maxAge: 1000 * 60 * 60 * 24 * 7,
    sameSite: true
  },

}));

....
</code></pre>



<h4 class="wp-block-heading">Secure HTTP headers</h4>



<p>Response headers are HTTP header that come with the HTTP response from the server to the client. The http response header contain data that could possibly damage the integrity of the client. It is therefore important to secure the response header of your application.</p>



<p>To secure the http response headers I user the module <a href="https://helmetjs.github.io/">helmet</a>. This is a relatively easy-to-use module consisting of various middleware functionalities to secure various http response headers.</p>



<p>First we install <code>helmet</code>as a dependency of our project. Then we require helmet and use helmet right after we created the app. </p>



<pre class="wp-block-code"><code>// secserver.js

// hTTP module
const http = require('http');
// express module
const express = require('express');
// hTTP header security module
const helmet = require('helmet');

// Create the express app
const app = express();

....

// use secure HTTP headers using helmet
app.use(helmet())

</code></pre>



<p>Using simply <code>app.use(helmet())</code> set the http header security to default. Then the following 7 out 11 helmet features can be used.</p>



<ol class="wp-block-list"><li><a href="https://helmetjs.github.io/docs/dns-prefetch-control">dnsPrefetchControl</a> controls browser DNS prefetching</li><li><a href="https://helmetjs.github.io/docs/frameguard/">frameguard</a> to prevent clickjacking</li><li><a href="https://helmetjs.github.io/docs/hide-powered-by/">hidePoweredBy</a> to remove the X-Powered-By header</li><li><a href="https://helmetjs.github.io/docs/hsts/">hsts</a> for HTTP Strict Transport Security</li><li><a href="https://helmetjs.github.io/docs/ienoopen/">ieNoOpen</a> sets X-Download-Options for IE8+</li><li><a href="https://helmetjs.github.io/docs/dont-sniff-mimetype/">noSniff</a> to keep clients from sniffing the MIME type</li><li><a href="https://helmetjs.github.io/docs/xss-filter/">xssFilter</a> adds some small XSS protections<br></li></ol>



<p>When we then request our home page to retrieve the http headers using <code>curl -k --head</code> in the terminal we see the following output. </p>



<pre class="wp-block-code"><code>Patricks-MBP:express-security patrick$ curl -k --head https://servtest.rottlaender.lan
HTTP/1.1 200 OK
Server: nginx/1.19.0
Date: Fri, 26 Jun 2020 16:14:14 GMT
Content-Type: text/html; charset=utf-8
Content-Length: 1734
Connection: keep-alive
X-DNS-Prefetch-Control: off
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=15552000; includeSubDomains
X-Download-Options: noopen
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
ETag: W/"6c6-U2uWyDNyzlyBAbSI/Quxqo9RRQE"

Patricks-MBP:express-security patrick$ 
</code></pre>



<h4 class="wp-block-heading">App routing</h4>



<p><strong>get routes:</strong> We have the following <code>get</code> routes and navigation.</p>



<ul class="wp-block-list"><li>Home (/)</li><li>Login (/login)</li><li>Register (/register)</li><li>Dashboard (/dashboard)</li><li>Logout (/logout)<br></li></ul>



<p><code>get</code> routes involve an optional middleware and respond HTML back to the client. </p>



<pre class="wp-block-code"><code>app.get('/&lt;route&gt;', &lt;optional: someMiddleware&gt;, (req, res) =&gt; {
	
	res.send(`&lt;some HTML&gt;`)
})
</code></pre>



<p>I will not explain the HTML and css in detail. But as everyone can see, the HTML is the same for every route except for the <code>&lt;body&gt;</code>. Of course, this is not very nice and becomes a bit more efficient with the use of a template engine, which I will explain below using the <a href="https://pugjs.org/api/getting-started.html">PUG template engine</a>. I will then rebuild the app using PUG.</p>



<p>Lets have a look at the <code>middleware</code>. If a request is made for a route and a middleware function is included, the middleware function is first executed before the next routing function <code>function(req, res)</code> is called. A condition is built into the middleware function which is checked. My middleware is built so that in case the condition is true the middleware code is executed directly and the next routing function is omitted. If the condition is false, the next routing function <code>function(req, res)</code> is called.</p>



<p>I have built 2 different middleware functions which each check</p>



<p><strong>middleware 1 (login- and register route):</strong> a user is logged in</p>



<pre class="wp-block-code"><code>// secserver.js
....
// middleware 1 to redirect authenticated users to their dashboard
const redirectDashboard = (req, res, next) =&gt; {
  if (req.session.userData) {
    res.redirect('/dashboard')

  } else {
    next()
  }
}
....
</code></pre>



<p>If a user is logged in the request should be redirected to the dashboard route, in any other case (user is not logged in) the next routing function <code>function(req, res)</code> is called and respond the HTML to the browser. This middleware 1 is included in the <strong>/login-</strong> and <strong>/register</strong> route. This mean logged in users will be redirected to their dashboard, not logged in users will see the login- and register form. </p>



<p><strong>middleware 2 (dashboard- and logout route):</strong> a user is not logged in.</p>



<pre class="wp-block-code"><code>// secserver.js
....

// middleware 2 to redirect not authenticated users to login
const redirectLogin = (req, res, next) =&gt; {
  if (!req.session.userData) {
    res.redirect('/login')
  } else {
    next()
  }
}
....
</code></pre>



<p>If a user is not logged in the request should be redirected to the login roure, in any other case (user is logged in) the next routing function <code>function(req, res)</code> is called and respond the HTML to the browser. This middleware 2 is included in the <strong>/dashboard-</strong> and <strong>/logout</strong> route. This mean not logged in users will be redirected to login route, logged in users will see the dashboard- or can log themselves out. </p>



<p><strong>post routes:</strong> We have the following <code>post</code> routes.</p>



<ul class="wp-block-list"><li>/login</li><li>/register<br></li></ul>



<p>The login and the register <code>get</code> routes contain a form in the HTML. With these forms the user provide the data to login and for user registration. When the user click the send button the <em>action</em> is to call the login- or register <code>post</code> route. This will happen for all not logged in users. The login and the register <code>get</code> routes have the middleware <code>redirectDashboard</code>to redirect the user to the dashbard if the user is already logged in.<br></p>



<pre class="wp-block-code"><code>// secserver.js
....

app.get('/login', redirectDashboard, (req, res) =&gt; {
....
res.send(`
....
&lt;div class="form"&gt;
	&lt;form id='register_form' method='post' action='/register'&gt;
	......
	&lt;label for='send'&gt;
   		&lt;input class='sendbutton' type='submit' name='send' value='Send'&gt;
	&lt;/label&gt;
	&lt;/form&gt;
&lt;/div&gt;

`)
)}
....

app.get('/register', redirectDashboard, (req, res) =&gt; {
....
res.send(`
....
&lt;div class="form"&gt;
	&lt;form id='login_form' method='post' action='/login'&gt;
	......
	&lt;label for='send'&gt;
   		&lt;input class='sendbutton' type='submit' name='send' value='Send'&gt;
	&lt;/label&gt;
	&lt;/form&gt;
&lt;/div&gt;
`)
)}
.....
</code></pre>



<p>The <code>post</code> routes contain functions to login- (loginUser) or register (createUser) the user.<br></p>



<pre class="wp-block-code"><code>// secserver.js
....
// Post routes to manage user login and user registration
app.post('/login', userController.loginUser);

app.post('/register', userController.createUser);
....
</code></pre>



<p>The <code>loginUser</code> function is defined in the user controller <code>database/controllers/userC.js</code>. This function lookup a user in the database based on the email address that has been provided by the request body. The data that are attached to the request body have been provided by the user vie the login form of the app. If no user could be found in the database login is not possible. If a user exist with the given email address then the provided password will be compared with the one stored in the database. If the password match fail login is not possible because the provided password is wrong. in any other case, the login takes place and a userData object is created and attached to the session object.</p>



<pre class="wp-block-code"><code>// database/controllers/userC.js

User.findOne({ email: req.body.email }, function(error, user) {
  if (!user) {
    res.status(400).send({ code: 400, status: 'Bad Request', message: 'No User found with this email' })

    } else {
      if (bcrypt.compareSync(req.body.password, user.password)) {
    
        var userData = { userId: user._id, name: user.name, lastname: user.lastname, email: user.email, role: user.role }

          req.session.userData = userData

          res.redirect('/dashboard')

        } else {
          res.status(400).send({ code: 400, status: 'Bad Request', message: 'Wrong User password' })
        }

      }
    })

  }
</code></pre>



<p>The <code>createUser</code> function is also defined in the user controller <code>database/controllers/userC.js</code>. This function create a new User object based on the data from the request body provided by the user via the form. The provided password will be hashed and stored together with all other data into the database. Finally a userData object is created and attached to the session and the user will be redirected to the dashboard after the registration was successful.<br></p>



<pre class="wp-block-code"><code>// database/controllers/userC.js

createUser: async function (req, res) {
    // assign input data from request body to input variables
    const name = req.body.name
    const lastname = req.body.lastname
    const email = req.body.email
    const password = req.body.password
    const role = req.body.role

    const newUser = new User({
      name: name,
      lastname: lastname,
      email: email,
      password: password,
      role: role
    })

    newUser.password = await bcrypt.hash(newUser.password, saltRounds)

    await newUser.save(function(err, user) {
          if (err) {
            // if a validation err occur end request and send response
            res.status(400).send({ code: 400, status: 'Bad Request', message: err.message })
          } else {
            // req.session.userId = user._id

            var userData = { userId: user._id, name: user.name, lastname: user.lastname, email: user.email, role: user.role }

            req.session.userData = userData

            res.redirect('/dashboard')
          }
        })
  },
</code></pre>



<p>And we have a default <code>get</code> route.</p>



<ul class="wp-block-list"><li>/favicon.ico<br></li></ul>



<p>Browsers will by default try to request /favicon.ico from the root of a hostname, in order to show an icon in the browser tab. As we dont use favicon so far we must avoid that these requests returning a 404 (Not Found). Here The /favicon.ico request will be catched and send a 204 No Content status.</p>



<pre class="wp-block-code"><code>// secserver.js
....
app.get('/favicon.ico', function(req, res) {
    console.log(req.url);
    res.status(204).json({status: 'no favicon'});
});
....
</code></pre>



<h3 class="wp-block-heading">3. Express App (Pug Template Version)</h3>



<p>From a functional point of view this app is pretty much the same app then the HTML version. The difference is that we use PUG templates instead of HTML in each res.send().</p>



<h4 class="wp-block-heading">Setup a seperate Database</h4>



<p>For the PUG version of my app I set up a new database to manage the users and the sessions.</p>



<pre class="wp-block-code"><code>#&gt; mongo

MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("b3e7f48a-a05c-4894-87db-996cb34eb1fb") }
MongoDB server version: 4.2.3

&gt; db
test

&gt; use admin
switched to db admin

&gt; db
admin

&gt; db.auth("adminUser", "adminpassword")
1

&gt; show dbs
admin               0.000GB
config              0.000GB
express-security    0.000GB
local               0.000GB

&gt; use express-security-pug
switched to db express-security-pug

&gt; db.createUser({ user: "owner_express-security-pug", pwd: "passowrd", roles: &#91;{ role: "dbOwner", db: "express-security-pug" }] })

Successfully added user: {
    "user" : "owner_express-security-pug",
    "roles" : &#91;
        {
            "role" : "dbOwner",
            "db" : "express-security-pug"
        }
    ]
}

&gt; db
express-security-pug

&gt; exit
</code></pre>



<p>Connection string to connect to express-security-pug db using the owner_express-security-pug user.</p>



<pre class="wp-block-code"><code>mongodb://owner_express-security-pug:password@localhost/express-security-pug
</code></pre>



<h4 class="wp-block-heading">Download the code from GitHub</h4>



<p>Pls. <a href="https://github.com/prottlaender/node-part-5-express-security-with-db-pug">go to my GitHub site</a> and clone the code. Here you find some inline documentation in the code.</p>



<h4 class="wp-block-heading">Create your app home directory express-security-pug</h4>



<p>My app home directory is different to the one that is available after you cloned the code from GitHub. </p>



<pre class="wp-block-code"><code>Patricks-MBP:2020-05-15-express-security patrick$ pwd
/Users/patrick/software/dev/node/articles/2020-05-15-express-security

Patricks-MBP:2020-05-15-express-security patrick$ mv node-part-5-express-security-with-db-pug express-security-pug

Patricks-MBP:2020-05-15-express-security patrick$ cd express-security-pug

Patricks-MBP:express-security-pug patrick$ pwd
/Users/patrick/software/dev/node/articles/2020-05-15-express-security/express-security-pug
</code></pre>



<h4 class="wp-block-heading">Install PUG and use it in your app</h4>



<p>First we install <a href="https://pugjs.org/api/getting-started.html">PUG</a> as a dependency. </p>



<pre class="wp-block-code"><code>Patricks-MBP:express-security-pug patrick$ pwd
/Users/patrick/software/dev/node/articles/2020-05-15-express-security/express-security-pug

Patricks-MBP:express-security-pug patrick$ npm install pug --save
</code></pre>



<p><a href="https://pugjs.org/api/getting-started.html">PUG</a> is already <a href="https://pugjs.org/api/express.html">fully integrated</a> into Express. Pls. read the documentation <a href="https://expressjs.com/en/guide/using-template-engines.html">how to use template engines in Express</a>. </p>



<p>After you installed PUG the view engine must be set in your main application file <em>secserverpug.js</em>.</p>



<pre class="wp-block-code"><code>// secserverpug.js
....
// use Pug Template Engine
app.set('view engine', 'pug')
app.set('views', './views')
....
</code></pre>



<p>These instructions tell your app that PUG template engine is used and that the templates can be found in <code>/views</code> directory.</p>



<h4 class="wp-block-heading">PUG Directory setup</h4>



<p>In <code>/views</code> I setup the templates for home, login, registration and an error template. </p>



<p>In <code>/views/includes</code> I setup the files containing HTML or JavaScript. These can be included in the templates. </p>



<pre class="wp-block-code"><code>Patricks-MBP:express-security-pug patrick$ ls -l
total 128
-rw-r--r--    1 patrick  staff    771  1 Jul 06:04 README.md
drwxr-xr-x    5 patrick  staff    160 29 Jun 05:26 database
drwxr-xr-x  150 patrick  staff   4800 29 Jun 06:11 node_modules
-rw-r--r--    1 patrick  staff  47547 29 Jun 06:11 package-lock.json
-rw-r--r--    1 patrick  staff    367 29 Jun 06:11 package.json
-rw-r--r--    1 patrick  staff   4393  2 Jul 05:34 secserverpug.js
drwxr-xr-x    3 patrick  staff     96 29 Jun 05:26 static
drwxr-xr-x    8 patrick  staff    256  2 Jul 05:45 views

Patricks-MBP:express-security-pug patrick$ ls -l views
total 40
-rw-r--r--  1 patrick  staff   549 30 Jun 05:35 dashboard.pug
-rw-r--r--  1 patrick  staff   522  2 Jul 05:50 err.pug
-rw-r--r--  1 patrick  staff   420 29 Jun 05:39 home.pug
drwxr-xr-x  6 patrick  staff   192 29 Jun 05:17 includes
-rw-r--r--  1 patrick  staff   735 30 Jun 05:02 login.pug
-rw-r--r--  1 patrick  staff  1067 30 Jun 05:08 register.pug

Patricks-MBP:express-security-pug patrick$ ls -l views/includes
total 32
-rw-r--r--  1 patrick  staff   76 29 Jun 05:39 foot.pug
-rw-r--r--  1 patrick  staff  167 29 Jun 05:24 head.pug
-rw-r--r--  1 patrick  staff  489  2 Jul 05:13 nav.pug
-rw-r--r--  1 patrick  staff  420 29 Jun 05:08 script.js

Patricks-MBP:express-security-pug patrick$ 
</code></pre>



<h4 class="wp-block-heading">The responsive Website Design</h4>



<p>Each site like <em>home</em>, <em>login</em>, <em>register</em> and <em>dashboard</em> has a <strong>specific site template</strong> in <code>/views</code> directory. The site content will be defined in the <em>main section</em> of each template. PUG enables files with HTML or JavaScript to be included. This makes the <em>site templates</em> clear and easy to maintain. The <strong>includes</strong> are located in <code>/views/includes</code> directory.</p>



<p>The website is build based on a grid design and each site template has the following structure.</p>



<pre class="wp-block-code"><code>doctype html

HTML

	Head
		include includes/head.pug	
	
	Body
		
		Grid-Container
			
				Header
					include includes/nav.pug
			
				Main
					... site template specific HTML ...
			
				Footer
					include includes/foot.pug
					
		&lt;script&gt;
			  include includes/script.js

</code></pre>



<p>The design of the website is defined in the css in <code>static/css/style.css</code>.</p>



<p>Here in the css we define the <strong>Site Structure</strong> as <em>grid areas</em> consisting of header, main and footer and link them to the <em>grid-container</em>. </p>



<pre class="wp-block-code"><code>....

.header { grid-area: header; background-color: #ffffff; border-radius: 5px;}
.main { grid-area: main; background-color: #ffffff; border-radius: 5px;}
.footer { grid-area: footer; background-color: #ffffff; border-radius: 5px;}

.grid-container {
  display: grid;
  grid-template-areas:
      "header"
      "main"
      "footer";
  grid-gap: 5px;
  background-color: #d1d1e0;
  padding: 50px;
}

....
</code></pre>



<p>The <strong>Navigation</strong> is defined in the Header area of the Grid-Container and the HTML comes into the template via <code>include includes/nav.pug</code>.</p>



<pre class="wp-block-code"><code>// includes/nav.pug

//(this) refers to the DOM element to which the onclick attribute belongs to
// the a DOM element will be given as parameter to the function

a(class="burgericon" onclick="myFunction(this)")
  div(class='burgerline' id='bar1')
  div(class='burgerline' id='bar2')
  div(class='burgerline' id='bar3')

a(class='link' href='/') Home
a(class='link' href='/login') Login
a(class='link' href='/register') Register
a(class='link' href='/dashboard') Dashboard
a(class='link' href='/logout') Logout
</code></pre>



<p>So the navigation design is then defined in the css. Each navigation object is an <code>a</code> link. We have <code>a</code> links with class <code>link</code> and <code>burgericon</code>. The burgericon is used to open the navigation bar onclick when the screen is smaller than 600px (like iphone displays etc., explained below), is cosisting of 3 burgerlines and these lines are created using 3 div objects with class <code>burgerline</code>. The burgelines will be transformed with speed 0.4s when you click on the burgericon (explained below). The burgericon is not visible and aligned on the right edge. All other navigation links are visible and aligned on the left edge.<br></p>



<pre class="wp-block-code"><code>/* static/css/style.css */
....

/* style the navigation links with float on the left (side by side) */
.header a.link {
  float: left;
  display: block;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 1.4vw;
  color: #28283e;
}

/* hover effect for each navigation link */
.header a.link:hover {
  background-color: #28283e;
  color: #ffffff;
}

/* style the burgericon link on the right */
.header a.burgericon {
  float: right;
  display: none;
  padding: 14px 16px;
}

/* style each burgerline that create the burgericon */
.burgerline {
  width: 35px;
  height: 5px;
  background-color: #28283e;
  margin: 6px 0;
  transition: 0.4s;
}
....
</code></pre>



<p>When the display screen is lower than 600px the navigation links will not be shown and the burgericon (on the right side) will be faded in instead. </p>



<pre class="wp-block-code"><code>/* static/css/style.css */
....
/* for screens up to 600px remove the navigation links and show the burgericon instead */
@media screen and (max-width: 600px) {
  .header a.link { display: none; }
  .header a.burgericon { display: block; }
}
....
</code></pre>



<p>When you click on the burgericon the burgerlines will be transformed so that you will see a cross instead of the hamburger like icon. The 2nd burgerline with <code>id='bar2'</code> will not be shown at all while the other 2 burgelines will be rotated 45 degrees counterclockwise (burgerline with <code>id='bar1'</code>) and clockwise (burgerline with <code>id='bar1'</code>). </p>



<pre class="wp-block-code"><code>/* static/css/style.css */
....
/* style burgerlines after on onclick event */
/* the .change class will be added onclick with classList.toggle in the JavaScript */
/* rotate first bar */
.change #bar1 {
  /* rotate -45 degrees (counterclockwise) move 15px down in Y-direction */
  transform: rotate(-45deg) translateY(15px);
}
/* fade out the second bar */
.change #bar2 {
  opacity: 0;
}
/* rotate third bar */
.change #bar3 {
  /* rotate +45 degrees (clockwise) move 15px up in Y-direction */
  transform: rotate(45deg) translateY(-15px);
}
....
</code></pre>



<p>After clicking on the burgericon, the burgerlines are transformed as described. The links of the navigation menu are displayed one below the other (float none) and aligned left.</p>



<pre class="wp-block-code"><code>/* static/css/style.css */
....
/* for screens up to 600px and after onclick event the responsive class will be added to the header */
@media screen and (max-width: 600px) {
  /* show navigation links left with no float (links shown among themselves) */
  .header.responsive a.link {
    float: none;
    display: block;
    text-align: left;
  }
}
....
</code></pre>



<p>All onclick functionalities are controlled by the javascript which is embedded in the HTML of each site template (pls see above includes/nav.pug). In the HTML, the onclick event is initiated in the burgericon link and the function myFunction is called with <code>onclick =" myFunction(this) "</code>. With the parameter <em>this</em> the entire burgericon object is transferred to the javascript function.</p>



<p>With each click on the burger icon, the class <code>change</code> is added to each burgerline or, if available, removed. This is done by the toggle() function. If <code>change</code> is set, the hamburg icon is transformed into a cross according to the specification in the css (see above). If <code>change</code> is withdrawn with a new click, the hamburger icon is displayed again.</p>



<p>But it happens even more in the javascript when you click on the hamburger icon. The element that has the id <code>responsivenav</code> is searched for and the variable<code>reponsiveNavElement</code> is assigned to this element. Is the class of the reponsiveNavElement <code>header</code> the class<code>responsive</code> is added after clicking on the hamburger icon. If the class <code>responsive</code> is set, as described above, the links of the navigation menu are displayed one below the other (float none) and aligned left. So it applies in the css <code>.header.responsive a.link {....}</code></p>



<p>In all other cases only the class <code>header</code> is set. So it applies in the css <code>.header a.link {....}</code> and the navigation links are not shown. </p>



<pre class="wp-block-code"><code>// includes/script.js

// the (burgerlines) parameter represent the DOM element that has been given to the function
function myFunction(burgerlines) {
  burgerlines.classList.toggle('change');

  var reponsiveNavElement = document.getElementById('responsivenav');
    if (reponsiveNavElement.className === 'header') {
      reponsiveNavElement.classList.add('responsive')
    } else {
      reponsiveNavElement.className = 'header';
    }
  }

</code></pre>



<p>Finally at the end of the css we define the defaults for <em>h1</em>, for our text content, the forms, the input fields and the send buttons.<br></p>



<h3 class="wp-block-heading">Summary and Outlook</h3>



<p>In this part 4 of my little node.js series we have seen how to setup a production ready environment for our express app. I showed this using a Mac OS, but in principle this setup also applies to Linux, for example.</p>



<p>The basic setup is, to put it simply, the app runs as a service on the server in the background using a Process Manager, but has no interface to the client. This client interface regulates a reverse proxy which is upstream of the app and accepts all requests and forwards them to the app, as well as the responses from the app back to the client. The communication is SSL/TLS secured.</p>



<p>At the center of the setup is a separate local MongoDB that manages all application data. In our example, these are the users, but also the sessions. I prefer to set up my own MongoDB on my server but of course it is conceivable to use a cloud-based solution or to install another database locally.</p>



<p>The express app itself uses secure HTTP response headers so that HTTP attacks like <em>clickjacking</em>, <em>MIME type sniffing</em> or some <em>smaller XSS attacks</em> on the client are made as difficult as possible. Access to personal areas of the application is secured by session-based authentication and authorization. The session-relevant data is stored in the database and not in the browser cookie, which means additional security with regard to attacks on the client. The browser cookie only contains a hash of the session ID to query the relevant user data from the database.</p>



<p>I would like to end my node.js series with Part 4. I discussed and demonstrated the basic concepts and procedures in parts 1 to 4. Of course there will be other interesting articles on the topic node.js and web programming on <a href="https://digitaldocblog.com">Digitaldocblog</a>. Just take a look.</p>
]]></content:encoded>
					
		
		
			</item>
		<item>
		<title>Node.js series Part 3. The Simple Express Blog App with MongoDB</title>
		<link>https://digitaldocblog.com/webserver/nodejs-series-part-3-the-simple-express-blog-app-with-mongodb/</link>
		
		<dc:creator><![CDATA[admin]]></dc:creator>
		<pubDate>Wed, 08 Apr 2020 07:00:00 +0000</pubDate>
				<category><![CDATA[Web-Development]]></category>
		<category><![CDATA[Webserver]]></category>
		<category><![CDATA[Blog-Application]]></category>
		<category><![CDATA[Express.js]]></category>
		<category><![CDATA[MongoDB]]></category>
		<category><![CDATA[Mongoose]]></category>
		<category><![CDATA[NPM Node package manager]]></category>
		<category><![CDATA[Web-Application]]></category>
		<guid isPermaLink="false">https://digitaldocblog.com/?p=114</guid>

					<description><![CDATA[In this Part 3 of my node.js series I rebuild the simple blog app from the last Part 2 so that a MongoDB database is used instead of a simple&#8230;]]></description>
										<content:encoded><![CDATA[
<p>In this Part 3 of my node.js series I rebuild the simple blog app from the last <a href="https://digitaldocblog.com/webserver/nodejs-series-part-2-create-a-simple-blog-app-with-expressjs/" title="Part 2">Part 2 </a>so that a <a href="https://www.mongodb.com/">MongoDB</a> database is used instead of a simple data file. To do this, a MongoDB must first be installed locally on the development system. We also use <a href="https://mongoosejs.com/">Mongoose</a> to access the database in our express blog application. I have described in detail on <a href="https://digitaldocblog.com/singleblog?article=4">Digitaldocblog</a> how to install MongoDB in my blog post <a href="https://digitaldocblog.com/singleblog?article=4">Mongodb and Mongoose on Ubuntu Linux</a>.</p>




<p>The creation of the database and the cloning of the application root directory from my <a href="https://github.com/prottlaender/node-part-3-express-blog-with-db-V2">GitHub page</a> will be briefly described in the following step-by-step instructions. This is followed by a description of the application functionality. Then I will explain more generally how data is modeled in a database-based Expressjs application with the help of mongoose and how the data is accessed so that the more basic software architecture is understood. The relevant code of our blog app is commented. In this respect, the explanations of the individual code passages can be found in the inline documentation.</p>




<h3 class="wp-block-heading">Create a MongoDB Database</h3>



<p>After the installation of MongoDB you have started the <em>mongod</em> service on your system. It is very important that you setup MongoDB with client authentication enabled. You have also created an admin user with a password on your admin default db. Pls. follow the description in my article <a href="https://digitaldocblog.com/singleblog?article=4">Mongodb and Mongoose on Ubuntu Linux</a>.</p>




<p>Then you create a database for your project and a user for your database using the <em>mongo</em> command on the console.</p>




<pre class="wp-block-code"><code>Patricks-MBP:digitaldocblog-V3 patrick$ mongo

MongoDB shell version v4.2.3
connecting to: mongodb://127.0.0.1:27017/?compressors=disabled&amp;gssapiServiceName=mongodb
Implicit session: session { "id" : UUID("4e8c592e-104d-48ef-b495-62129e446d23") }
MongoDB server version: 4.2.3

&gt; db
test

&gt; show dbs

&gt; use admin
switched to db admin

&gt; db.auth("admin", "YOUR-ADMIN-PASSWD")
1

&gt; show dbs
admin               0.000GB
config              0.000GB
local               0.000GB

&gt; use YOUR-DB-NAME
switched to db YOUR-DB-NAME

&gt; db
YOUR-DB-NAME

&gt; db.createCollection("col_default")
{ "ok" : 1 }

&gt; show dbs
admin               0.000GB
config              0.000GB
local               0.000GB
YOUR-DB-NAME	    0.000GB

&gt; db.createUser({ user: "YOUR-DB-USER", pwd: "YOUR-DB-USER-PASSWD", roles: [{ role: "dbOwner", db: "YOUR-DB-NAME" }] })
Successfully added user: {
	"user" : "YOUR-DB-USER",
	"roles" : [
		{
			"role" : "dbOwner",
			"db" : "YOUR-DB-NAME"
		}
	]
}

&gt; show users
{
	"_id" : "YOUR-DB-NAME.YOUR-DB-USER",
	"userId" : UUID("ef080b98-849f-41f4-b561-a658a88e4595"),
	"user" : "YOUR-DB-USER",
	"db" : "YOUR-DB-NAME",
	"roles" : [
		{
			"role" : "dbOwner",
			"db" : "YOUR-DB-NAME"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}

&gt; show dbs
admin               0.000GB
config              0.000GB
local               0.000GB
YOUR-DB-NAME	    0.000GB
&gt; 

&gt; exit
bye

</code></pre>



<p>If you enter the command <em>mongo</em> on the console, the MongoDB client connects to the MongoDB service. The MongoDB client is the so-called MongoDB shell with which the user can work on the console. After the connection is established, the MongoDB shell is displayed in the terminal and with the command <em>db</em> we see the output <em>test</em>. </p>




<p>The <em>db</em> command shows the database you are currently connected to. test is the default database and is actually no longer used. The <em>show dbs</em> command shows all available databases. Since we have activated client authentication nothing is shown here because we are not yet authenticated.</p>




<p>With <em>use admin</em> we switch to admin db and authenticate ourselves with <em>db.auth</em>. After we have entered the <em>db.auth</em> command in the MongoDB shell as described, the shell shows us a 1. This shows that the authentication was successful. As admin user we can now show all databases with <em>show dbs</em>.</p>




<p>With the command <em>use YOUR-DB-NAME</em> we create the database YOUR-DB-NAME and also switch from the database admin to the database YOUR-DB-NAME. With the command <em>db.createCollection</em> I always create a default collection in YOUR-DB-NAME to display the new database YOUR-DB-NAME with the <em>show dbs</em> command in the MongoDB shell. If you simply create the database and no collection the new database is not shown with the <em>show dbs</em> command. </p>




<p>Then I create a user with <em>db.createUser</em> for my new database YOUR-DB-NAME, assign the role <em>dbOwner</em> to this user and the password <em>YOUR-DB-USER-PASSWD</em>.</p>




<p>The database YOUR-DB-NAME is now created and with <em>exit</em> we leave the MongoDB shell.</p>




<h3 class="wp-block-heading">Create the application root directory</h3>



<p>Clone the Simple Blog App from my <a href="https://github.com/prottlaender/node-part-3-express-blog-with-db-V2">GitHub page</a> and then switch to the directory <em>node-part-3-express-blog-with-db-V2</em>.</p>




<pre class="wp-block-code"><code>Patricks-MBP:~ patrick$ cd node-part-3-express-blog-with-db-V2

</code></pre>



<p>The application root directory then looks like this.</p>




<pre class="wp-block-code"><code>Patricks-MBP:node-part-3-express-blog-with-db-V2 patrick$ ls -l
total 72
-rw-r--r--   1 patrick  staff    768 9 Apr 05:19 README.md
-rw-r--r--   1 patrick  staff   2162 9 Apr 05:19 blog.js
drwxr-xr-x   6 patrick  staff    192 9 Apr 05:19 database
drwxr-xr-x   3 patrick  staff     96 9 Apr 05:19 modules
drwxr-xr-x  77 patrick  staff   2464 9 Apr 05:19 node_modules
-rw-r--r--   1 patrick  staff  22302 9 Apr 05:19 package-lock.json
-rw-r--r--   1 patrick  staff    188 9 Apr 05:19 package.json

Patricks-MBP:node-part-3-express-blog-with-db-V2 patrick$ ls -l database
total 16
drwxr-xr-x  4 patrick  staff  128  9 Apr 05:19 controllers
-rw-r--r--  1 patrick  staff  704  9 Apr 05:19 db_.js
drwxr-xr-x  4 patrick  staff  128  9 Apr 05:19 models

Patricks-MBP:node-part-3-express-blog-with-db-V2 patrick$ ls -l database/controllers
total 40
-rw-r--r--  1 patrick  staff  9464 9 Apr 05:19 blogController.js
-rw-r--r--  1 patrick  staff  5306 9 Apr 05:19 userController.js

Patricks-MBP:node-part-3-express-blog-with-db-V2 patrick$ ls -l database/models
total 16
-rw-r--r--  1 patrick  staff  1574 9 Apr 05:19 blogModel.js
-rw-r--r--  1 patrick  staff  1216 9 Apr 05:19 userModel.js

Patricks-MBP:node-part-3-express-blog-with-db-V2 patrick$ ls -l modules
total 8
-rw-r--r--  1 patrick  staff  175  9 Apr 05:19 logger.js

Patricks-MBP:node-part-3-express-blog-with-db-V2 patrick$ 

</code></pre>



<p>Read the README.md. After you run <em>npm install</em> You must adapt your database connection string and rename <em>database/db_.js</em> into <em>database/db.js</em>. Your database connection string ist as follows.</p>




<pre class="wp-block-code"><code>mongodb://YOUR-DB-USER:YOUR-DB-USER-PASSWD@localhost:27017/YOUR-DB-NAME

</code></pre>



<p>The application should run with <em>npm blog.js</em>. The application code is explained and commented inline. In addition, I will explain details in the following chapters.</p>




<h3 class="wp-block-heading">How does the application work ?</h3>



<p>The application looks like a very simple web application but already contains a lot of program logic. This program logic is mainly contained in the two user and blog controllers. </p>




<p>The <strong>application data</strong> are <em>users</em> and <em>blogs</em>. These data are stored in a MongoDB and can be created, changed or deleted by the application. When data is entered, i.e. when data sets are created and when data fields are changed, <strong>input validation</strong> takes place. This input validation is based on the mongoose built in input validation and especially for string values on the mongoose custom validation, whereby it is checked whether the input of a string corresponds to a defined regular expression (<a href="https://regex101.com/">regex for ECMA Java Script</a>).</p>




<p>The primary identifier for users is the email address. The <strong>users must be unique</strong> and can only be created if the email address is not already assigned to an existing user.</p>




<p>The users can be blog authors and therefore they have a reference to each blogid whose author they are. Whenever a blog post is created, the application checks whether a user with the specified email address already exists and whether the email address already belongs to an existing user. If the user does not exist or the specified email address belongs to an existing user, the blog post cannot be created. If a user exists and it is also his own email address, the new blog post can be created and the author&#8217;s name, first name and email address are stored on the blog in the database. In parallel the blogid of the new blog post is stored as reference on the user object.</p>




<p>We thus have a <strong>reference from users to their blogs where they are authors</strong> and a reference from blogs to the users or blog authors. When creating a blog, it is a condition that the author exists as a user in the database, but it may still be that we have blogs with authors in the database for which there is no longer a user. This is because it is possible to <strong>delete a user without deleting all blogs where the user is the author</strong>. Therefore it may still be that we have blogs with authors in the database for which there is no longer a user.</p>




<p>Consequently, when a blog is deleted, it is checked whether the author exists as a user. If the user no longer exists, the blog entry will still be deleted. If there is a user in the database, the blog post is deleted and the reference blogid on the user is deleted at the same time.</p>




<p>But we can also <strong>update the email address of a user</strong>. This is a very realistic use case because email addresses can change for users and consequently a user would like to change their changed email address accordingly in our application. Because the email address is the unique identifier of a user, we have to change the email address both on the user and on all blogs where the user is entered as the author. </p>




<p>Our application can also display blogs. All blogs are displayed or only the blogs for a specific year or month or only for a defined date. In order to display the blogs in this way, the blog data are selected accordingly from the database.</p>




<p>In addition, the application also displays a homepage and an about page, which have no further significance.</p>




<h3 class="wp-block-heading">Data Models</h3>



<p>To organize our application data in the <a href="https://www.mongodb.com/">MongoDB</a> we define so called models using <a href="https://mongoosejs.com/">Mongoose</a>. Models contain the essential data structure and data definitions that a database collection should have. Our database will have 2 collections one for the <em>users</em> and one for the <em>blogs</em>.</p>




<p>For each database collection exactly one model is defined in a seperate file. In our example, we need one model for each of the two collections <em>col_users</em> and <em>col_blogs</em>. </p>




<p>For <em>col_users</em> the model is defined in the file </p>




<ul class="wp-block-list">
	<li><em>database/models/userModel.js</em><br></li>
</ul>



<p>for the <em>col_blogs</em> the model is defined in the file </p>




<ul class="wp-block-list">
	<li><em>database/models/blogModel.js</em>.<br></li>
</ul>



<p>I would like to show a standard model here.</p>




<pre class="wp-block-code"><code>// model.js
....

mongoose = require('mongoose')
var Schema = mongoose.Schema

var dataSchema = new Schema ({ key1:..., key2:..., ..., keyN:...}) 

var Data = mongoose.model('col_data', dataSchema)

module.exports = Data

</code></pre>



<p>With <strong>mongoose.Schema</strong> we create a database Schema. With <strong>new Schema(&#8230;)</strong> we define exactly what the Schema looks like and which keys or data fields are defined for each data object that will be stored in the collection. The new Schema is stored in a variable that typically describes the purpose of the new Schema (userSchema or blogSchema in our app). With <strong>mongoose.model()</strong> we create the model and map it to the database collection. The first argument in the <em>mongoose.model()</em> function is the singular name of the database collection. So if we create the model with <em>col_data</em> mongoose is looking for <em>col_datas</em> collection in the database. The second argument in the callback is the new Schema that we defined before. This model will be stored in the Variable <em>Data</em> and exported with <strong>module.exports</strong>.<br/></p>




<p>It is extremely important that all input data are validated before the data is saved in the database. This ensures that the application only processes validated data.</p>




<p>In the model definition of or blog application, I mark all <strong>auto data fields</strong> with a preceding underscore. With auto data fields, the value is either created by the database (like the id) or a default value is always set (like created). This means that these data fields are never manipulated by data input.</p>




<p><strong>Input data fields</strong> are subject to mongoose built-in validation. The topic of input validation is described in great detail in the <a href="https://mongoosejs.com/docs/validation.html">mongoose documentation</a>. Nevertheless, I would like to go into a few points of input validation here.</p>




<p>Basically the specification of validation properties takes place in the database Schema definition per key of the data object. We have built-in validation properties or short validators like <em>required</em>, <em>minlength</em> or <em>maxlength</em> but also the option to define a custom validation function using the property <em>validate</em>. Here in the example below the custom validation function of the key &#8222;name&#8220; checks the input for the match with a <a href="https://regex101.com/">regex</a>. If the input value does not correspond to the <a href="https://regex101.com/">regex</a>, the function return  false and the validation has failed. If the function return true, the data can be saved and the validation was successful.</p>




<pre class="wp-block-code"><code>// model.js

....

mongoose = require('mongoose')
var Schema = mongoose.Schema

var dataSchema = new Schema ({ 

 // define the auto data fields
  _id: {
    type: Schema.ObjectId,
    auto: true
  },

  _created: {
    type: Date,
    default: Date.now()
  },

  // define the input data fields
  name: {
    type: String,
    required: true,
    // input string validation function
    // input sting must match regex criteria
    validate: function(name) {
      return /^[a-zA-Z0-9üÜäÄöÖ.’-]+$/.test(name)
    }
  },  
....

})

....

</code></pre>



<h3 class="wp-block-heading">Data Controllers</h3>



<p>To organize our application data accesses and data manipulations using Mongoose we define so called data controllers in separate files. </p>




<p>In principle, each <em>data model</em> that we have defined in our <em>data model files</em> are representing a <em>data perimeter</em>. A data perimeter can be accessed via so-called <em>controller modules</em> which are defined in separate <em>controller files</em>. These controller modules are in turn defined as <em>controller functions</em> in the corresponding <em>data controller</em>. </p>




<p>These controller functions define the <em>data operations</em> like search queries, create, update and delete data within the controller functions. These data operations are defined in a try &#8230; block and if an error occurs when accessing the data, this error is forwarded to the catch &#8230; block. This catch block then takes over the error handling. I do this try catch thing for all operations except for save(). With save() errors are handled directly in the callback.</p>




<p>In addition to the req and res parameter, the controller functions also receive next as a parameter. This is required to call the default error handler of the server which is defined in our main application file blog.js. </p>




<p>If the request cannot be ended with a response due to an <strong>error</strong> accessing the data, then the request will be passed to the catch block. The catch block call the next(error) function with the error as parameter in order to pass control to the <strong>default error handler</strong> to respond to the request. </p>




<p>If the request cannot be ended with a response due to an <strong>err</strong> accessing the data, then the request will also be passed to the catch block. But the catch block then call an <strong>individual error handler</strong> to respond to the request. </p>




<p>In our application we have the <em>user data perimeter</em> and the <em>blog data perimeter</em> and for each of these different data perimeters there is a separate data controller.</p>




<h4 class="wp-block-heading">User Controller</h4>



<p>The <strong>user data controller</strong> exists to control data access and data manipulations for the <em>user data perimeter</em>.</p>




<ul class="wp-block-list">
	<li>database/controllers/userController.js<br></li>
</ul>



<p>The user data controller contain the following <strong>user controller modules</strong> and functions.</p>




<h4 class="wp-block-heading">createUser</h4>



<p>The createUser function create a new User object in the database. We try first to find a user with the given email address. </p>




<p>If an error occurs here in the query, the request error is passed to the default error handler via catch block. If no error occurs, either a user is found or not. If a user is found, the user cannot be created with createUser and the response is 400 bad request. </p>




<p>If no user is found, the user can be created. This means that the newUser object is saved and the input data is validated when it is saved. If an input data validation error occurs, we will respond with 400 bad request. otherwise there is a 200 ok response and the new user object has been successfully created in the database.</p>




<h4 class="wp-block-heading">updateUserEmail</h4>



<p>With the updateUserEmail function, the email address of a user object can be changed. In parallel also the author email will be adapted on the blog objects where the user is author of blogs. </p>




<p>First the user is searched for with his existing email address. If the function runs on an error, the request and the error are passed on to the default error handler with catch. </p>




<p>If no user is found, we respond with 400 bad request. If, on the other hand, a user is found, the email address can be updated by saving the user object with the new email address. When saving, the input validation takes place again. Only if the input validation was successful the storage of the user object is completed.</p>




<p>Now the email address must be updated on the blogs where the user is the author. </p>




<p>For this we are looking for all blogs where the author email corresponds to the existing email address of the user. If the search runs for an err, we will respond with an individual 502 bad gateway this time because the request has been partially processed up to this point. The email address on the user object has already been updated, but the data for updating the author email addresses on the blogs cannot be queried. </p>




<p>If there is no err in the blog query, the user may not be the author of any blog. Then we answer with 200 ok and confirm that only the email address on the user object has been changed. </p>




<p>If, on the other hand, the user is the author of blogs, we use the updateMany() function to update the email address of any blog found.</p>




<p>This updateMany() function receive a filter object with the previously existing email address of the user as first parameter and then the update object to replace this existing email address with the new email address of the user. This operation is executed on any blog found in the database and is also carried out in a try block. If an err occurs, the request is passed on for individual error handling to the catch block. Here in the catch block we answer with a 502 bad gateway because the update on the user object has been already performed successfully but the update of the author email address on the blogs found was not successful because the updateMany() operation failed. </p>




<p>If the blog update process was successful, we respond with 200 ok. In this case the email address has been changed on the user object and also on his blogs.</p>




<h4 class="wp-block-heading">removeUser</h4>



<p>With removeUser function a user object can be removed from the database. We try first to find the user that should be removed with the given email address. If an error occurs, the request error is passed to the default error handler via catch block. </p>




<p>If no error occurs, either a user is found or not. </p>




<p>If no user is found, the user cannot be removed and the response is 400 bad request. </p>




<p>If the user to be removed has been found we try to delete this user from the database using the deleteOne() function. If an error occurs here, the request error is also passed to the default error handler via catch block. </p>




<p>If the deletion was successful we respond with 200 ok.</p>




<h4 class="wp-block-heading">Blog Controller</h4>



<p>The <strong>blog data controller</strong> exists to control data access and manipulations for the <em>blog data perimeter</em>.</p>




<ul class="wp-block-list">
	<li>database/controllers/blogController.js<br></li>
</ul>



<p>The blog data controller contain the following <strong>blog controller modules</strong> and functions.</p>




<h4 class="wp-block-heading">createBlog</h4>



<p>The createBlog module create a new blog object in the database and update the new blog id reference on the author user object. </p>




<p>The new blog object can only be created if the author data email, first- and lastname match with a user object in the database. So the author must already exist as a user in the database. </p>




<p>We try first to find a user with the author email address. If an error occurs, the request error is passed to the default error handler via catch block. If no error occurs, either a user is found or not. </p>




<p>If no user is found, we respond with 400 bad request. </p>




<p>If a user is found, it is checked whether the provided first name or last name does not match the first name or last name of the user in the database found with the given email address. If one of the names does not match, the condition is false and we send a 400 bad request. </p>




<p>If both names are the same, there is a perfect match of email, first name and last name and the provided author data are validated. Then the blog object can be saved and the blog input data will be validated.</p>




<p>If an input data validation error occurs, we will respond with 400 bad request. </p>




<p>In any other case the new blog has been saved to the database and we try to update the user object by adding the new blog id on the user object as a blog reference. Therefore, we try to use the updateOne() function to find the user object based on the author&#8217;s email address to add the blog id of the newly created blog object as a blog reference.</p>




<p>This operation is carried out in a try block and if an err occurs, it is passed on to the catch block. In case of an err we answer with a 502 bad gateway. The blog object is created but the user object is still not updated because the updateOne() operation was not successful. If the updateOne() operation was successful we respond with 200 ok.</p>




<h4 class="wp-block-heading">removeBlog</h4>



<p>The removeBlog module remove a blog object from the database and update the user object by removing the relevant blog id reference on the author user object. </p>




<p>We try to find a blog object that should be removed based on the blog title. If an error occurs during that query the default error handling function will be invoked via the catch block and next(error). In case of no error the query return one blog object or null which means that no blog object has been found. </p>




<p>If no blog has been found we respond with 400 bad request. </p>




<p>If the query was successful and we found a blog object we try to find a user based on the author email address. If an error occurs the default error handling function will be invoked via the catch block. In case of no error the query return one user object or no user object.</p>




<p>If we have no user object found that mean that the author of the blog is no longer a user in our application. In this case we try to remove only the blog using the deleteOne() function. If this blog deletion function fail we have no success and an error. We catch this error in the catch block to invoke the default error handler function. If the deleteOne() function can be executed successfully, we respond with ok 200. The blog object with the title has been deleted. </p>




<p>If we have found a user object this means that this user is the author of the blog object we want to delete. In this case we first try to remove the blog object using the deleteOne() function and catch the error in the catch block to invoke the default error handler function when the execution of deleteOne() fail. </p>




<p>When the blog deletion was successful, we also try to delete the blog id as a reference on the user object using the updateOne() function. If updateOne throw an err we go ahead with catch and respond with 502 bad gateway as the blog could be removed but the user object update failed. </p>




<p>If the user update of the user object was successful we respond with 200 ok.<br/></p>




<h4 class="wp-block-heading">returnAllBlogs</h4>



<p>The returnAllBlogs module is a function that searches all blog objects in the database and returns them in an array blogs when the requested url is /blogs. If the requested url is different than the next() function will be called to transfer to the next request handler in the row.</p>




<p>We try to search for all blog objects using the find() function. This find function return an error in case the query fail. In this case the catch block will invoke the default error handler function. In case the query was successful the function return an array blogs including the blog objects. </p>




<p>In case the array is empty or better the length is equal to 0 no blog object has been found in the database and we return 200 ok no blogs found. </p>




<p>In case there are blog objects available we create for each blog object found a dataset object of blog attributes containing the title, the author (including name, firstname and email) and the date, push this dataset into a blog array and return this blog array with 200 ok.</p>




<h4 class="wp-block-heading">returnYearBlogs</h4>



<p>The returnYearBlogs module is a function that searches blog objects of a certain year in the database and returns them in an array blogs when the requested url is /blogs/year. If the requested url is different than the next() function will be called to transfer to the next request handler in the row.</p>




<p>We try to search for all blog objects in a year using the find() function and return an error in case the query fail. In this case the catch block will invoke the default error handler function. </p>




<p>In case the query was successful the function return a query array blogs including the blog objects found for the relevant search criteria. In case no blog object has been found (length of blogs is equal to 0) in the database we return 200 ok no blogs found. </p>




<p>In case there are blog objects available we create for each blog object found a dataset object of blog attributes containing the title, the author (including name, firstname and email) and the date, push this dataset into another blog array and return this blog array with 200 ok.</p>




<h4 class="wp-block-heading">returnMonthBlogs</h4>



<p>The returnMonthBlogs module is a function that searches blog objects of a certain year and month in the database and returns them in an array blogs when the requested url is /blogs/year/month. If the requested url is different than the next() function will be called to transfer to the next request handler in the row.</p>




<p>We try to search for all blog objects in a year and month using the find() function and return an error in case the query fail. In this case the catch block will invoke the default error handler function. </p>




<p>In case the query was successful the function return a query array blogs including the blog objects found for the relevant search criteria. In case no blog object has been found (length blogs is equal to 0) in the database we return 200 ok no blogs found. </p>




<p>In case there are blog objects available we create for each blog object found a dataset object of blog attributes containing the title, the author (including name, firstname and email) and the date, push this dataset into another blog array and return this blog array with 200 ok.</p>




<h4 class="wp-block-heading">returnDateBlogs</h4>



<p>The returnDateBlogs module is a function that searches blog objects of a certain date in the database and returns them in an array blogs. </p>




<p>As this is the last routing handler in the app.get() routing function where the path is defined as /blogs/:year?/:month?/day? the requested url matches this definition or not. </p>




<p>In case the requested url is something like /blogs/year/month/day/<strong>else</strong> the url is not defined and then the default route error handler will be invoked and return 404 Not found. </p>




<p>In case the requested url path match /blogs/year/month/day we try to search for all blog objects for the date using the find() function and return an error in case the query fail. In case of an error the catch block will invoke the default error handler function. </p>




<p>In case the query was successful the function return a query array blogs including the blog objects found for the relevant search criteria. </p>




<p>In case no blog object has been found (length blogs is equal to 0) in the database we return 200 ok no blogs found. </p>




<p>In case there are blog objects available we create for each blog object found a dataset object of blog attributes containing the title, the author (including name, firstname and email) and the date, push this dataset into another blog array and return this blog array with 200 ok.</p>




<h3 class="wp-block-heading">Data operations in detail</h3>



<p>Our application perform the following data operations.</p>




<ul class="wp-block-list">
	<li>create data</li>
	<li>search and return data</li>
	<li>update data</li>
	<li>delete data <br></li>
</ul>



<p>These operations will be implemented in the controller modules. We use the following functions to perform these operations.</p>




<ul class="wp-block-list">
	<li>save()</li>
	<li>find()</li>
	<li>findOne()</li>
	<li>updateOne()</li>
	<li>updateMany()</li>
	<li>deleteOne()<br></li>
</ul>



<p>If we want to <strong>create</strong> a new Data object we call <em>new Data(  &#8230;  )</em> and apply the key  specifications according to the Schema defined in the model. </p>




<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p><strong>note</strong>: Please note that we are using new Data(  &#8230;  ) here because we export <em>Data</em> in the above model example definition. If you look in the model files of our blog app, you will notice that I export in the user model <em>User</em> and in the blog model <em>Blog</em>. Consequently, for example, when creating a new user object in the user data controller, the call new User(  &#8230;  ) is made.</p>
</blockquote>



<p>The function <strong>save()</strong> receive a callback function with <em>error</em> as first parameter and <em>data</em> as second parameter. Within the callback we can work with <em>error</em> as the error object and with <em>data</em> as the data object that will be saved in the database. With save(), error handling takes place directly in the call back function using the <em>if (error) &#8230; else &#8230;</em> block.</p>




<pre class="wp-block-code"><code>// controller.js

newData = new Data({key1:..., key2:..., ..., keyN:...})

newData.save(function(error, data) {
	if (error) {

	// do something when an error occurs

	} else {

	// do what you need to do when the creation was successful

	} 
})

</code></pre>



<p>If we want to <strong>search and return data</strong> we call <em>find()</em> or <em>findOne()</em>. </p>




<p>If we expect that a search return several data objects as a result we are using the <em>find()</em> function. </p>




<p>The <em>find()</em> function is covered with the <em>try &#8230; catch &#8230;</em> blog. </p>




<p><strong>find()</strong> receive as first parameter a filter object as search criteria and as second parameter a callback function with <em>error</em> as first parameter and <em>data</em> as second parameter. Because we use <em>try catch</em> error handling is regulated in the catch block and we respond to the request in case of an error within this catch block. </p>




<p>Within the callback we can work with <em>data</em> which is an array containing all the data objects that have been found in the database. In case no data objects were found the <em>data array</em> is empty. In case the function fail we catch the error.</p>




<p>Suppose you want to search in <strong>Data</strong> perimeter for data objects that have a specificName. Then we pass the filter object  name: specificName  and then the callback function(error, data) &#8230; to the Data.find() function. </p>




<pre class="wp-block-code"><code>// controller.js

// create the filter object
var searchDataWithName = { name: specificName }

try {

	Data.find(searchDataWithName, function(error, data) {

	if (data.length == 0) {

	// do something when no data have been found 

	} else {

	// do something with the data array that have been found 

	}

	})

} catch (error) {

// do something when an error occurs

}

</code></pre>



<p>If a search should return only one data object as a result we are using the <em>findOne()</em> method.</p>




<p>The <em>findOne()</em> function is covered with the <em>try &#8230; catch &#8230;</em> blog. </p>




<p><strong>findOne()</strong> receive as first parameter a filter object as search criteria and as second parameter a callback function with <em>error</em> as first parameter and <em>data</em> as second parameter. Because we use <em>try catch</em> error handling is regulated in the catch block and we respond to the request in case of an error within this catch block. </p>




<p>Within the callback we can work with <em>data</em> which is the object that has been found in the database. In case no data object has been found the value of data is null. In case the function fail we catch the error.</p>




<p>Suppose you want to search in <strong>Data</strong> perimeter for one data object that has a specificName. Then we pass the filter object  name: specificName  and then the callback function(error, data) &#8230; to the Data.findOne() function. </p>




<pre class="wp-block-code"><code>// controller.js


// create the filter object
var searchDataWithName = { name: specificName }

try {

Data.findOne(searchDataWithName, function(error, data) {

	if (!data) {

	// do something when no data have been found
	
	} else {

	// do something with the data in the data object that have been found 

	} 

	})

} catch (error) {

// do something when an error occurs

}



</code></pre>



<p>If we want to <strong>update</strong> an existing Data object we search the Data object, apply the changes and then call <em>save()</em>. We can also use <em>updateOne()</em> or <em>updateMany()</em>. </p>




<p>If we do search and <strong>save()</strong> the data object first must be found in the database and will then be returned using the <em>findOne()</em> function. Then we can apply the changes to one or more data attribute values i.e. update the email address of a user and then call save() to save the updated data object back into the database. This procedure has the advantage that input validation is used with save() and is therefore recommended whenever we receive changes directly as input values and these input values must be validated. </p>




<pre class="wp-block-code"><code>// controller.js

// create the filter object
var searchDataWithName = { name: specificName }

try {

	Data.findOne(searchDataWithName, function(error, data) {

	if (!data) {

	// do something when no data have been found
	
	} else {

		// specify the update value
		var updateEmail = newEmail
	
		// update the value
		data.email = updateEmail

		data.save(function(err, updatedData) {

			if (err) {

			// do something when an err occurs
			
			} else {

			// do something when the update was successful

			}
		})
	} 
	})

} catch (error) {

// do something when an error occurs

}

</code></pre>



<p>If we use updateMany() or updateOne() the data objects or the one data object will be looked up and updated in the database in one step. The data object(s) will <strong>not be returned</strong>. This makes processing faster and saves network resources.</p>




<p>The functions updateMany() and updateOne() are both covered with the <em>try &#8230; catch &#8230;</em> blog. </p>




<p><strong>updateMany()</strong> receive as first parameter a filter object as search criteria, as second parameter the update object and as third parameter a callback function with <em>error</em> as first parameter and <em>result</em> as second parameter. Because we use <em>try catch</em> error handling is regulated in the catch block and we respond to the request in case of an error within this catch block. </p>




<p>Within the callback we can work with <em>result</em> which is an object containing data about the processing result  n: 1, nModified: 1, ok: 1 . This mean n objects found, n objects modified and the processing was ok (ok: 0 if the processing failed).</p>




<p>Suppose you want to find in <strong>Data</strong> perimeter for data objects that have a specificName and update all objects found with specificNewName. Then we pass the filter object  name: specificName , the update object  name: specificNewName  and then the callback function(error, result) &#8230; to the Data.updateMany() function. </p>




<pre class="wp-block-code"><code>// controller.js

// create the filter object
var searchDataWithName = { name: specificName }

// create the update object
var updatedName = { name: specificNewName }

....

try {
      
   Data.updateMany(
      	
     searchDataWithName, 
      	
     updatedName, 
      	
     function(err, result) {
      
       // do something with the result
          
     })
     
} catch (err) {
     	
// do something with the err

}

....

</code></pre>



<p><strong>updateOne()</strong> also receive as first parameter a filter object as search criteria, as second parameter the update object and as third parameter a callback function with <em>error</em> as first parameter and <em>result</em> as second parameter. Because we use <em>try catch</em> error handling is regulated in the catch block and we respond to the request in case of an error within this catch block. </p>




<p>Within the callback we can work with <em>result</em> which is an object containing data about the processing result  n: 1, nModified: 1, ok: 1 . This mean n objects found, n objects modified and the processing was ok (ok: 0 if the processing failed).</p>




<p>Suppose you want to find in <strong>Data</strong> data perimeter for one data object that has a specificName and you want to update this single object with specificNewName. Then we pass the filter object  name: specificName , the update object  name: specificNewName  and then the callback function(error, result) &#8230; to the Data.updateOne() function. </p>




<pre class="wp-block-code"><code>// controller.js

// create the filter object
var searchDataWithEmail = { name: specificEmail }

// create the update object
var updatedEmail = { name: specificNewEmail}

try {
   
   Data.updateOne(
      	
     searchDataWithEmail, 
      	
     updatedEmail, 
      	
     function(err, result) {
      
     // do something with the result
          
    })
     
} catch (err) {

// do something with the err

}

....

</code></pre>



<p>If we want to <strong>remove</strong> an existing Data object we search for the data object using <em>findOne()</em> to get the data object returned, and then call <em>deleteOne()</em>. </p>




<p>We do this 2 step approach i.e. in <em>removeBlogs</em> because we use the returned blog object to determine  first the id of the blog object and then use it to find and update the user object. You can do this in one single step only by using <em>deleteOne()</em>, but take into account that you will not receive a data object with which further queries or updates can be carried out.</p>




<p><strong>deleteOne()</strong> receive as first parameter a filter object as search criteria and as second parameter a callback function with <em>error</em> as first parameter and <em>result</em> as second parameter. Because we use <em>try catch</em> error handling is regulated in the catch block and we respond to the request in case of an error within this catch block. </p>




<p>Within the callback we can work with <em>result</em> which is an object containing data about the processing result  n: 1, deletedCount: 1, ok: 1 . This mean n objects found, n objects deleted and the processing was ok (ok: 0 if the processing failed). You can use the result object in the callback to check if the object to be removed has been found or not. But this an operation we don&#8217;t need to perform because we are using the 2 step approach with findOne() and then deleteOne().</p>




<pre class="wp-block-code"><code>....

if (result.n == 0) {
  // do something if no object to be removed has been found
} else {
  // do something when the delete was successful
}

....

</code></pre>



<p>Suppose you want to find in <strong>User</strong> data perimeter for a data object that has a specificName and you want to remove this object from the database. Then we pass the filter object  name: specificName  and then the callback function(error, result) &#8230; to the User.deleteOne() function. </p>




<pre class="wp-block-code"><code>// contoller.js

/ create the filter object
var searchDataWithName = { name: specificName }

try {

	User.findOne(searchDataWithName, function(error, user) {

	if (!user) {

	// do something when no data have been found
	
	} else {
	
		try {
		
		User.deleteOne(searchDataWithName, function(error, result) {
		
			// do something when the delete was successful
		
		})
		
		
		} catch (error) {
		
		// do something when an error occurs		
		}		
}
})


} catch (error) {

// do something when an error occurs

}

</code></pre>



<h3 class="wp-block-heading">HTTP request Routing</h3>



<p>In our application main file <em>blog.js</em> we define routes to process HTTP POST and HTTP GET requests.</p>




<p><strong>HTTP POST requests</strong> are routed using the app.post(&#8218;routingPath&#8216;, routingHandler) method. </p>




<p>During the <strong>create-, update- and remove data</strong> operations app.post() routes are called and the request and response objects are transferred to the corresponding routingHandler to take over the request handling. The request body contain all relevant input data to process the request. </p>




<p>The routingHandler then calls the controller module and transfers the request and response object to this module. Then the module takes over the complete processing of the request and finally sends the response. </p>




<p>So for example if an HTTP POST request is made to the path <em>/createusers</em> the app.post(&#8218;/createusers&#8216;, userController.createUser) route is called and the <em>createUser</em> module take over the complete processing. </p>




<pre class="wp-block-code"><code>// blog.js

....

// load database controllers
const userController = require('./database/controllers/userController');
const blogController = require('./database/controllers/blogController');

....

// define routes (routing table)

....

app.post('/createusers', userController.createUser)

app.post('/updateuseremail', userController.updateUserEmail)

app.post('/removeusers', userController.removeUser)

app.post('/createblogs', blogController.createBlog)

app.post('/removeblogs', blogController.removeBlog)

....

</code></pre>



<p>You have to imagine it in reality with a real web application like this: On a website there is an HTML form and the end user of the application can enter user data such as last name, first name and email address to add for example a new user in the application or in the application database. The moment the user of the application clicks on the send button, the data entered in the form is transferred to the route /createusers with HTTP POST which means that the relevant app.post(&#8218;/createusers&#8216;, userController.createUser) function is called to handle this HTTP POST request. </p>




<p>Unfortunately we are not yet dealing with a real web application because there is no HTML form until now. This is exactly where <a href="https://www.postman.com/">Postman</a> comes in to test an HTTP POST action. In principle, Postman replaces the form. With Postman I can (amongst other things) transfer HTTP POST requests to the application and thus I also transfer the request body. It is therefore necessary that you familiarize yourself with <a href="https://www.postman.com/">Postman</a> to test the applications app.post() routes.</p>




<p><strong>HTTP GET requests</strong> are routed using the app.get(&#8218;routingPath&#8216;, routingHandler) method.</p>




<p>So for example if an HTTP GET request is made to the path <em>/</em> the app.get(&#8218;/&#8216;, routingHandler) route is called and the <em>routingHandler</em> take over the complete processing and send directly the response. The same happens when an HTTP GET request is made on the route <em>/about</em>. This is easy and not spectacular.</p>




<pre class="wp-block-code"><code>// blog.js

....

// load database controllers
const userController = require('./database/controllers/userController');
const blogController = require('./database/controllers/blogController');

....

// define routes (routing table)

....

app.get('/', (req, res) =&gt; {
  res.send('Hello, this is the Blog Home Page.')
})

app.get('/about', (req, res) =&gt; {
  res.send('Hello, this is the Blog About Page.')
})

....


</code></pre>



<p>It is a bit more special when an HTTP GET request is made to the route app.get(&#8218;/blogs/:year?/:month?/:day?&#8216;, &#8230;. ). </p>




<p>The route definition here provides so-called request parameters. The <em>/blogs</em> route can be parameterized with the parameters year, month and day. The question mark behind each parameter indicates that the parameter is optional.</p>




<p>The request is forwarded to several routing handlers. </p>




<p>The first routing handler assigns the request url and the request parameters year, month and day to variables and calls next() to hand over the request to the next routing handler in the row.</p>




<p>The next routingHandler is <em>blogController.returnAllBlogs</em>. This routingHandler calls the controller module <em>returnAllBlogs</em> and transfers the request and response object to this module. Then the module takes over the complete processing of the request and finally sends an array containing all blogs as response <strong>if the request url is equal to /blogs</strong> otherwise next() is called to hand over the request to the next routing handler in the row.</p>




<p>The next routingHandler is <em>blogController.returnYearBlogs</em>. This routingHandler calls the controller module <em>returnYearBlogs</em> and transfers the request and response object to this module. Then the module takes over the complete processing of the request and finally sends an array containing all blogs in the specified year as response <strong>if the request url is equal to /blogs/year</strong> otherwise next() is called to hand over the request to the next routing handler in the row.</p>




<p>The next routingHandler is <em>blogController.returnMonthBlogs</em>. This routingHandler calls the controller module <em>returnMonthBlogs</em> and transfers the request and response object to this module. Then the module takes over the complete processing of the request and finally sends an array containing all blogs in the specified year and month as response <strong>if the request url is equal to /blogs/year/month</strong> otherwise next() is called to hand over the request to the next routing handler in the row.</p>




<p>The next and last routingHandler is <em>blogController.returnDateBlogs</em>. This routingHandler calls the controller module <em>returnDateBlogs</em> and transfers the request and response object to this module. Then the module takes over the complete processing of the request and finally sends an array containing all blogs from the specified date.</p>




<p>Any other route will end up in an error 404 Bad request. </p>




<pre class="wp-block-code"><code>// blog.js

....

// load database controllers
const userController = require('./database/controllers/userController');
const blogController = require('./database/controllers/blogController');

....

// define routes (routing table)

....

app.get('/blogs/:year?/:month?/:day?',

        (req, res, next) =&gt; {
          url = req.url
          year = req.params.year
          month = req.params.month
          day = req.params.day

          next()
        },

        blogController.returnAllBlogs,
        blogController.returnYearBlogs,
        blogController.returnMonthBlogs,
        blogController.returnDateBlogs

      )

....

</code></pre>



<h3 class="wp-block-heading">Status Handling</h3>



<p>In our application we work with the following HTTP Status codes.</p>




<ul class="wp-block-list">
	<li>code 200: status: Ok. Request completed.</li>
	<li>code 500: status: Internal Server Error. Request failed due to server error.</li>
	<li>code 400: status: Bad Request. Request failed due to wrong input data.</li>
	<li>code 404: status: Not Found. Request failed due to wrong route.</li>
	<li>code 502: status: Bad Gateway. Request partly completed but not fully completed due to missing data.<br></li>
</ul>



<h3 class="wp-block-heading">Summary and Outlook</h3>



<p>In this Part 3 of my node.js series I explained how to setup our express blog app using a MongoDB database. We learned how to create data models and controllers to control access to the data. But the blog app has still no HTML frontend or no HTML template rendering is used.</p>




<p>So in the next <a href="https://digitaldocblog.com/mac/nodejs-series-part-4-express-website-with-authentication-and-authorization-in-a-mac-production-environment/" title="Part 4">Part 4</a> of my node.js series I will introduce how to extend the blog app with an HTML interface. Therefore we implement the use of the template engine <a href="https://pugjs.org/api/getting-started.html">Pug</a>. With <a href="https://pugjs.org/api/getting-started.html">Pug</a> we can create an HTML interface for our blog application.</p>




]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
