Monthly Archives: June 2017

Node.js Weekly Update - 30 June

By Gergely Németh

Node.js Weekly Update - 30 June

Below you can find RisingStack‘s collection of the most important Node.js updates, projects, tutorials & Node related conferences from this week:

Security updates for all active release lines, July 2017

The Node.js project will be releasing new versions across all of its active release lines (4.x, 6.x, 8.x) as well as 7.x the week of July 10th 2017 to incorporate a security fix.

All current versions of v4.x through to v8.x inclusive are vulnerable to an issue that can be used by an external attacker to cause a denial of service. The severity of this vulnerability is high and users of the affected versions should plan to upgrade when a fix is made available.

Node.js Performance Monitoring with Prometheus

Prometheus is an open-source solution for Node.js monitoring and alerting. It provides powerful data compressions and fast data querying for time series data.

Node.js Weekly Update - 30 June

When we want to monitor our Node.js application with Prometheus, we need to solve the following challenges:

  • Instrumentation: Safely instrumenting our code with minimal performance overhead
  • Metrics exposition: Exposing our metrics for Prometheus with an HTTP endpoint
  • Hosting Prometheus: Having a well configured Prometheus running
  • Extracting value: Writing queries that are statistically correct
  • Visualizing: Building dashboards and visualizing our queries
  • Alerting: Setting up efficient alerts
  • Paging: Get notified about alerts with applying escalation policies for paging

Online Training: Testing Node.js Applications

The “Testing Node.js Applications” course takes four weeks, with 2-hour webinars (3 in total) and a 1-on-1 session tailored for your special needs.

Node.js Weekly Update - 30 June

During these four weeks, you will learn how to unit test your application, write integration and end-to-end tests. The webinars will be recorded and distributed to the attendees.

Building a sentiment analysis bot with IBM Watson and Raspberry Pi

Do you ever wonder how your teammates perceive your Slack chat messages? Maybe you sound heroic! Or unpleasant. Perhaps you project harsh undertones you haven’t even noticed!

Node.js Weekly Update - 30 June

This project uses Node.js, so make sure Node.js is installed on your machine. You’ll also need an IBM Bluemix account and add the Watson Tone Analyzer.

Trading Cryptocurrencies, Forex, Commodities Stocks and More Using Node.js

We’ll look at the libraries and tools that @flyingunicorn222 has developed over the last couple years after getting into trading Bitcoin and Ethereum (which turned out later into trading all sorts of things based on technical analysis and a bit of flaky statistics).

Node.js Weekly Update - 30 June

Read and write memory in NodeJS (via node addon) (finally!)

Features:

  • open a process
  • close the process (handle)
  • list all open processes
  • list all modules associated with a process
  • find a certain module associated with a process
  • read memory
  • write to memory
  • pattern scanning

This is a Node add-on (last tested to be working on v6.9.1) and therefore requires node-gyp to use.

npm install memoryjs

Memorizing APIs and other tips for coding fluently

On “Your Brain At Work“, Dr. David Rock gives a quick introduction to the current state of neuroscience and goes on to give a great deal of advice on how to handle the perils of office life, which most of us developers can probably relate to.

Node.js Weekly Update - 30 June

This post will attempt to take the main ideas from this book and apply them to common software development situations.

Upcoming Node.js & JavaScript Events

Now open CFP’s:

Upcoming Events

June 30: ThunderPlains, Oklahoma City (OK), United States

June 30: NodeConf EU, Kilkenny, Ireland

July 8: Open Source Summit Europe, Prague, Czech Republic

July 15: Non Binary in Tech, London, UK

July 24: Codemotion Milan, Milan, Italy

August 6: SeaGL, Seattle (WA), United States

August 21: CloudNativeCon + KubeCon North America 2017, Austin (TX), United States

August 31: CubaConf, Havana, Cuba

Previously in the Node.js Weekly Update

In the previous Node.js Weekly Update we read about Node.js overtaking Java in a year, a great TypeScript tutorial, an npm 5 guide, and about how Intel uses Node.js.

We help you to stay up-to-date with Node.js on a daily basis too. Check out our Node.js news page and its Twitter feed!

Source:: risingstack.com

CloudApp: Screen Recording Software on Steroids (With a Simple UI)

By Louis Lazaris

As an editor, writer, web designer, and developer, being a good communicator is a must-have skill for me. While it certainly is a boon to my job that I have strong English skills, that’s often not enough.

That’s why there are tons of screen capture tools available on both Mac and Windows that allow people like me to express ideas, concepts, and problems in a visual way. After all, it’s a pretty well established fact that many people understand things better with visuals instead of words alone.

In this post, I’m going to introduce you to a screen capture tool that I wish I’d been introduced to a long time ago: It’s called CloudApp and I’ll show you how it can be used to communicate bugs, features, and workflow steps that come up in a typical developer workday.

What is CloudApp?

In a nutshell, CloudApp is a visual communication platform with a ridiculously easy-to-use interface that allows you to create, save, and share annotated screenshots, animated GIFs, and screen recordings remotely.

Need to point to a specific feature in an app or on a website? Want to describe a step-by-step process? Need to highlight where a piece of content can be found on a page, while blurring out sensitive information? Or maybe you just need to explain a layout bug in a visual way. The features of CloudApp make accomplishing these tasks as quick and painless as possible.

CloudApp can be downloaded and installed natively on Mac or Windows, and can be integrated with a number of well-known tools including Trello, Zendesk, Slack, and Google Docs.

When you install CloudApp on your Mac, it looks like this, installed in your menu bar:

