Thursday, August 26, 2021

Angular - What are entryComponents

This is for dynamically added components that are added using ViewContainerRef.createComponent(). Adding them to entryComponents tells the offline template compiler to compile them and create factories for them.

The components registered in route configurations are added automatically to entryComponents as well because router-outlet also uses ViewContainerRef.createComponent() to add routed components to the DOM.

Offline template compiler (OTC) only builds components that are actually used. If components aren't used in templates directly the OTC can't know whether they need to be compiled. With entryComponents you can tell the OTC to also compile this components so they are available at runtime.


If you don't list a dynamically added component to entryComponents you'll get an error message a bout a missing factory because Angular won't have created one.


A Bit of Background about entryComponent


entryComponent is any component Angular loads imperatively. You can declare entryComponent by bootstrapping it in NgModule or in route definitions.


@NgModule({

  declarations: [

    AppComponent

  ],

  imports: [

    BrowserModule,

    FormsModule,

    HttpClientModule,

    AppRoutingModule

  ],

  providers: [],

  bootstrap: [AppComponent] // bootstrapped entry component

})



References:

https://stackoverflow.com/questions/39756192/what-is-entrycomponents-in-angular-ngmodule





Friday, August 13, 2021

How to hide computer name in the terminal

Open the preferences in the terminal (top right)

Then go into the shell tab

Then copy/paste the command export PS1="\W \$"; clear;

Then restart the terminal and should work


References:

https://apple.stackexchange.com/questions/34910/how-to-hide-computer-name-and-user-name-in-terminal-command-prompt

Wednesday, August 11, 2021

Node Server too busy rpm

 toobusy polls the node.js event loop and keeps track of "lag", which is long requests wait in node's event queue to be processed. When lag crosses a threshold, toobusy tells you that you're too busy. At this point you can stop request processing early (before you spend too much time on them and compound the problem), and return a "Server Too Busy" response. This allows your server to stay responsive under extreme load, and continue serving as many requests as possible.



ar toobusy = require('toobusy-js'),

    express = require('express');


var app = express();


// middleware which blocks requests when we're too busy

app.use(function(req, res, next) {

  if (toobusy()) {

    res.send(503, "I'm busy right now, sorry.");

  } else {

    next();

  }

});


app.get('/', function(req, res) {

  // processing the request requires some work!

  var i = 0;

  while (i < 1e5) i++;

  res.send("I counted to " + i);

});


var server = app.listen(3000);


process.on('SIGINT', function() {

  server.close();

  // calling .shutdown allows your process to exit normally

  toobusy.shutdown();

  process.exit();

});


References 

https://github.com/STRML/node-toobusy 

Mongo DB Encryption at rest

 Encryption at rest, when used in conjunction with transport encryption and good security policies that protect relevant accounts, passwords, and encryption keys, can help ensure compliance with security and privacy standards, including HIPAA, PCI-DSS, and FERPA.


Encrypted Storage Engine¶

Available in MongoDB Enterprise only, Available for the WiredTiger Storage Engine only. 


MongoDB Enterprise 3.2 introduces a native encryption option for the WiredTiger storage engine. This feature allows MongoDB to encrypt data files such that only parties with the decryption key can decode and read the data.



If encryption is enabled, the default encryption mode that MongoDB Enterprise uses is the AES256-CBC (or 256-bit Advanced Encryption Standard in Cipher Block Chaining mode) via OpenSSL. AES-256 uses a symmetric key; i.e. the same key to encrypt and decrypt text. MongoDB Enterprise for Linux also supports authenticated encryption AES256-GCM (or 256-bit Advanced Encryption Standard in Galois/Counter Mode). FIPS mode encryption is also available.


AES256-GCM and Filesystem Backups


For encrypted storage engines that use AES256-GCM encryption mode, AES256-GCM requires that every process use a unique counter block value with the key.


For encrypted storage engine configured with AES256-GCM cipher:


Restoring from Hot Backup

Starting in 4.2, if you restore from files taken via "hot" backup (i.e. the mongod is running), MongoDB can detect "dirty" keys on startup and automatically rollover the database key to avoid IV (Initialization Vector) reuse.

Restoring from Cold Backup

However, if you restore from files taken via "cold" backup (i.e. the mongod is not running), MongoDB cannot detect "dirty" keys on startup, and reuse of IV voids confidentiality and integrity guarantees.


Starting in 4.2, to avoid the reuse of the keys after restoring from a cold filesystem snapshot, MongoDB adds a new command-line option --eseDatabaseKeyRollover. When started with the --eseDatabaseKeyRollover option, the mongod instance rolls over the database keys configured with AES256-GCM cipher and exits.


In general, if using filesystem based backups for MongoDB Enterprise 4.2+, use the "hot" backup feature, if possible.

For MongoDB Enterprise versions 4.0 and earlier, if you use AES256-GCM encryption mode, do not make copies of your data files or restore from filesystem snapshots ("hot" or "cold").



The data encryption process includes:


Generating a master key.

Generating keys for each database.

