Thursday, January 10, 2019

Build an App with Everything New & Noteworthy in Angular 7

Angular 7 was released earlier this quarter and I’m pumped about a few of its features. If you’ve been following Angular since Angular 2, you know that upgrading can sometimes be a pain. There was no Angular 3, but upgrading to Angular 4 wasn’t too bad, aside from a bunch of changes in Angular’s testing infrastructure. Angular 4 to Angular 5 was painless, and 5 to 6 only required changes to classes that used RxJS.

Before I dive into showing you how to build an Angular app with authn/authz, let’s take a look at what’s new and noteworthy in this release.

Upgrade to Angular 7

If you created your app with Angular CLI, chances are you can easily upgrade to the latest release using ng update.

ng update @angular/cli @angular/core

You can also use the Angular Update Guide for complete step-by-step instructions.

Angular Update Guide

What’s New in Angular 7

There are a few notable features in Angular 7, summarized below:

  • CLI prompts: this feature has been added to Schematics so you can prompt the user to make choices when running ng commands.
  • Performance enhancements: the Angular team found many people were using reflect-metadata as a dependency (rather than a dev-only dependency). If you update using the aforementioned methods, this dependency will automatically be moved. Angular 7 also adds bundle budgets so you’ll get warnings when your bundles exceed a particular size.
  • Angular Material: Material Design had significant updates in 2018 and Angular Material v7 reflects those updates.
  • Virtual Scrolling: this feature allows you to load/unload parts of a list based on visibility.
  • Drag and Drop: this feature has been added to the CDK of Angular Material.

Bundle budgets is the feature that excites me the most. I see a lot of Angular apps with large bundle sizes. You want your baseline cost to be minimal, so this feature should help. The following defaults are specified in angular.json when you create a new project with Angular CLI.

"budgets": [{
  "type": "initial",
  "maximumWarning": "2mb",
  "maximumError": "5mb"
}]

You can use Chrome’s data saver extension for maximum awareness of the data your app uses.

For more details on what’s new in Angular 7, see the Angular blog, coverage on InfoQ, or the Angular project’s changelog.

Now that you know how awesome Angular 7 is, let’s take a look at how to create secure applications with it!

Create a Secure Angular 7 Application

An easy way to create Angular 7 apps is using the Angular CLI. To install it, run the following command:

npm i -g @angular/cli

The example below uses Angular CLI 7.1.0. To verify you’re using the same version, you can run ng --version.

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / △ \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 7.1.0
Node: 11.1.0
OS: darwin x64
Angular:
...

Package                      Version
------------------------------------------------------
@angular-devkit/architect    0.11.0
@angular-devkit/core         7.1.0
@angular-devkit/schematics   7.1.0
@schematics/angular          7.1.0
@schematics/update           0.11.0
rxjs                         6.3.3
typescript                   3.1.6

To create a new app, run ng new ng-secure. When prompted for routing, type "Y". The stylesheet format is not relevant to this example, so choose whatever you like. I used CSS.