It’s similar on Windows, placed conveniently in your system tray.

A Single Tool to Replace Many

I’m almost ashamed to admit what my current setup is for doing screen shots and recordings to provide feedback, answer questions, and issue bug reports to clients, co-workers, and others.

I use a native app for screenshots, another one for annotated images, a large bloated piece of software for screen recording, and a couple of different utilities for doing animated GIFs. I’ve also used a few web-based apps for some of these tasks. None of the aforementioned tools is overly complicated, and they all do an adequate job, but it’s not ideal to have to open a different app for each of those tasks.

Enter CloudApp, which does all of this and more in a single, powerful, and easy-to-use tool.

CloudApp’s five primary buttons are visible with one click of the CloudApp icon:

The buttons do the following:

  • Take a screenshot
  • Create a GIF
  • Record your screen (video in HD with audio input option)
  • Take a screenshot and annotate
  • Upload from computer

All these options also have keyboard shortcuts for even quicker access. Additionally, you’ll notice the three dots next to the primary buttons. This opens more options that include:

  • Record webcam video
  • Upload from clipboard
  • Take delayed screenshot

As you can see, there are quite a few features packed into a smart and clean interface.

How Can Developers Use CloudApp?

Although a developer’s primary job is to write and execute code, there’s a lot more to being a developer. If you’re like me, you’ve probably had to do many, if not all of the following at some point in your career:

  • Process a bug
  • Explain a specific feature in an app
  • Demonstrate a set of steps or explain a workflow

You can try to do those things with words alone, or with static, unedited images. But what if you could accomplish those tasks in a speedy, productive manner using animated GIFs, screencasts, and annotated images?

Let’s consider the three things just mentioned and how CloudApp makes them easier.

Pointing Out a Bug

As a developer you’ve probably had the “that’s not what I see” experience when dealing with how a design looks or how a certain feature works (or doesn’t work) in a particular browser. The client (or maybe someone else on your team) sees a bug that you don’t see. Or maybe it’s the other way around. Whatever the case, being able to quickly create a screenshot and annotate it is a huge time saver.

The first option in the CloudApp toolbar (the camera icon) is the screenshot tool. The fourth option, however, lets you take a screenshot and annotate prior to saving it. When you click the annotate screenshot button, you’ll see the following window:

In this case, I’ve taken a screenshot of the search box on scotch.io on Safari 10 for desktop, so I can point out an alignment problem with the magnifying glass that appears inside the box. As many developers have discovered, Safari is the new IE in terms of bugs and incompatibilities. So a tool like CloudApp can come in handy when doing testing on Safari.

In the annotation window you’ll have access to lots of features including a line tool, arrow tool, shape tools, colors, crop tool, pixelate tool, and spotlight tools. In this case, I used the Oval Tool to indicate where the bug is:

Once you hit “save” in the annotation window, the link is copied to the clipboard and you’re ready to share the URL and get feedback. In fact, for every piece of content that gets created or added to CloudApp, you automatically get a URL that uses the ‘cl.ly’ link shortener copied to your clipboard, which you can then share with anyone.

Let’s look at another handy way to use CloudApp.

Explaining a UI Feature

One thing that I’ve often had to do in my work is explain a feature in an app’s interface, maybe something not so easy to find. As an example, let’s use the Chrome DevTools and let’s say I had to describe to my QA team how to test certain parts of a web page with pseudo-states enabled or disabled. Of course, they could do this by simply using a page as a typical user would, but there could be an edge case where doing this via the DevTools can speed things up.

Here’s a GIF I created with CloudApp that demonstrates how to find this feature in the DevTools:

As mentioned, when you create a screenshot or recording with CloudApp, the app will automatically add a link to that piece of media to your clipboard. The URL itself will take you to a page that looks like this:

Notice the right sidebar area that allows for comments. This allows me to send a screenshot, GIF, or video to a colleague and they can add their questions, feedback, etc. Much more useful and productive than a run-of-the-mill screen grab tool!

Sharing a Workflow

As a developer, you probably love to share your productivity and workflow tips with others. Or maybe you just want to show a series of complex steps in a single recording without the need to take multiple, annotated screenshots. CloudApp’s video recording feature is great for this.

Easy HD recording is just a couple of clicks away. In the video shown below, created with CloudApp, I’m demonstrating how to use Chrome’s DevTools to view a minified script, prettify it using a somewhat obscure feature of the DevTools. I then use a breakpoint to step through a JavaScript function:

Check out the screen recording here

And once again, as with GIFs and screenshots, the media page for the video allows comments. In this example, I’ve added a comment to explain how I did a “find” inside the script, which might not be obvious when playing the video.

That screenshot is annotated with CloudApp, and the annotated file is itself available for comments and feedback from anyone who views the link as a logged-in user of CloudApp.

While I’m on the subject of workflow, one practical way CloudApp can be used is sharing workflows in a terminal window. So if you’re trying to share with a colleague something that’s supposed to happen as the result of a terminal command, a quick GIF can do the trick. In the GIF below, I’m installing Yeoman, the popular front-end scaffolding tool:

Thus, CloudApp allows me to create a video or GIF demonstrating the command being executed along with the result in the terminal. The person I send the link to can now run the same command and compare the results, ensuring there are no mysterious error messages or other problems. I’m sure you can see great benefit to this, especially when you’re dealing with much more complex workflows and terminal commands.

This sort of thing can also be a great benefit when doing presentations. So whether you’re presenting something in a meeting at work or at a conference or local meetup, CloudApp becomes your one-stop app for creating all your screenshots and animated GIFs.