Encrypting data with the database keys.

Encrypting the database keys with the master key.



The encryption occurs transparently in the storage layer; i.e. all data files are fully encrypted from a filesystem perspective, and data only exists in an unencrypted state in memory and during transmission.


Key Management¶


The database keys are internal to the server and are only paged to disk in an encrypted format. MongoDB never pages the master key to disk under any circumstances.



Only the master key is external to the server (i.e. kept separate from the data and the database keys), and requires external management. To manage the master key, MongoDB's encrypted storage engine supports two key management options:


Integration with a third party key management appliance via the Key Management Interoperability Protocol (KMIP). Recommended

Local key management via a keyfile.



Using a key manager meets regulatory key management guidelines, such as HIPAA, PCI-DSS, and FERPA, and is recommended over the local key management.



Your key manager must support the KMIP communication protocol.

To authenticate MongoDB to a KMIP server, you must have a valid certificate issued by the key management appliance.


Encrypt Using a New Key

To create a new key, connect mongod to the key manager by starting mongod with the following options:



mongod --enableEncryption --kmipServerName <KMIP Server HostName> \

  --kmipPort <KMIP server port> --kmipServerCAFile ca.pem \

  --kmipClientCertificateFile client.pem



When connecting to the KMIP server, the mongod verifies that the specified --kmipServerName matches the Subject Alternative Name SAN (or, if SAN is not present, the Common Name CN) in the certificate presented by the KMIP server. [1] If SAN is present, mongod does not match against the CN. If the hostname does not match the SAN (or CN), the mongod will fail to connect.


To verify that the key creation and usage was successful, check the log file. If successful, the process will log the following messages:


[initandlisten] Created KMIP key with id: <UID>

[initandlisten] Encryption key manager initialized using master key with id: <UID>



Local Key Management

Using the keyfile method does not meet most regulatory key management guidelines and requires users to securely manage their own keys.

The safe management of the keyfile is critical.


To encrypt using a keyfile, you must have a base64 encoded keyfile that contains a single 16 or 32 character string. The keyfile must only be accessible by the owner of the mongod process.


Create the base64 encoded keyfile with the 16 or 32 character string. You can generate the encoded keyfile using any method you prefer. For example,



openssl rand -base64 32 > mongodb-keyfile


Update the file permissions.

chmod 600 mongodb-keyfile



To use the key file, start mongod with the following options:

--enableEncryption,

--encryptionKeyFile <path to keyfile>,


mongod --enableEncryption --encryptionKeyFile  mongodb-keyfile



References:

https://docs.mongodb.com/manual/core/security-encryption-at-rest/


Tuesday, August 10, 2021

Setting up nginx with Node JS


NGINX is a high-performance HTTP server as well as a reverse proxy.

Unlike traditional servers, NGINX follows an event-driven, asynchronous architecture. As a result, the memory footprint is low and performance is high. If you’re running a Node.js-based web app, you should seriously consider using NGINX as a reverse proxy.



NGINX can be very efficient in serving static assets. For all other requests, it will talk to your Node.js back end and send the response to the client



To install nginx on AWS, yum can be used. 


sudo yum install nginx


Once the nginx is installed, configuration can be done on the below file. 


sudo vi /etc/nginx/nginx.conf


to start the nginx 


sudo nginx

to reload nginx 

nginx -s reload

Now at this point if type in the IP or domain, should be able to see the Amazon landing page from nginx. 


Now it is time to forward the request to the Application server, to do that , need to edit the /etc/nginx/nginx.conf


Below is a sample configuration for SSL and for forwarding all requests on Port 80 to Port 1337 where Application server is listening  


Now lets encrypt might have given in form of chain and actual cert. nginx can take cert and key form. so create new cert like this below 