After Angular CLI finishes creating your app, cd into its directory, run ng new, and navigate to [http://localhost:4200](http://localhost:4200) to see what it looks like.

Default Angular App!

Add Identity and Authentication to Your Angular 7 App with OIDC

If you’re developing apps for a large enterprise, you probably want to code them to use the same set of users. If you’re creating new user stores for each of your apps, stop it! There’s an easier way. You can use OpenID Connect (OIDC) to add authentication to your apps and allow them all to use the same user store.

OIDC requires an identity provider (or IdP). There are many well-known IdPs like Google, Twitter, and Facebook, but those services don’t allow you to manage your users like you would in Active Directory. Okta allows this, and you can use Okta’s API for OIDC.

Register for a forever-free developer account, and when you’re done, come on back so you can learn more about how to secure your Angular app!

Free developer account!

Now that you have a developer account, I’ll show you several techniques for adding OIDC authentication to you Angular 7 app. But first, you’ll need to create a new OIDC app in Okta.

Create an OIDC App in Okta

Log in to your Okta Developer account and navigate to Applications > Add Application. Click Web and click Next. Give the app a name you’ll remember, and specify [http://localhost:4200](http://localhost:4200) as a Login redirect URI. Click Done. Edit your app after creating it and specify [http://localhost:4200](http://localhost:4200) as a Logout redirect URI too. The result should look something like the screenshot below.

Okta OIDC App

Use angular-oauth2-oidc

The angular-oauth2-oidc library provides support for OAuth 2.0 and OIDC. It was originally created by Manfred Steyer and includes many community contributions.

Install angular-oauth2-oidc using the following command:

npm i angular-oauth2-oidc@5.0.2

Open src/app/app.module.ts and import OAuthModule as well as HttpClientModule.

import { HttpClientModule } from '@angular/common/http';
import { OAuthModule } from 'angular-oauth2-oidc';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    OAuthModule.forRoot()
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Modify src/app/app.component.ts to import OAuthService and configure it to use your Okta application settings. Add login() and logout() methods, as well as a getter for the user’s name.

import { Component } from '@angular/core';
import { OAuthService, JwksValidationHandler, AuthConfig } from 'angular-oauth2-oidc';

export const authConfig: AuthConfig = {
  issuer: 'https://{yourOktaDomain}/oauth2/default',
  redirectUri: window.location.origin,
  clientId: '{yourClientId}'
};

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ng-secure';

  constructor(private oauthService: OAuthService) {
    this.oauthService.configure(authConfig);
    this.oauthService.tokenValidationHandler = new JwksValidationHandler();
    this.oauthService.loadDiscoveryDocumentAndTryLogin();
  }

  login() {
    this.oauthService.initImplicitFlow();
  }

  logout() {
    this.oauthService.logOut();
  }

  get givenName() {
    const claims = this.oauthService.getIdentityClaims();
    if (!claims) {
      return null;
    }
    return claims['name'];
  }
}

Modify src/app/app.component.html to add Login and Logout buttons.

<h1>Welcome to !</h1>

<div *ngIf="givenName">
  <h2>Hi, !</h2>
  <button (click)="logout()">Logout</button>
</div>

<div *ngIf="!givenName">
  <button (click)="login()">Login</button>
</div>

<router-outlet></router-outlet>

Restart your app and you should see a login button.

App with Login button

Click the login button, sign in to your Okta account, and you should see your name with a logout button.

App with name and Logout button

Pretty slick, eh?

Okta’s Angular SDK

You can also use Okta’s Angular SDK to implement the same functionality. You can start by installing it.

The post Build an App with Everything New & Noteworthy in Angular 7 appeared first on SitePoint.


by Matt Raible via SitePoint

Animated Mesh Lines with Three.js

A set of five demos with animated WebGL lines created with the THREE.MeshLine library. Find out how to animate and build these lines to create your own animations.

These lines shaped as ribbons have a really interesting graphic style. They also have less vertices than a TubeGeometry usually used to create thick lines.

The post Animated Mesh Lines with Three.js appeared first on Best jQuery.


by Admin via Best jQuery

You can now embed your Google Drawings in Docs

Although it brings a small change, Google has introduced a new and helpful feature for Google Drawings users. The feature will enable them to embed their Drawings saved in Drive directly to Google Doc. Previously, this was not possible and users had to go through the hassle of creating documents...

[ This is a content summary only. Visit our website http://bit.ly/1b4YgHQ for full links, other content, and more! ]

by Saima Salim via Digital Information World

A single Instagram hashtag can uncover images of child sexual abuse

For the pedophiles, all it takes is a single hashtag to open the door to one of Instagram’s seediest corners where images of sexually exploited children reside. Sadly, these images are openly traded as if they were mere collectibles. In fact, our research found that finding images of sexually...

[ This is a content summary only. Visit our website http://bit.ly/1b4YgHQ for full links, other content, and more! ]

by Saima Salim via Digital Information World

Beware: AI will track you for sharing passwords of video-streaming websites

We are often guilty of sharing the password for Netflix, Hulu or HBO Go with our family members, friends, and romantic liaisons. However, a UK company named Synamedia has a plan of action to track down users who share passwords with others. At the CES this year, the UK-based firm unveiled a...

[ This is a content summary only. Visit our website http://bit.ly/1b4YgHQ for full links, other content, and more! ]

by Saima Salim via Digital Information World

How to Use the Modulo Operator in PHP

PHP has a total of eight arithmetic operators. The most common are addition (+), subtraction (-), multiplication (*) and division (/). A slightly lesser-known, though still very important operator is modulo (%). In this tutorial, we'll focus on the modulo operator. We will discuss what it does and some of its practical uses.

What Does the Modulo Operator Do?

If you have two variables $a and $b, calculating $a % $b—usually pronounced "a modulo b" or "a mod b"—will give you the remainder after dividing $a by $b. Modulo is an integer operator, so  it converts both the operands to integers before calculating the remainder. So basically modulo does integer division and then gives back whatever is left from the dividend.

The sign of the value returned by a modulo operation is determined by the sign of the dividend. In division, the result after dividing two negative numbers will be a positive number. However, that's not the case with the modulo operator. The sign of divisor has no effect on the final value.

Here are a couple of examples:

Floating Point Modulo

If you want to calculate the remainder when two floating point numbers are divided by each other, you will have to use the fmod($dividend, $divisor) function. It returns the floating point remainder after the division. The remainder value will have the same sign as the dividend and its magnitude will be less than the divisor. The three numbers are related by following relation:

Here, the value i will always be an integer.

You should remember that floating point arithmetic is not always accurate due to limitations of the binary or decimal representation of fractions. For example, 1/3 cannot be accurately represented in decimal form. You can keep writing 0.33333.... but at some point you would have to stop. You will get closer to the original value with each additional 3 in the decimal representation but the value will still not be exactly 1/3.

This kind of inaccuracy causes problems with the fmod() function: the results are not entirely reliable.

Here are some examples of the fmod() function:

The second value isn't accurate because 0.2 divides 18.8 perfectly. This is just a shortcoming of calculations in the floating point format used by computers.

Uses of the Modulo Operator

In this tutorial, we will restrict ourselves to integer modulo because it is much more common and has a lot of applications.

Checking if a Number is Multiple of Some Other Number

The result of the modulo operator is zero if the first number is perfectly divisible by the second number. This could be used to check if one number is multiple of the other in a given number pair. Probably the most common use of this property of the modulo operator is in checking if a number is even or odd. Here is an example:

In the above example, you could be getting the list of colors from some user and ask them to only provide even number of colors.

The example below uses a similar reasoning to create groups with 5 students each. In real life, you will have to use extra code to group the students but the basic idea of checking if the total students are multiples of 5 does not change.

Changing Numbers to be Multiple of Some Other Number

In the above section, we used the modulo operator to inform users to only provide input values in certain multiple. If that is not possible, we can also force the input to be even as well as a multiple of 5 or some other number.

The modulo operator provides the whole number left after dividing the first number with the second number. This means that subtracting the remainder from the first number will make it a multiple of the second number. For example, 28 can be changed to be multiple of 5 by taking the modulo 28 % 5. In this case, the modulo will be 3. We can now subtract 3 from the original number to make it a multiple of 5. The following line will force any positive number x to be a multiple of some other positive number y by subtracting an appropriate value from it.

In our previous example with 28 students, we could just leave 3 students out and group other students together.

Put a Limit on the Input

As I mentioned in the beginning of the post, in case of positive numbers the modulo operator will return a number between 0 and N - 1, where N is the divisor. This means that you can put a cap on any input and do some operations repetitively and sequentially. Here is an example:

In the above example, we have just five colors but a total of 180 images. This means that we will have to keep looping through the same five colors and assign them to all our images. The modulo operator fits this need perfectly. It will restrict the value of $i % $color_count between 0 and (5 - 1) or 4 inclusive. In other words, we will be able to pick all colors of our array sequentially very easily.

Do Some Task Every Nth Time in a Loop

When traversing a loop, we can check the value of a variable incremented with each pass through the loop and do some specific task after every nth iteration. One practical use case that comes to mind is updating users about some long-running process. Lets say you are making changes to 1000 different images using PHP. If the changes are significant, this process will take a while to update all images.

In such cases, the users will have no way of knowing if the program is just stuck or actually making any progress. What you could do is report the progress to users after editing every 10th image.

The update_images() function in the above example is completely made up but you could replace it with some other processes like resizing the images, adding watermark, turning them gray scale etc. (Check out my PHP GD image editing tutorials if you want to learn how to programatically edit images in PHP yourself.)

Converting Between Different Units of Measurement

The modulo operator can also be used to convert between different units of measurement. For example, you could use it to change a time duration expressed in number of seconds into the same duration expressed in hours, minutes and seconds. Similarly, you could also convert a large of centimeters into kilometers, meters and centimeters. Here is an example:

We begin by simply dividing the total number of seconds by 3600 and casting the value into an integer. This gives us the total number of hours since every hour has 3600 seconds. In the next step, we subtract 3600 * $hours from the original number of seconds. This gets rid of all the seconds that we have converted to hours. Dividing by 60 now will give us the total number of minutes. Finally, we use the modulo operator to get the number of seconds.

Final Thoughts

As you saw in this tutorial, the modulo operator, though easy to use, has a lot of applications. We began this tutorial by looking at the modulo of both positive and negative numbers as well as floats. After that we covered some common scenarios where we would use modulo. 

If you have any questions related to this tutorial, please let me know in the comments. Do you have any other uses of modulo in mind? Please share them with fellow readers by posting them below.


by Monty Shokeen via Envato Tuts+ Code

Save the air.

A windy webspecial in collaboration with Atelier Grand Berg (concept, design & illustration) and German Wahnsinn (music and sounddesign).
by via Awwwards - Sites of the day