Lots More Features

I have to admit, I’m really impressed with the UI for CloudApp. There is no clutter and somehow the CloudApp team has been able to include so many extra features that I haven’t even discussed here. It’s actually been a pleasure examining and learning all the ins and outs of the app while putting together this article.

Here’s a quick summary of some of the other features I didn’t cover:

  • Access to “My CloudApp”, a web dashboard where you can search, sort, and organize your media.
  • Ability to “drop” just about any kind of file into CloudApp, all of which becomes part of “My CloudApp”, allowing you to share, organize, sort, etc.
  • Access to analytics for all your “drops”, including file history, number of views, and more.
  • Ability to drag a file directly onto the CloudApp icon in the menu bar for an instant “drop”.

Conclusion

As the examples in this article have demonstrated, there’s a ton of stuff you can do with CloudApp to help you improve communication on your team and with your clients.

CloudApp truly is screenshot software on steroids, and as easy to use as the simplest of screenshot tools.

CloudApp’s free plan is used by millions and there’s also multiple individual and team paid plans that you can upgrade to that offer more features including security, custom branding, and more. I highly recommend you at least try it out and fiddle with the different features I’ve discussed here. I’m sure after just a few hours of use you’ll consider adding it to your team’s productivity and communication toolset.

Source:: scotch.io

Build an Ionic App with User Authentication

By Matt Raible

Emulator Login

With Okta and OpenID Connect (OIDC) you can easily integrate authentication into an Ionic application, and never have to build it yourself again. OIDC allows you to authenticate directly against the Okta Platform API, and this article shows you how to do just that in an Ionic application. I’ll demo how to log in with OIDC redirect, using Okta’s Auth SDK, and using OAuth with Cordova’s in-app browser; user registration is omitted as the feature is still under active development.

Why Ionic?

Ionic is an open source mobile SDK for developing native and progressive web applications. It leverages Angular and Apache Cordova to allow you to build mobile apps with HTML, CSS, and JavaScript. Apache Cordova embeds the HTML code inside a native WebView on the device, using a foreign function interface to access the native resources of it. You might’ve heard of PhoneGap – this is Adobe’s commercial version of Cordova.

Cordova and PhoneGap allow you to target multiple platforms (e.g. Android and iOS) with one codebase. Not only that, but the apps look like native apps and perform just as well. If you need to tap into native features that aren’t available in web technologies, there are a number of native plugins. Ionic Native is a curated set of these plugins.

I first started using Ionic in late 2013. The project I was working on was developing a native application, but wanted to build several screens of the application with HTML so web developers could author them. I wrote about my experience in March 2014. I enjoyed working with it and found that porting an existing app to use it was more about modifying HTML and tweaking CSS.

Ionic 2 was released in January, making it possible to develop Ionic applications with Angular. Ionic 3 was released in April, allowing development with Angular 4.

NOTE: “Angular” is the common name for Angular 2+. AngularJS is the common name for the 1.x versions. The reason for #ItsJustAngular is Angular 4 was released in March 2017. See Branding Guidelines for Angular and AngularJS for more information.

This article will show you how to build a simple Ionic application and add user authentication to it. Most applications require authentication, so they know who the user is. Once an app knows who you are, it can save your data and better personalization features.

Get Started with Ionic

To set up your environment to develop with Ionic, complete the following steps:

  1. Install Node.js
  2. Install Ionic and Cordova using npm: npm install -g cordova ionic

Create an Ionic Application

From a terminal window, create a new application using the following command:

ionic start ionic-auth

You will be prompted to select a starter project and optionally link your app to your Ionic Dashboard. For this tutorial, choose the tabs starter project and do not connect the app to your Ionic Dashboard.

Project creation may take a minute or two to complete, depending on your internet connection speed. Run the commands below to start your Ionic application.

cd ionic-auth
ionic serve

This command will open your default browser on http://localhost:8100. You can use Chrome’s device toolbar to see what the application will look like on an iPhone 6.

One slick feature of Ionic’s serve command is it shows compilation errors in the browser, rather than in the (sometimes hidden) developer console. For example, if you give an invalid type to the rootPage variable in app.component.ts, you’ll see an error like the one below.

TypeScript Error

Add User Authentication

Ionic Cloud offers a free Auth service. It allows authentication with an email and password, as well as social providers like Facebook, Google, and Twitter. It provides several classes you can use to build authentication in its @ionic/cloud-angular dependency. It even has support custom authentication, but it “requires our own server to handle authentication.”

While there aren’t many current tutorials on using this service, there are a few from last year.

You might notice that both tutorials require quite a bit of code. Also, there doesn’t seem to be a lot of documentation on how you can verify user credentials from the Auth service in a backend service.

Create an OpenID Connect App in Okta

OpenID Connect (OIDC) builds on top of the OAuth 2.0 protocol. It allows clients to verify the identity of the user and, as well as to obtain their basic profile information. To integrate Okta’s Identity Platform for user authentication, you’ll first need to:

  • Register and create an OIDC application
  • Log in to your Okta account and navigate to Admin > Add Applications and click Create New App
  • Select Single Page App (SPA) for the Platform and OpenID Connect for the sign on method
  • Click Create and give your application a name (e.g. “Ionic OIDC”)
  • On the next screen, add http://localhost:8100 as a Redirect URI and click Finish. You should see settings like the following:

Okta OIDC Settings

  • Click on the Assignments tab and select Assign > Assign to People
  • Assign yourself as a user, or someone else that you have credentials for.

Create a Login Page