cat cert.pem fullchain.pem >newcert.pem



     server {

        listen       80;

        listen       443 ssl http2 default_server;

        listen       [::]:443 ssl http2 default_server;

        server_name  _;

        root         /usr/share/nginx/html;


        ssl_certificate "/etc/nginx/ssl/newcert.pem";

        ssl_certificate_key "/etc/nginx/ssl/privkey.pem";

        ssl_session_cache shared:SSL:1m;

        ssl_session_timeout  10m;

        ssl_ciphers HIGH:!aNULL:!MD5;

        ssl_prefer_server_ciphers on;


        # Load configuration files for the default server block.

        include /etc/nginx/default.d/*.conf;



        location / {

           proxy_pass http://localhost:1337;

           proxy_http_version 1.1;

           proxy_set_header Upgrade $http_upgrade;

           proxy_set_header Connection 'upgrade';

   proxy_set_header Host $host;

           proxy_cache_bypass $http_upgrade;

        }


        error_page 404 /404.html;

        location = /404.html {

        }


        error_page 500 502 503 504 /50x.html;

        location = /50x.html {

        }

    }


                                                       



references

https://www.sitepoint.com/configuring-nginx-ssl-node-js/

https://medium.com/@mertcal/install-nginx-on-ec2-instance-in-30-seconds-e714d427b01b



Angular - What are @Input and @Output

Both are use to transform the data from one component to another component.  Or, you can say pass the different types of data form parent to child component and child to parent component.


Or

 

In a simple way, transform/exchange data between two components.

 


@Input is a decorator to mark a property as an input.  @Input is used to define an input property, to achieve component property binding.  @Inoput decorator is used to pass data (property binding) from parent to child component.  The component property should be annotated with @Input decorator to act as input property.


To make the parent-child relation, keep the instance (selector of student component) of student component inside the template URL (app.component.html) of app component.

 


Open app.component.html:  Inside this file, we keep an instance of student component. 


  1. <div> <app-student></app-student></div>  



  1. import { Component, Input, OnInit } from '@angular/core';  
  2.   
  3. @Component({  
  4.    selector: 'app-student',  
  5.    templateUrl: './student.component.html',  
  6.    styleUrls: ['./student.component.css']  
  7. })  
  8.   
  9. export class StudentComponent implements OnInit {  
  10. @Input() myinputMsg:string;  
  11.   
  12. constructor() { }  
  13.   
  14. ngOnInit() {  
  15.    console.log(this.myinputMsg);  
  16.    }  
  17.   
  18. }  




  1. <div>  
  2. <app-student [myinputMsg]="myInputMessage"></app-student>  
  3. </div>  





@Output Decorator

 

@Output decorator is used to pass the data from child to parent component.  @Output decorator binds a property of a component, to send data from one component to the calling component.  @Output binds a property of the type of angular EventEmitter class.

 

To transfer the data from child to parent component, we use @Output decorator.

 

Lets's Open the child component' .ts file (student.component.ts).

 

For use the @Output decorator we have to import, two important decorators, they are Output and EventEmitter.

 

EventEmitter


Use in components with the @Output directive to emit custom events synchronously or asynchronously, and register handlers for those events by subscribing to an instance. 


import { Component, Input, Output,EventEmitter, OnInit } from '@angular/core'; 


Now, create any variable with @Output decorator


@Output() myOutput:EventEmitter<string>= new EventEmitter();  


Here in the place of string, we can pass different types of DataTypes.

After that create a variable to store and pass the message to the parent component.


outputMessage:string="I am child component."  


import { Component, Input, Output,EventEmitter, OnInit } from '@angular/core'; 

  1. @Component({  
  2.    selector: 'app-student',  
  3.    templateUrl: './student.component.html',  
  4.    styleUrls: ['./student.component.css']  
  5. })  
  6. export class StudentComponent implements OnInit {  
  7.    @Input() myinputMsg:string;  
  8.    @Output() myOutput:EventEmitter<string>= new EventEmitter();  
  9.    outputMessage:string="I am child component."  
  10.    constructor() { }  
  11.   
  12.    ngOnInit() {  
  13.       console.log(this.myinputMsg);  
  14.    }  
  15. }  



tudent.component.html


<button (click)="sendValues"> Send Data </button>  


sendValues(){  

   this.myOutput.emit(this.outputMessage);  

}  


References 

https://www.c-sharpcorner.com/article/input-and-output-decorator-in-angular/


Angular Component Selectors

A decorator is used to mark the class as the component in Angular, and it provides informational metadata that defines what kind of properties can be used by the existing component.


A component takes properties as metadata as object, and the object contains key-value pairs like selector, style, or styleUrl. All these properties make a component a complete reusable chunk for the Angular application.


A selector is one of the properties of the object that we use along with the component configuration.


A selector is used to identify each component uniquely into the component tree, and it also defines how the current component is represented in the HTML DOM.


When we create a new component using Angular CLI, the newly created component looks like this.


import { Component } from '@angular/core';


@Component({

  selector: 'my-app',

  templateUrl: './app.component.html',

  styleUrls: [ './app.component.css' ]

})

export class AppComponent  {

  name = 'This is simple component';

}


Here in app.component.ts, notice that we have one property called selector along with the unique name used to identify the app component in the HTML DOM tree once it is rendered into the browser.


 <my-app> is rendered initially because the app component is the root component for our application. If we have any child components, then they all are rendered inside the parent selector.


Basically, the selector property of the component is just a string that is used to identify the component or an element in the DOM.


By default, the selector name may have an app as a prefix at the time of component creation, but we can update it. Keep in mind that two or more component selectors must not be the same.



Selector as an Attribute



We have looked at an example of how to use a selector as an element name, but we are not limited to that. We can also use a selector as an attribute of an element, just like we do along with other HTML elements.

@Component({

4  selector: '[my-app]',

5  templateUrl: './app.component.html',

6  styleUrls: [ './app.component.css' ]

7})



Selector as a Class



@Component({

4  selector: '.my-app',

5  templateUrl: './app.component.html',

6  styleUrls: [ './app.component.css' ]

7})

8export class AppComponent  {

9  name = 'Angular';

10}







References

https://www.pluralsight.com/guides/understanding-the-purpose-and-use-of-the-selector-in-angular