To create a login page for authentication, create src/pages/login.ts and src/pages/login.html. In login.html, add a form with username and password fields.

<ion-header>
  <ion-navbar>
    <ion-title>
      Login
    </ion-title>
  </ion-navbar>
</ion-header>
<ion-content padding>
  <form #loginForm="ngForm" (ngSubmit)="login()" autocomplete="off">
    <ion-row>
      <ion-col>
        <ion-list inset>
          <ion-item>
            <ion-input placeholder="Email" name="username" id="loginField"
                       type="text" required [(ngModel)]="username" #email></ion-input>
          </ion-item>
          <ion-item>
            <ion-input placeholder="Password" name="password" id="passwordField"
                       type="password" required [(ngModel)]="password"></ion-input>
          </ion-item>
        </ion-list>
      </ion-col>
    </ion-row>
    <ion-row>
      <ion-col>
        <div *ngIf="error" class="alert alert-danger">{{error}}</div>
        <button ion-button class="submit-btn" full type="submit"
                [disabled]="!loginForm.form.valid">Login
        </button>
      </ion-col>
    </ion-row>
  </form>
</ion-content>

You can leverage a couple of open source libraries to perform the actual authentication. The first one is Manfred Steyer’s angular-oauth2-oidc. This library allows you to interact with identity and access tokens easily. The second is the Okta Auth SDK. Since OIDC and OAuth are not authentication protocols, this is necessary to perform authentication from JavaScript without redirecting to Okta.

Install angular-oauth2-oidc using npm.

npm install angular-oauth2-oidc  --save

The Okta Auth SDK doesn’t currently have TypeScript support, so it’s easiest to add it by adding the following at the bottom of src/index.html.

<script src="https://ok1static.oktacdn.com/assets/js/sdk/okta-auth-js/1.5.0/OktaAuth.min.js"></script>

In src/pages/login/login.ts, add the basic structure of the LoginPage class and a constructor that configures your OIDC settings with the OAuthService from angular-oauth2-oidc. You will need to replace “[client-id]” with the Client ID from your Okta OIDC settings and “[dev-id]” with your account’s correct URI.

import { Component, ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';
import { OAuthService } from 'angular-oauth2-oidc';
declare const OktaAuth: any;

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})
export class LoginPage {
  @ViewChild('email') email: any;
  private username: string;
  private password: string;
  private error: string;

  constructor(private navCtrl: NavController, private oauthService: OAuthService) {
    oauthService.redirectUri = window.location.origin;
    oauthService.clientId = '[client-id]';
    oauthService.scope = 'openid profile email';
    oauthService.oidc = true;
    oauthService.issuer = 'https://dev-[dev-id].oktapreview.com';
    oauthService.scope = 'openid email profile';
  }

  ionViewDidLoad(): void {
    setTimeout(() => {
      this.email.setFocus();
    }, 500);
  }
}

Modify src/app/app.component.ts to check to see if the user is logged in. If they’re not, set the LoginPage as the rootPage.

import { OAuthService } from 'angular-oauth2-oidc';
import { LoginPage } from '../pages/login/login';

@Component({
  templateUrl: 'app.html'
})
export class MyApp {
  rootPage: any = TabsPage;

  constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen,
              oauthService: OAuthService) {
    if (oauthService.hasValidIdToken()) {
      this.rootPage = TabsPage;
    } else {
      this.rootPage = LoginPage;
    }

    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();
    });
  }
}

Update src/app/app.module.ts to add LoginPage to its declarations and entryComponents. You’ll also need to add OAuthService to its providers.

@NgModule({
  declarations: [
    ...
    LoginPage
  ],
  ...
  entryComponents: [
    ...
    LoginPage
  ],
  providers: [
    OAuthService,
    ...
  ]
})

Run ionic serve to make sure the LoginPage is displayed when the app first loads. You’ll see the following error when the app tries to load:

No provider for Http!

This error happens because OAuthService has a dependency on Angular’s Http, but it hasn’t been imported into your project. Add HttpModule as an import in src/app/app.module.ts.

import { HttpModule } from '@angular/http';

@NgModule({
  ...
  imports: [
    BrowserModule,
    HttpModule,
    IonicModule.forRoot(MyApp)
  ],
  ...
})

Now the login screen should load. You can use Chrome’s Device Toolbar to see what it’ll look like on an iPhone 6.

Login Page

To solve for the lack of TypeScript support you’ll need to add the following to the top of src/app/pages/login/login.ts.

declare const OktaAuth: any;

TIP: To learn more about including external JavaScript libraries in a TypeScript project, see Nic Raboy’s article on the subject.

Add a login() method in src/app/pages/login/login.ts that uses the Okta Auth SDK to 1) login and 2) exchange the session token for an identity and access token. An ID token is similar to an identity card, in standard JWT format, signed by the OpenID Provider. Access tokens are part of the OAuth specification. An access token can be a JWT. They are used to access protected resources, often by setting them as an Authentication header when making a request.

login(): void {
  this.oauthService.createAndSaveNonce().then(nonce => {
    const authClient = new OktaAuth({
      clientId: this.oauthService.clientId,
      redirectUri: this.oauthService.redirectUri,
      url: this.oauthService.issuer
    });
    authClient.signIn({
      username: this.username,
      password: this.password
    }).then((response) => {
      if (response.status === 'SUCCESS') {
        authClient.token.getWithoutPrompt({
          nonce: nonce,
          responseType: ['id_token', 'token'],
          sessionToken: response.sessionToken,
          scopes: this.oauthService.scope.split(' ')
        })
          .then((tokens) => {
            // oauthService.processIdToken doesn't set an access token
            // set it manually so oauthService.authorizationHeader() works
            localStorage.setItem('access_token', tokens[1].accessToken);
            this.oauthService.processIdToken(tokens[0].idToken, tokens[1].accessToken);
            this.navCtrl.push(TabsPage);
          })
          .catch(error => console.error(error));
      } else {
        throw new Error('We cannot handle the ' + response.status + ' status');
      }
    }).fail((error) => {
      console.error(error);
      this.error = error.message;
    });
  });
}

You want an identity token so you can have more information about the user. You want an access token so you can use it to access protected APIs that require a Bearer token. For example, in Adding Authentication to Your Angular PWA, there’s a BeerService that sends an access token when it makes an API request.

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs';
import { OAuthService } from 'angular-oauth2-oidc';

@Injectable()
export class BeerService {

  constructor(private http: Http, private oauthService: OAuthService) {
  }

  getAll(): Observable<any> {
    const headers: Headers = new Headers();
    headers.append('Authorization', this.oauthService.authorizationHeader());

    let options = new RequestOptions({ headers: headers });

    return this.http.get('http://localhost:8080/good-beers', options)
      .map((response: Response) => response.json());
  }
}

You can (optionally), pretty up the login screen by adding a logo above the form. Download this image, copy it to src/assets/image/okta.png, and add the following above the

tag in login.html.

<ion-row>
  <ion-col text-center>
    <img src="assets/image/okta.png" width="300">
  </ion-col>
</ion-row>

When you try to login to your application using credentials from an Okta user, you’ll see a cross-origin error in your browser’s console.

XMLHttpRequest cannot load https://dev-158606.oktapreview.com/api/v1/authn. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

To fix this, modify the Trusted Origins on Okta (under Security > API) to include your client’s URL (e.g. http://localhost:8100). Check CORS and Redirect for the type of origin.

Add Origin

Now sign in should work, but there’s not much proof on the UI. Add a “Logout” button in the top right corner of the home screen. Replace the in src/pages/home/home.html with the HTML below.

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
    <ion-buttons end>
      <button ion-button (click)="logout()">
        Logout
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

In src/pages/home/home.ts, add a logout() method, as well as methods to get a name and claims from the identity token. Claims in an ID token are bits of information about the issuer, the user, intended audience, expiration date, and issue date. You can see the standard claims in the OIDC spec.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { LoginPage } from '../login/login';
import { OAuthService } from 'angular-oauth2-oidc';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController, public oauthService: OAuthService) {
  }

  logout() {
    this.oauthService.logOut();
    this.navCtrl.setRoot(LoginPage);
    this.navCtrl.popToRoot();
  }

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

  get claims() {
    return this.oauthService.getIdentityClaims();
  }
}

To display this information on the home tab, add the following HTML just after the second paragraph in src/app/home/home.html.

<div *ngIf="givenName">
  <hr>
  <p>You are logged in as: <b>{{ givenName }}</b></p>
  <div class="claims">
    <strong>Claims from Identity Token JWT:</strong>
    <pre>{{claims | json}}</pre>
  </div>
</div>

Update src/app/home/home.scss to add some CSS to make the raw JSON look a bit better.

page-home {
  .claims {
    pre {
      color: green;
    }
  }
  pre {
    border: 1px solid silver;
    background: #eee;
    padding: 10px;
  }
}

Now you should see your name and claims information displayed when you log in.

Home claims

You should also be able to log out and see the login screen with its logo.

Login with logo

NOTE: You might notice that the tabs don’t disappear when logging out. I’m still trying to figure out why this doesn’t work as expected.

Deploy to a Mobile Device

It’s pretty cool that you’re able to develop mobile apps with Ionic in your browser. However, it’s nice to see the fruits of your labor and validate how awesome your app looks on a phone. It does look and behave like a native app!

To see how your application will look on different devices you can run ionic serve --lab. The --lab flag opens a page in your browser that lets you see how your app will display on various devices.

Ionic labs

The LoginPage tries to auto-focus onto the email field when it loads. To auto-activate the keyboard you’ll need to tell Cordova it’s OK to display the keyboard without user interaction. You can do this by adding the following to config.xml in the root directory.

<preference name="KeyboardDisplayRequiresUserAction" value="false" />

iOS

To emulate or deploy to an iOS device, you’ll need a Mac and a fresh installation of Xcode. If you’d like to build iOS apps on Windows, Ionic offers an Ionic Package service.

Make sure to open Xcode to complete the installation. Then run ionic cordova emulate ios to open your app in Simulator.

You’ll likely be prompted to install the @ionic/cli-plugin-cordova plugin. Type “y” and hit enter when prompted.

TIP: The biggest problem I found when running the app in Simulator was that it was difficult to get the keyboard to pop up. To workaround this, I used Hardware > Keyboard > Toggle Software Keyboard when I needed to type text in a field.

If you enter your credentials on the login screen you’ll notice nothing happens. Open Safari and navigate to Develop > Simulator > MyApp / Login, and you’ll see that eventually, an error shows up in the console. If you don’t see a Develop menu, review the steps in this article to enable it.

Web Inspector Error

If you use the Network tab, you can see that only one network request is made (to /authn), which is different than the two requests (to /authn and /authorize) that are made when running in a browser.

DevTools Network Requests

I believe this doesn’t work when the app is packaged with Cordova because it’s making a request to the server with an embedded iframe that then posts back to the current window using postMessage. It seems that Ionic/Cordova doesn’t support this flow (yet). To work around this issue, you can talk directly to Okta’s OAuth service using an in-app browser that’s provided by Cordova. Nic Raboy shows how to do this with Facebook in Using An OAuth 2.0 Service Within An Ionic 2 Mobile App.

Install the Cordova In-App Browser plugin using the following command:

ionic cordova plugin add cordova-plugin-inappbrowser

Open src/app/pages/login/login.html and wrap the

with a

that only shows this login form when running in a browser. Add a new

that is displayed when running in an emulator or on a device.

<ion-content padding>
  <ion-row>
   <!-- optional logo -->
  </ion-row>
  <div showWhen="core">
    <form>
     ...
    </form>
  </div>
  <div hideWhen="core">
    <button ion-button full (click)="redirectLogin()">Login with Okta</button>
  </div>
</ion-content>

Open src/pages/login/login.ts and add a reference to window just below the imports.

declare const window: any;

Then add the methods below to facilitate logging in with OAuth.

redirectLogin() {
    this.oktaLogin().then(success => {
      localStorage.setItem('access_token', success.access_token);
      this.oauthService.processIdToken(success.id_token, success.access_token);
      this.navCtrl.push(TabsPage);
    }, (error) => {
      this.error = error;
    });
  }

  oktaLogin(): Promise<any> {
    return this.oauthService.createAndSaveNonce().then(nonce => {
      let state: string = Math.floor(Math.random() * 1000000000).toString();
      if (window.crypto) {
        const array = new Uint32Array(1);
        window.crypto.getRandomValues(array);
        state = array.join().toString();
      }
      return new Promise((resolve, reject) => {
        const oauthUrl = this.buildOAuthUrl(state, nonce);
        const browser = window.cordova.InAppBrowser.open(oauthUrl, '_blank',
          'location=no,clearsessioncache=yes,clearcache=yes');
        browser.addEventListener('loadstart', (event) => {
          if ((event.url).indexOf('http://localhost:8100') === 0) {
            browser.removeEventListener('exit', () => {});
            browser.close();
            const responseParameters = ((event.url).split('#')[1]).split('&');
            const parsedResponse = {};
            for (let i = 0; i < responseParameters.length; i++) {
              parsedResponse[responseParameters[i].split('=')[0]] =
                responseParameters[i].split('=')[1];
            }
            const defaultError = 'Problem authenticating with Okta';
            if (parsedResponse['state'] !== state) {
              reject(defaultError);
            } else if (parsedResponse['access_token'] !== undefined &&
              parsedResponse['access_token'] !== null) {
              resolve(parsedResponse);
            } else {
              reject(defaultError);
            }
          }
        });
        browser.addEventListener('exit', function (event) {
          reject('The Okta sign in flow was canceled');
        });
      });
    });
  }

  buildOAuthUrl(state, nonce): string {
    return this.oauthService.issuer + '/oauth2/v1/authorize?' +
        'client_id=' + this.oauthService.clientId + '&' +
        'redirect_uri=' + this.oauthService.redirectUri + '&' +
        'response_type=id_token%20token&' +
        'scope=' + encodeURI(this.oauthService.scope) + '&' +
        'state=' + state + '&nonce=' + nonce;
  }

Change the redirectUri that’s set in the constructor to hard-code http://localhost:8100. If you skip this step window.location.origin will result in a file:// origin being sent when the app is running on a device. By making it a known URL, we can look for it with the in-app browser on the “loadstart” event.

constructor(private navCtrl: NavController, private oauthService: OAuthService) {
  oauthService.redirectUri = 'http://localhost:8100';
  ...
}

You’ll have to re-deploy your app to your phone after making these changes.

ionic cordova emulate ios

Now you should be able to log in by clicking on the “Login with Okta” button and entering valid credentials.

Emulator Okta Login Emulator Home

The nice thing about using this technique is the Okta login screen has Remember Me and Forgot Password support, so you don’t need to code those yourself.

To deploy the app to an iPhone, start by plugging one into your computer. Then run the following commands to install ios-deploy, build the app, and run it on your device.

npm install -g ios-deploy 
ionic cordova run ios

This command will likely fail if you haven’t previously set up code signing for your application.

Signing for "MyApp" requires a development team. Select a development team in the project editor.
Code signing is required for product type 'Application' in SDK 'iOS 10.3'

Open your project in Xcode using the command below.

open platforms/ios/MyApp.xcodeproj

Ionic’s deployment documentation provides instructions to solve this issue.

Select your phone as the target in Xcode and click the play button to run your app. The first time you do this, Xcode may spin for a while with a “Processing symbol files” message at the top.

Once you’ve configured your phone, computer, and Apple ID, you should be able to open the app and log in. Below is how it looks on my iPhone.

iPhone Login iPhone Okta Login iPhone Home

Android

To emulate or deploy to an Android device, you’ll first need to install Android Studio. As part of the install, it will show you where it installed the Android SDK. Set this path as an ANDROID_HOME environment variable. On a Mac, it should be ~/Library/Android/sdk/.

If you’ve just installed Android Studio, make sure to open it to complete the installation.

To deploy to the Android emulator, run ionic cordova emulate android. This command will install Android support and print out instructions about how to create an emulator image.

Error: No emulator images (avds) found.
1. Download desired System Image by running:
/Users/mraible/Library/Android/sdk/tools/android sdk
2. Create an AVD by running: /Users/mraible/Library/Android/sdk/tools/android avd
HINT: For a faster emulator, use an Intel System Image and install the HAXM device driver

Run the first suggestion and download your desired system image. Then run the second command and created an AVD (Android Virtual Device) with the following settings:

AVD Name: TestPhone
Device: Nexus 5
Target: Android 7.1.1
CPU/ABI: Google APIs Intel Axom (x86_64)
Skin: Skin with dynamic hardware controls

WARNING: These instructions won’t work with version 2.3.2 of Android Studio on Mac. When you try to run the first command, it’ll say the following:

*************************************************************************
The "android" command is deprecated.
For manual SDK, AVD, and project management, please use Android Studio.
For command-line tools, use tools/bin/sdkmanager and tools/bin/avdmanager
*************************************************************************

To solve this problem, open Android Studio, select “Open an existing Android Studio project” and select the ionic-auth/platforms/android directory. If prompted to upgrade, choose “OK”, then proceed to create a new AVD as described in Android Studio’s documentation.

After performing these steps, you should be able to run ionic cordova emulate android and see your app running in the AVD.

Android Login Android Okta Login Android Home

NOTE: If you get an application error that says “The connection to the server was unsuccessful. (file:///android/www/index.html)”, add the following line to config.xml. This line sets the default timeout to 60 seconds (default is 20). Thanks to the Stack Overflow community for this solution.

<preference name="loadUrlTimeoutValue" value="60000"/>

PWAs with Ionic

Ionic ships with support for creating progressive web apps (PWAs). This means you can deploy your Ionic app as a web app (rather than a mobile app) and make it run offline in browsers that support service workers.

You can see how to enable service workers and make your app into a PWA by reading the PWAs section of how to develop a mobile app with Ionic and Spring Boot. A PWA is a web application that can be “installed” on your system. It works offline when you don’t have an internet connection, leveraging data cached during your last interactions with the app. Adding PWA features can make your apps load a lot faster, creating happy users. To learn more about PWAs, see The Ultimate Guide to Progressive Web Applications.

Learn More

I hope you’ve enjoyed this tour of Ionic, Angular, and Okta. I like how Ionic takes your web development skills up a notch and allows you to create mobile applications that look and behave natively and perform swiftly.

You can see the complete source code for this project on GitHub. Please contact me on Twitter @mraible or on Okta’s Developer Forums if you have any questions.

To learn more about Ionic, Angular, or Okta, please see the following resources:

Source:: scotch.io

What's New in Laravel 5.5

By Hammad Ahmed

Whoops PHP Package

At the time of this writing, Laravel 5.5 is not released yet. It is slated, as the next major release, for release in July 2017. To play around with new features and changes, you need to grab the dev release of Laravel using this Laravel Installer command:

laravel new project --dev

Get Ahead with PHP 7.0+

Laravel 5.5 will require PHP 7.0+. Along with developer features, PHP 7 includes speed improvements which will decrease CPU load by half. So, you should definitely make this upgrade. And if you are using Laravel 5, making this upgrade will be a lot easier since you using the latest version of PHP.

The Next LTS (Long Term Support) Release

After Laravel 5.1, Laravel 5.5 is scheduled to be the next LTS release. This includes two years of bug fixes and three years of security updates.

Welcome Back: Whoops!

Whoops, an error-handling framework, which used to be used by Laravel 4, was removed with the release of Laravel 5.0. But with Laravel 5.5, it’s coming back pre-installed. What Whoops actually does is that it makes the annoying PHP errors and exceptions a little less annoying by changing how they appear. As you can see in the image that it sports the lines of the file in which the error or exception occurred and traces back the operation till inception. And not forgetting to mention, it has zero dependencies (currently(‘pre-laravel-55’)).

“vendor:publish” Gets a Provider Prompt

In previous versions of Laravel, running the vendor:publish command will publish views, configs, migrations and other resources of all vendors. But in Laravel 5.5, running this command will prompt you to select a provider or tag, making it easier to publish only the ones you want. You can also bypass this prompt by specifying the --all' or '--provider' flag with thepublish` command.

Email Themes

Laravel 5.5 adds the ability to specify a custom theme directly to Mailable classes. You can create a CSS style-sheet like this:

touch resources/views/vendor/mail/html/themes/batman.css

And then specify this filename as a property in your Mailable class.

class SendInvoice extends Mailable
{
    protected $theme = 'batman';
    ...
}

Rendering Mailables to the Browser

It can be tedious to test your email templates across email clients. One way to test them is to render them to the browser so that you can make instant changes. But it is not an easy task. Luckily, Laravel 5.5 adds the facility to display them directly from your routes.

You can create a Mailable like this:

php artisan make:mail UserWelcome --markdown=emails.user.subscription.canceled

And then render it through a route:

Route::get('/no/way', function () {
    return new AppMailUserSubscriptionCanceled();
});

There are other tools like Litmus, which solve this problem, but they are pretty expensive relative to this tediously trivial task.

Fresh Migrations

Laravel 5.5 adds another Artisan command to the migrate: namespace. This is similar to migrate:refresh but rather than rolling back your existing migrations, it drops all tables and migrates them from start. The difference between rolling back migrations and dropping tables is that rolling back migrations runs the drop method for each of them. Whilst, the migrate:fresh command simply drops all off of the tables and starts from scratch.

Automatic Package Discovery

In Laravel 5.4 and all versions before, pulling a Laravel package required registering its service providers and adding aliases. Laravel 5.5 adds the ability for packages to automatically register service providers and add aliases through the package’s composer.json file like this:

"extra": {
    "laravel": {
        "providers": [
            "TheDarkKnightBatmanServiceProvider"
        ],
        "aliases": {
            "Bar": "TheDarkKnightBatman"
        }
    }
}

If you are a package developer, then things can’t be much easier for your package users.

Frontend Presets

Out of the box, Laravel includes some CSS and JavaScript scaffolding to help accelerate coding the nitty-gritty. Although you could remove them and start over with your personal preferences, the suggestion was only limited to the Vue framework. Laravel 5.5 introduces 3 frontend presets: Bootstrap, Vue, React and an option choose your own. With Vue being the default preset, you can change the preset to react using this command:

php artisan preset react

You can change react in the above command to vue, bootstrap or none based on your preference.

Error Pages: Design Improvement

In Laravel 5.5, a little change is made in the design of the error pages like 404 or 50* errors: there are some design additions with Flexbox getting the error message centered on the page.

Before Laravel 5.5:

Before Laravel 5.5

In Laravel 5.5:

In Laravel 5.5

Custom Error Reporting

Laravel 5.5 adds support for defining a report method on any custom exception. In Laravel 5.4, you had to check in the Handler class’s report method if a particular exception was thrown. So that you could do something like send an email or report to your app’s monitoring service. You were doing something like this:

...

class Handler extends ExceptionHandler
{
    ...

    public function report(Exception $exception)
    {
        if ($exception instanceof CustomException) {
            // Send email
        }

        parent::report($exception);
    }
}

But with Laravel 5.5, you can get rid of this and register the report method on your custom exception class. Laravel checks to see if there is a report method on your exception class and if it does: calls it.

Streamlined Request Validation

Laravel 5.5 comes with two changes to Request feature. One is that you can now directly call the validate method on your Request instance. So instead of using the controller validator, you can call the validator on your Request instance. You also no longer need to pass the request as the first argument to the validator. Here is an example:

...

public function store()
{
    request()->validate([
        'title' => 'required',
        'body' => 'required'
    ]);

    return Post::create(request(['title', 'body']));
}

The second change made is that the validator returns the request data which you can store in a variable and pass on to the create method of the model.

...

public function store()
{
    $post = request()->validate([
        'title' => 'required',
        'body' => 'required'
    ]);

    // $data = request()->only('title', 'body');

    return Post::create($post);
}

You need to be careful with this since the data returned by the validator will only contain the fields defined in the rules. This adds a little security but you can loose data if some fields were not defined rules for. To avoid this trap, you can add the field with an empty rule like this:

public function store()
{
    $post = request()->validate([
        'title' => 'required',
        'body' => 'required',
        'fieldWithNoRules' => '',
        'andAnotherOne' => ''
    ]);

    // $data = request()->only('title', 'body');

    return Post::create($post);
}

Exception Helper Functions

Coming to Laravel 5.5 are two new helper functions to help you throw exceptions more elegantly. They are: throw_if and throw_unless, and they do exactly what they say. If you want to throw an exception based on a condition then these may help you reduce a conditional block to a single line. They both accept three arguments with the third being optional. First one is a boolean, second is the exception class and third is the exception message passed in case if you didn’t pass with the instantiation of the exception in the second argument. throw_if throws the exception if the boolean is positive and throw_unless throws the exception when the boolean is negative. Here are the examples:

// For `throw_if:

$foo = true;
throw_if($foo, new BarException('Foo is true'));
// or 
throw_if($foo, BarException::class, 'Foo is true');

// For `throw_unless:

$phoo = false;
throw_unless($phoo, new BazException('Phoo is false'));
// or
throw_unless($phoo, BazException::class, 'Phoo is false');

Custom Validation Rules

Laravel 5.5 is coming with a new feature for adding custom validation rules. Custom validation rules are nothing new but with Laravel 5.5 you can have a dedicated class to handle the validation. To define a custom validation rule, you need to create a class with two methods: passes and message. You can place this class anywhere like in the AppRules namespace. The passes method accepts two arguments: attribute and value, which you can use to validate the field.

<?php

namespace AppRules;

use IlluminateContractsValidationRule;

class CustomRule implements Rule
{   
    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        // must return true or false for the validation to pass or fail
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        // return a string here for the failing condition
    }
}

Your custom rule should implement the Laravel’s IlluminateContractsValidationRule contract. You can use this custom validation rule anywhere like in a Form Request class or in the controller validator or the validator from the Request instance. If you are using a custom rule then you can’t pass a string with rules separated by a comma. You need to pass each rule as a single element grouped in an array like this:

$request->validate([
    'someField' => [
        'required', 'min:4', new CustomRule()
    ]
]);

You may also inject any dependency to the constructor if you want. This class-based approach makes custom validation a lot easier.

Model Factory Generators

In Laravel 5.5 you can easily generate model factories with a new Artisan command called make:factory. Here is an example:

php artisan make:factory PostFactory

This will make a new file called PostFactory.php in the database/factories folder. What makes it a lot better is that you can also generate a factory while making a model.

php artisan make:model Post -f

You may also pass the -c flag to add a controller and the -m flag to add a migration. This will help in quickly whipping up a resource.

Miscellany

One minor change is that if you forget to include the CSRF field in a form then it presents you with better inactivity error page. So, if you see something like that, then be sure that it’s related to CSRF.

There is another minor change that will help you in building APIs. Now you get a JSON stack trace rather than HTML markup if an error occurs. This makes it a lot prettier to look at rather than the ugly markup if you are using a tool like Postman.

Conclusion

I hope this guide gets you prepared for the forthcoming goodness. So, This is all there is coming to Laravel 5.5.

Happy Coding!

Source:: scotch.io