Node.js Weekly Update - September 15

By Tamas Kadlecsik

Node.js Weekly Update - September 15

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

Re-thinking the Node.js ecosystem for modern JavaScript

We need to rebuild most of the software infrastructure in the Node.js Ecosystem.

In order to move forward, we’re going to have to stop using a lot of the software infrastructure we rely on today but first we need solid alternatives.

What’s new in Node.js 8.5?

With the recent release of Node.js 8.5, three very exciting new features landed in the Node.js core.

In the short blogpost, you are going to learn about them:

  • ECMAScript Modules in Node.js!
  • Performance Hooks
  • File copy with the core fs module

Using ES modules natively in Node.js

Starting with version 8.5.0, Node.js supports ES modules natively, behind a command line option. Most of the credit for this new functionality goes to Bradley Farias.

This blog post explains the details.

How To Combine a NodeJS Back End with a ReactJS Front End App

This blogpost shows how you can build the front and back end of a website using NodeJS for the back end.

Node.js Weekly Update - September 15

We’ll use node to create endpoints, and set up a database in JSON format. Then, we’ll create a front end application using React that will post to the database, and also fetch data from it.

Understanding & Measuring HTTP Timings with Node.js

Understanding and measuring HTTP timings helps us to discover performance bottlenecks in client to server or server to server communication.

Node.js Weekly Update - September 15

This article explains timings in an HTTP request and shows how to measure them in Node.js.

Building a crude Node.js from scratch

Node is powered by the JavaScript engine used in Google Chrome, called V81. This post is going to guide you through two steps:

  • making a “Hello World” example in V8
  • making a crude Node runtime with support for 3 statements: console.log, console.error and quit for quitting the process

Securing Node.js RESTful APIs with JSON Web Tokens

Have you ever wondered how authentication works? What’s behind all the complexity and abstractions. Actually, nothing special. It’s a way of encrypting a value, in turn creating a unique token that users use as an identifier. This token verifies your identity. It can authenticate who you are, and authorize various resources you have access to. If you by any chance don’t know any of these keywords, be patient, I’ll explain everything below.

This will be a step by step tutorial of how to add token based authentication to an existing REST API. The authentication strategy in question is JWT (JSON Web Token). If that doesn’t tell you much, it’s fine. It was just as strange for me when I first heard the term.

ES2017’s async/await is the best thing to ever happen to JavaScript

Async await is part of the ES2017 standard, in node since version 7 and all current browsers.

  • await – is a way to await until a promise has returned a value (resolved). Error handling is plain old JavaScript: if something breaks (ie, a promise rejects), an Error is thrown. On the next line, you can just use the value like any other. No more .then().
  • async – a thing you add to the function containing the await keyword. Technically it starts a special context, practically it’s a thing you need to add.

Previously in the Node.js Weekly Update

In the previous Node.js Weekly Update we read that Node.js 6.11.3 (LTS) & Yarn 1.0 got released & about Fastify, a speedy Node.js Web Framework.

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

Deploying an Angular CLI App to Production with Firebase

By Chris Sevilleja

Firebase Home Page

Building Angular apps is a fun project. Once you’re done building, it’s time to expand the fun by sharing your project with the world.

While there’s many ways to host our Angular application, we’ll be looking at how to host with Firebase since Firebase makes it super simple. Firebase offers many great features (and has a solid free plan).

  • Realtime Database
  • Hosting
  • Authentication
  • Cloud Functions
  • Cloud Storage
  • Bunch More

We’ll just be using Firebase hosting to handle our Angular app.

TLDR: What’s the Overall Process

  • The Angular CLI will create our dist files: ng build --prod
  • We’ll deploy using Firebase command line tools: firebase deploy
  • Firebase will host and handle routing!

Creating an Angular App

We’ll be using the Angular CLI to create our Angular app that we’ll deploy. For more info on the CLI, check out our article: Use the Angular CLI For Faster Angular v2+ Projects.

Angular CLI Home Page

Install the CLI

If you don’t already have the CLI installed, we can do it using Node and npm.

npm install -g @angular/cli

Note: The -g flag is to install globally across our entire machine.

Start an Angular App

Once we have the CLI, we can create a new Angular app and test it out using the following:

# create a new app
ng new hosty-app

# go into our new app
cd hosty-app

# serve it locally and see it in action
ng serve --open

ng serve

Angular CLI Test App

Our app is good to go! Let’s start setting up our Firebase app.

Creating the Firebase App

We’ll need to create a Firebase account and a Firebase app so that our application knows where to deploy to. Once you login to your Firebase console, create a new app.

Firebase Dashboard

We’ll name our app Angular Hosting Test. You can also set the subdomain for your app. Your app will be hosted at subdomain.firebase-app.com.

Create a Firebase Project

Our new app is live! That’s all we had to do in the Firebase dashboard. The rest of the work will be done on our own computer in our applications.

Installing the Firebase Tools

In order to deploy to Firebase, we’ll need the Firebase CLI tools. Here’s the steps we’re about to take:

  • Download the tools
  • Login to Firebase using the tools
  • Link our local app to our Firebase app

Install the Firebase Tools

We’ll use npm to install similar to how we installed the Angular CLI:

npm install -g firebase-tools

Login to Firebase

We’ll use the CLI tools to login to Firebase.

firebase login

This will open your browser and allow us to login from there.

Firebase CLI Login

Firebase Login Successful

That’s it! We’re all ready to start using the Firebase tools.

Using Firebase In Our Angular App

The first step is to link our local Angular app to our Firebase app we created in the Firebase dashboard.

firebase init

Here’s the answers to the questions Firebase tools will ask:

  • Are you ready to proceed? Yes
  • Which Firebase CLI features? Hosting (In the future, use whatever you need! Press space to select.)
  • Select a default Firebase project? Angular Hosting Test (Choose whatever app you created in the earlier steps)
  • What do you want to use as your public directory? dist (This is important! Angular creates the dist folder.)
  • Configure as a single-page app? Yes

Firebase Init

You may be asking, what exactly does this command do? This creates two new files:

.firebaserc: Sets the Firebase project we’re linking to

{
  "projects": {
    "default": "angular-hosting"
  }
}

firebase.json: Sets the hosting folder and rewrites

{
  "hosting": {
    "public": "dist",
    "rewrites": [
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }
}

Our app is now linked to our Firebase app. We’re ready to finally deploy!

Deploying

The deploy is essentially two steps:

  • Create the production files in the dist folder
  • Deploy to Firebase!

Build Our Angular App

We’ll create our production files using the Angular CLI command:

ng build --prod

This will create a brand new dist/ folder in our project with the files necessary to launch our app. You could take these files and open the index.html file locally and see your app running!

ng build

Angular CLI Dist Files

Deploy to Firebase

Now that we have the dist/ folder, we can tell Firebase to deploy it:

firebase deploy

firebase deploy

Our app is now deployed and ready to view! Run this Firebase command to see it in action:

firebase open hosting:site

https://angular-hosting.firebaseapp.com/

Firebase Hosting Dashboard

You can visit the Firebase dashboard to see the logs of all your deployments. You can even set a custom domain in the dashboard.

Firebase Hosting Dashboard

Extra: Script to Deploy

If you want to automate the process of building and deploying, you can add a script to your package.json file:

"scripts": {
  ... 
  "deploy": "ng build --prod && firebase deploy"
},

Now we can run the deploy script with:

npm run deploy

Watch as both commands run and our site is updated!

Conclusion

With Firebase hosting, it’s an easy process to deploy our Angular CLI apps to production. In the future we’ll be exploring more options with other hosting providers, but Firebase is a fast, free, and easy way to host quick Angular apps.

Source:: scotch.io

Using Sass with the Angular CLI

By Chris Sevilleja

Angular CLI Home Page

One of the first things you’ll usually do in a project is to bring in Sass to make working with CSS easier.

When working with the Angular CLI, the default stylesheets have the .css extension. Let’s explore how we can easily bring in Sass to our Angular CLI projects.

Sass Home Page

If you want a quick intro into the Angular CLI, check out the official docs and our Use the Angular CLI For Faster Angular v2+ Projects.

Starting an Angular CLI Project with Sass

Normally, when we run ng new my-app, our app will have .css files. To get the CLI to generate .scss files (or .sass/.less) is an easy matter.

Create a new project with Sass with the following:

ng new my-sassy-app --style=scss

You can also set the --style flag with the following:

  • --style=scss
  • --style=sass
  • --style=less

Converting a Current App to Sass

If you’ve already created your Angular CLI app with the default .css files, it will take a bit more work to convert it over. You can tell Angular to start processing Sass files with the following command:

ng set defaults.styleExt scss

This will go ahead and tell the Angular CLI to start processing .scss files. If you want to peek under the hood at what this command did, check out the Angular CLI config file: .angular-cli.json.

You’ll find the new config line at the bottom of the file:

"defaults": {
  "styleExt": "scss",
  "component": {
  }
}

Changing the CSS Files to Sass

The Angular CLI will start processing Sass files now. However, it doesn’t go through the process of converting your already existing .css files to .scss files. You’ll have to make the conversion manually.

Using Sass Imports

I personally like creating Sass files for project variables and for project mixins. This way, we can bring in any variables/mixins we’ll need quickly and easily.

For instance, let’s create a brand new CLI app:

ng new my-sassy-app --style=scss

Next, we’ll create the following files:

|- src/
    |- sass/
        |- _variables.scss
        |- _mixins.scss
        |- styles.scss

To start using these new Sass files, we’ll import the _variables.scss and _mixins.scss into the main styles.scss.

// src/sass/styles.scss

@import './variables';
@import './mixins';

The last step is to update our .angular-cli.json config to use this new src/sass/styles.scss instead of the src/styles.scss. In our .angular-cli.json file, just change the following line to point to the right styles.scss.

I like separating out our Sass into its own folder because it allows us to create a more robust Sass foundation. I personally lean towards the Sass 7-1 Pattern.

Now when we start up our app, these new Sass files will be used!

Importing Sass Files Into Angular Components

We have new _variables.scss and _mixins.scss files that we will probably want to use in our components. In other projects, you may be used to having access to your Sass variables in all locations since your Sass is compiled by a task runner.

In the Angular CLI, all components are self-contained and so are their Sass files. In order to use a variable from within a component’s Sass file, you’ll need to import the _variables.scss file.

One way to do this is to @import with a relative path from the component. This may not scale if you have many nested folders or eventually move files around.

The CLI provides an easy way to import Sass files using the ~.

No matter what component Sass file we’re in, we can do an import like so:

// src/app/app.component.scss

@import '~sass/variables';

// now we can use those variables!

The tilde (~) will tell Sass to look in the src/ folder and is a quick shortcut to importing Sass files.

Using Bootstrap Sass Files

Another scenario we’ll need to do often is to import third party libraries and their Sass files.

We’ll bring in Bootstrap and see how we can import the Sass files into our project. This is good since we can pick and choose what parts of Bootstrap we want to use. We can also import the Bootstrap mixins and use them in our own projects.

To get us started, install bootstrap:

npm install --save bootstrap@4.0.0-beta

Note: We’re using the 4.0 beta because 4.0 is built with Sass and gives the proper .scss files.

Adding Bootstrap CSS File

Now that we have Bootstrap, let’s look at how we can include the basic CSS file. This is an easy process by adding the bootstrap.css file to our .angular-cli.json config:

"styles": [
  "../node_modules/bootstrap/dist/css/bootstrap.css",
  "sass/styles.scss"
],

Note: We’re using the .. because the CLI starts looking from within the src/ folder. We had to go up one folder to get to the node_modules folder.

While we can import the Bootstrap CSS this way, this doesn’t let us import just sections of Bootstrap or use the Sass variables/mixins that Bootstrap provides.

Let’s look at how we can use the Bootstrap Sass files instead of the CSS file.

Adding Bootstrap Sass Files

Let’s cut down the number of CSS rules that we use in our app. Let’s look at all the Sass files that Bootstrap uses:

/*!
 * Bootstrap v4.0.0-beta (https://getbootstrap.com)
 * Copyright 2011-2017 The Bootstrap Authors
 * Copyright 2011-2017 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 */

@import "functions";
@import "variables";
@import "mixins";
@import "print";
@import "reboot";
@import "type";
@import "images";
@import "code";
@import "grid";
@import "tables";
@import "forms";
@import "buttons";
@import "transitions";
@import "dropdown";
@import "button-group";
@import "input-group";
@import "custom-forms";
@import "nav";
@import "navbar";
@import "card";
@import "breadcrumb";
@import "pagination";
@import "badge";
@import "jumbotron";
@import "alert";
@import "progress";
@import "media";
@import "list-group";
@import "close";
@import "modal";
@import "tooltip";
@import "popover";
@import "carousel";
@import "utilities";

That’s a lot of tools that you may not use in your own project.

Inside our src/sass/styles.scss file, let’s import only the Bootstrap files we’ll need. Just like we imported Sass files from the src folder using the tilde (~), the tilde will also look into the node_modules folder.

We can do the following to only get the Bootstrap base tools:

// src/sass/styles.scss

@import 
  '~bootstrap/scss/functions',
  '~bootstrap/scss/variables',
  '~bootstrap/scss/mixins',
  '~bootstrap/scss/print',
  '~bootstrap/scss/reboot',
  '~bootstrap/scss/type';

Conclusion

The tilde (~) makes importing Sass files in the Angular CLI super easy! Hope this quick tip was helpful in your Angular journey. Thanks for reading.

While it is a bit more work to have to import files into every component that you’ll want to use them in, it’s not too bad of a workaround to use the ~.

Source:: scotch.io

Build a Preact App with Authentication

By Lee Brandt

Base Preact Application

React is a fast, and lightweight library, which has led to fast adoption across the SPA (single-page app) ecosystem. Preact is an even lighter-and-faster alternative to React, weighing in at a measly 3kb! For less complex applications, it can be a great choice.

In this tutorial, you’ll build a basic Preact application with a couple of pages and user authentication using the Okta Sign-In Widget.

Bootstrap Your App With PreactCLI

To get your project started, you’ll install the PreactCLI using NPM.

npm install -g preact-cli

Once you have the CLI installed, run the command to create a base Preact application:

preact create okta-preact-example

This command will chug along for a few minutes scaffolding a basic Preact app and installing all the dependencies. Once it’s done, you should see a bunch of information on the command line informing you of what you can do next.

Change into the application directory.

cd okta-preact-example

Then start the application, just to make sure everything worked as expected.

npm start

You should see a quick build run and the screen will clear and show you that the application is running at http://localhost:8080. When you open up that URL in your browser, you should see a page like this:

Some Things To Note About PreactCLI

Even though the PreactCLI-generated app looks a lot like a React app generated by create-react-app, and you can even use some of the React plugins (like React-Router in your Preact application, there are some significant differences.

For instance, unlike the ReactCLI, there is no way to eject the Webpack configuration. Instead Preact encourages developers to customize Webpack by creating a file called preact.config.js, using Preact’s Webpack Config Helpers and exporting functions to change the way Webpack behaves.

Even though the PreactCLI says the application is running at http://0.0.0.0:8080, use http://localhost:8080. It’s the same thing and when you set up your application in the Okta dashboard, you’ll set http://localhost:8080 as your base URL and callback URL, so this just makes sure that you can call the Okta APIs.

Create Your Okta Application

Now that you have the basic shell of an application, it’s time to add user authentication. If you don’t already have one, create a free (forever) account at Okta.

Once you’ve created an account, go to the admin dashboard and click on “Applications” in the page menu. Then click the green “Add Application” button, then the green “Create New App” button, so that you see a modal window like:

Create Application Screen

Choose “SPA” from the Platform buttons. OpenID Connect will already be chosen for you. Click the “Next” button to create your application.

This will take you to a screen to “Application Settings” page of the Create Application wizard. Enter “OktaPreactExample” in the Application name field and add http://localhost:8080 as your base URI and as a login redirect URI. When you’re done, your form should look like this:

Application Settings Screen

Note: You’ll need to create a user (if you don’t already have one) and assign your new application to them as well. Or you can log in with the credentials you use to log in to your Okta account (the admin user).

Install the Okta Sign In Widget

The easiest way to get Okta’s authentication into your new Preact application will be to use Okta’s Sign-In Widget. You’ll install it with npm using:

npm install @okta/okta-signin-widget --save

You’ll also need to install preact-router with:

npm install preact-router --save

Add an Auth High Order Component

With that done, you now need to add some High Order Components to help with authentication.

Add a file called auth.js in the /src/lib folder and add the following code:

import {h} from 'preact';
import { route } from 'preact-router';
import OktaSignIn from '@okta/okta-signin-widget/dist/js/okta-sign-in.min.js';
import '@okta/okta-signin-widget/dist/css/okta-sign-in.min.css';
import '@okta/okta-signin-widget/dist/css/okta-theme.css';

class Auth {
  constructor() {
    this.login = this.login.bind(this);
    this.logout = this.logout.bind(this);
    this.isAuthenticated = this.isAuthenticated.bind(this);
    this.handleAuthentication = this.handleAuthentication.bind(this);

    this.widget = new OktaSignIn({
      baseUrl: 'https://{yourOktaDomain}.com/',
      clientId: '{clientId}',
      redirectUri: 'http://localhost:8080',
      authParams: {
        responseType: ['id_token', 'token'],
        scopes: ['openid', 'email', 'profile']
      }
    });
  }

  isAuthenticated() {
    // Checks if there is a current accessToken in the TokenManger.
    return !!this.widget.tokenManager.get('accessToken');
  }

  getCurrentUser(){
    return this.widget.tokenManager.get('idToken');
  }

  login() {
    // Redirect to the login page
    route('/login/');
  }

  async logout() {
    this.widget.tokenManager.clear();
    await this.widget.signOut();
    location = '/';
  }

  handleAuthentication(tokens) {
    for (let token of tokens) {
      if (token.idToken) {
        this.widget.tokenManager.add('idToken', token);
      } else if (token.accessToken) {
        this.widget.tokenManager.add('accessToken', token);
      }
    }
  }
}

// create a singleton
const auth = new Auth();
export const withAuth = WrappedComponent => props =>
  <WrappedComponent auth={auth} {...props} />;

In the first line of code, you can tell something’s different. The h module in Preact is what turns JSX into DOM elements. Normally, React would use the React library to generate React.createElement statements to make DOM elements from JSX. Preact uses the h library to make something like h('div', {class:'something'}, 'Content') statements to do that.

Next, you imported route from preact-router right below the h import. This is what is used by Preact to do the redirects in the login function. Notice that the Auth class is just a regular function and does not extend Component. In the constructor, the internal functions were bound with the this context from the Auth class.

Then enter your Okta organization URL and client ID to the Okta Sign-In Widget configuration. Your Organization URL will be the URL you use when you log into your Okta account (e.g. http://dev-12345.oktapreview.com) and you can get your client ID from the application’s property page in the administrative dashboard on the “General” tab for your application (obviously, yours won’t be blurred out):

Client ID Screen

You’ll also want to change the redirectUri property to http://localhost:8080 because the Preact uses port 8080 instead of 3000 for normal React apps.

The login function simply routes the user to the login page, while the logout function clears the tokens saved in the widget’s token manager, calls signOut on the widget, and redirects the user to the root of the application.

Finally, a singleton of the Auth class is created to be shared by all the components, and is passed in as a prop called auth to any component that you wrap in withAuth.

Create a Widget Wrapper

Create a file in your /src/lib folder called OktaSignInWidget.js. Enter the code for this component:

import { h, Component } from 'preact';

export default class OktaSignInWidget extends Component {
  componentDidMount() {
    this.widget = this.props.widget;
    this.widget.renderEl({ el: this.widgetContainer }, this.props.onSuccess, this.props.onError);
  }

  componentWillUnmount() {
    this.widget.remove();
  }

  render() {
    return <div ref={(div) => { this.widgetContainer = div; }} />
  }
};

Here, the componentDidMount method renders the Okta Sign-In Widget to the div in your render method and the componentWillUnmount function removes the widget.

In the render method, there’s some strange-looking code. This allows you to set a reference to the current element into a variable called widgetContainer and then use it in the componentDidMount as this.widgetContainer. Neat, huh? Thanks to Matt Raible for showing me that trick!

Create a Redirect Component

The React-Router has a Redirect component in it, but the Preact router doesn’t, so you’ll need one. Luckily, it’s easy to create your own. In your /src/lib folder create a file called Redirect.js and add the following code:

import { Component } from 'preact';

export default class Redirect extends Component {
  componentWillMount() {
    location = this.props.to.pathname;
  }

  render() {
    return null;
  }
}

This is just a component that will redirect based on a URL passed to it. In this case, the use will be redirected using the window.location mechanism, mostly because you’ll want to refresh the page. You could also just use route(this.props.to.pathname) and let Preact’s router redirect the user.

Create a Login Component

Next, create a Login folder in src/routes. In that folder create an index.js file and a style.css file. This just follows along with the way the Preact CLI creates components.

In the index.js file, create a Login component, wrapped in the withAuth component. First, by importing the modules needed:

import { h, Component } from 'preact';
import Redirect from '../../lib/Redirect';
import OktaSignInWidget from '../../lib/OktaSignInWidget';
import { withAuth } from '../../lib/auth';

Start the component by wrapping in the withAuth high order component you created earlier, and set the beginning state. Here, you’ll have the redirectToReferrer set to false by default.

export default withAuth(class Login extends Component {
  state = {
    redirectToReferrer: false
  };
})

In the componentWillMount lifecycle function, wire up the onSuccess and onError functions and create them in your component.

  componentWillMount() {
    this.onSuccess = this.onSuccess.bind(this);
    this.onError = this.onError.bind(this);
  }

  onSuccess(tokens) {
    this.props.auth.handleAuthentication(tokens);
    this.setState({
      redirectToReferrer: true
    });
  }

  onError(err) {
    console.log('error logging in', err);
  }

You’ll notice your component passes handling of the authentication back to the high order component. This is a prime example of the benefits of high order components and composition in JavaScript.

Finally, create the render function that will make the decision about showing the login widget or, if the user is already logged in, redirecting them to the home page. You could also redirect the user to the page they were going to when they were redirected to the login page, but let’s skip that for now.

 render({location, auth}, {redirectToReferrer}) {
    let from;
    if (location && location.state) {
      from = location.state;
    } else {
      from = { pathname: '/' };
    }

    if (auth.isAuthenticated() || redirectToReferrer) {
      return <Redirect to={from} />;
    }

    return (
      <OktaSignInWidget
        widget={auth.widget}
        onSuccess={this.onSuccess}
        onError={this.onError} />
    );
  }

You’ll notice here that Preact is a little different in that it gives you handles to props and state as parameters to the render function. This code simply uses destructuring of those parameters to make using location, auth and redirectToReferrer simple without having a ton of this.props.{whatever}.

So your final /src/routes/login/index.js file will look like:

import { h, Component } from 'preact';
import Redirect from '../../lib/Redirect';
import OktaSignInWidget from '../../lib/OktaSignInWidget';
import { withAuth } from '../../lib/auth';

export default withAuth(class Login extends Component {
  state = {
    redirectToReferrer: false
  };

  componentWillMount() {
    this.onSuccess = this.onSuccess.bind(this);
    this.onError = this.onError.bind(this);
  }

  onSuccess(tokens) {
    this.props.auth.handleAuthentication(tokens);
    this.setState({
      redirectToReferrer: true
    });
  }

  onError(err) {
    console.log('error logging in', err);
  }

 render({location, auth}, {redirectToReferrer}) {
    let from;
    if (location && location.state) {
      from = location.state;
    } else {
      from = { pathname: '/' };
    }

    if (auth.isAuthenticated() || redirectToReferrer) {
      return <Redirect to={from} />;
    }

    return (
      <OktaSignInWidget
        widget={auth.widget}
        onSuccess={this.onSuccess}
        onError={this.onError} />
    );
  }
})

Update the Profile Page

Now that you have the Login component and it is using the Okta Sign-In Widget, use the auth component you created and update the profile page (in /src/routes/profile/index.js) to give you some more information about the user. This is what your final /src/routes/profile/index.js file should look like:

import { h, Component } from 'preact';
import { route } from 'preact-router';
import { withAuth } from '../../lib/auth';
import style from './style';

export default withAuth(class Profile extends Component {

  constructor(props){
    super(props);
  }

  componentWillMount(){
    if(this.props.auth.isAuthenticated()){
      this.state = {
        user: this.props.auth.getCurrentUser()
      };
    }else{
      return route('/login/');
    }
  }

  render(props, { user }) {
    return (
      user ?
      <div class={style.profile}>
        <h3 class={style.heading}>Profile</h3>
        <ul>
          <li>
            <span class={style.key}>Name:</span>
            <span class={style.value}>{user.claims.name}</span>
          </li>
          <li>
            <span class={style.key}>Email:</span>
            <span class={style.value}>{user.claims.email}</span>
          </li>
        </ul>
      </div> :
      null
    );
  }
})

You’ve added the authentication protection at the Component level in the componentWillMount function of the component. If the user is authenticated, it calls the getCurrentUser function on the high order component and adds the user to the component’s state. In the render function, you simply output the user’s name and email.

Update the Header Component

Now you just need to get the routes into your application and get the menu to link to them. Start by changing the /src/components/header/index.js file to:

import { h, Component } from 'preact';
import { Link } from 'preact-router/match';
import { withAuth } from '../../lib/auth';
import style from './style';

export default withAuth(class Header extends Component {

  componentWillMount(){
    if(this.props.auth.isAuthenticated()){
      this.setState({
          user: this.props.auth.getCurrentUser()
      });
    }
  }

  render(props, {user}) {
    return (
      <header class={style.header}>
        <h1>Preact App</h1>
        <nav>
          <Link activeClassName={style.active} href="/">Home</Link>
          {user ? <Link activeClassName={style.active} href="/profile">Profile</Link> : null }
          {user 
            ? <Link activeClassName={style.active} onClick={props.auth.logout.bind(null, props.history)} href="javascript:;">Logout</Link>
            : <Link activeClassName={style.active} onClick={props.auth.login.bind(null, props.history)} href="javascript:;">Login</Link>}         
        </nav>
      </header>
    );
  }
})

This will show the “Login” button if the user is not logged in and the “Logout” button if they are. It will also only show the “Profile” menu item to those users who are logged in.

Change Your Routing

Finally, change the routes in your /src/components/app.js file so that your application knows about your new routes and how to handle them. So your new app.js file will look like:

import { h, Component } from 'preact';
import { Router } from 'preact-router';

import Header from './header';
import Home from '../routes/home';
import Profile from '../routes/profile';
import Login from '../routes/Login';
// import Home from 'async!./home';
// import Profile from 'async!./profile';

export default class App extends Component {
  /** Gets fired when the route changes.
   *  @param {Object} event   "change" event from [preact-router](http://git.io/preact-router)
   *  @param {string} event.url The newly routed URL
   */
  handleRoute = e => {
    this.currentUrl = e.url;
  };

  render() {
    return (
      <div id="app">
        <Header />
        <Router onChange={this.handleRoute}>
          <Home path="/" />
          <Profile path="/profile/" />
          <Login path="/login/" />
        </Router>
      </div>
    );
  }
}

All that really changed is that you imported the newly created Login component and remove the user property being passed into the Profile component and added a new route for the Login component.

Run Your New Preact Application!

You should now be able to save your work and run npm start in the root folder and see a fully-functioning Preact application with user authentication via Okta!

There are a lot of similarities between Preact and React, but there are some key differences. Preact is meant for applications where keeping the size of the download small is critical. There are some nice conveniences in the Preact router, but there are some things missing (like withRouter). There are also some neat conveniences, like having props and state passed to the render function. All in all, I think Preact is neat, but I could see really needing a full-fledged React for complex apps.

Learn More

You can find out more about Preact from their website and Preact-Router from the Github repository.

You can also get the complete code for this article from the Okta Developer Github repository.

As always, if you have any questions, comments or concerns about the article, the code, Preact or Okta, feel free to reach out to me via email, or hit me up in the comments or via Twitter @leebrandt.

If you’re interested in learning more about authentication using the Okta Sign-In Widget with Angular, you can follow Matt Raible’s posts at https://developer.okta.com/blog/2017/03/27/angular-okta-sign-in-widget or https://developer.okta.com/blog/2017/06/13/add-authentication-angular-pwa, and If you want to know more about Okta’s Identity Platform, read Randall Degges post at https://developer.okta.com/blog/2017/08/29/meet-the-new-okta-identity-platform.

Source:: scotch.io

Processing Incoming Request Data in Flask

By Anthony Herbert

In any web app, you’ll have to process incoming request data from users. Flask, like any other web framework, allows you to access the request data easily.

In this tutorial, we’ll go through how to process incoming data for the most common use cases. The forms of incoming data we’ll cover are: query strings, form data, and JSON objects. To demonstrate these cases, we’ll build a simple example app with three routes that accept either query string data, form data, or JSON data.

The Request Object

To access the incoming data in Flask, you have to use the request object. The request object holds all incoming data from the request, which includes the mimetype, referrer, IP address, raw data, HTTP method, and headers, among other things. Although all the information the request object holds can be useful, in this article, we’ll only focus on the data that is normally directly supplied by the caller of our endpoint.

To gain access to the request object in Flask, you simply import it from the Flask library.

from flask import request

You then have the ability to use it in any of your view functions.

Once we get to the section on query strings, you’ll get to see the request object in action.

The Example App

To demonstrate the different ways of using request, we’ll start with a simple Flask app. Even though the example app uses a simple organization layout for the view functions and routes, what you learn in this tutorial can be applied to any method of organizing your views like class-based views, blueprints, or an extension like Flask-Via.

To get started, first we need to install Flask.

pip install Flask

Then, we can start with the following code.

#app.py

from flask import Flask, request #import main Flask class and request object

app = Flask(__name__) #create the Flask app

@app.route('/query-example')
def query_example():
    return 'Todo...'

@app.route('/form-example')
def form_example():
    return 'Todo...'

@app.route('/json-example')
def json_example():
    return 'Todo...'

if __name__ == '__main__':
    app.run(debug=True, port=5000) #run app in debug mode on port 5000

Start the app with:

python app.py

The code supplied sets up three routes with a message telling us ‘Todo…’. The app will start on port 5000, so you can view each route in your browser with the following links:

http://127.0.0.1:5000/query-example (or localhost:5000/query-example)
http://127.0.0.1:5000/form-example (or localhost:5000/form-example)
http://127.0.0.1:5000/json-example (or localhost:5000/json-example)

For each of the three routes, you’ll see the same thing:

Query Arguments

URL arguments that you add to a query string are the simpliest way to pass data to a web app, so let’s start with them.

A query string looks like the following:

example.com?arg1=value1&arg2=value2

The query string begins after the question mark (?) and has two key-value pairs separated by an ampersand (&). For each pair, the key is followed by an equals sign (=) and then the value. Even if you’ve never heard of a query string until now, you have definitely seen them all over the web.

So in that example, the app receives:

arg1 : value1
arg2 : value2

Query strings are useful for passing data that doesn’t require the user to take action. You could generate a query string somewhere in your app and append it a URL so when a user makes a request, the data is automatically passed for them. A query string can also be generated by forms that have GET as the method.

To create our own query string on the query-example route, we’ll start with this simple one:

http://127.0.0.1:5000/query-example?language=Python

If you run the app and navigate to that URL, you’ll see that nothing has changed. That’s only because we haven’t handled the query arguments yet.

To do so, we’ll need to read in the language key by using either request.args.get('language') or request.args['language'].

By calling request.args.get('language'), our application will continue to run if the language key doesn’t exist in the URL. In that case, the result of the method will be None. If we use request.args['language'], the app will return a 400 error if language key doesn’t exist in the URL. For query strings, I recommend using request.args.get() because of how easy it is for the user to modify the URL. If they remove one of the keys, request.args.get() will prevent the app from failing.

Let’s read the language key and display it as output. Modify with query-example route the following code.

@app.route('/query-example')
def query_example():
    language = request.args.get('language') #if key doesn't exist, returns None

    return '''<h1>The language value is: {}</h1>'''.format(language)

Then run the app and navigate to the URL.

As you can see, the argument from the URL gets assigned to the language variable and then gets returned to the browser. In a real app, you’d probably want to do something with the data other than simply return it.

To add more query string parameters, we just append ampersands and the new key-value pairs to the end of the URL. So an additional pair would look like this:

http://127.0.0.1:5000/query-example?language=Python&framework=Flask

With the new pair being:

framework : Flask

And if you want more, continue adding ampersands and key-value pairs. Here’s an example:

http://127.0.0.1:5000/query-example?language=Python&framework=Flask&website=Scotch

To gain access to those values, we still use either request.args.get() or request.args[]. Let’s use both to demonstrate what happens when there’s a missing key. We’ll assign the value of the results to variables and then display them.

@app.route('/query-example')
def query_example():
    language = request.args.get('language') #if key doesn't exist, returns None
    framework = request.args['framework'] #if key doesn't exist, returns a 400, bad request error
    website = request.args.get('website')

    return '''<h1>The language value is: {}</h1>
              <h1>The framework value is: {}</h1>
              <h1>The website value is: {}'''.format(language, framework, website)

When you run that, you should see:

If you remove the language from the URL, then you’ll see that the value ends up as None.

If you remove the framework key, you get an error.

Now that you undertand query strings, let’s move on to the next type of incoming data.

Form Data

Next we have form data. Form data comes from a form that has been sent as a POST request to a route. So instead of seeing the data in the URL (except for cases when the form is submitted with a GET request), the form data will be passed to the app behind the scenes. Even though you can’t easily see the form data that gets passed, your app can still read it.

To demonstrate this, modify the form-example route to accept both GET and POST requests and to return a simple form.

@app.route('/form-example', methods=['GET', 'POST']) #allow both GET and POST requests
def form_example():
    return '''<form method="POST">
                  Language: <input type="text" name="language"><br>
                  Framework: <input type="text" name="framework"><br>
                  <input type="submit" value="Submit"><br>
              </form>'''

Running the app results in this:

The most important thing to know about this form is that it performs a POST request to the same route that generated the form. The keys that we’ll read in our app all come from the “name” attributes on our form inputs. In our case, language and framework are the names of the inputs, so we’ll have access to those in our app.

Inside the view function, we need to check if the request method is GET or POST. If it’s GET, we simply display the form we have. If it’s POST, then we want to process the incoming data.

To do that, let’s add a simple if statement that checks for a POST request. If the request method isn’t POST, then we know it’s GET, because our route only allows those two types of requests. For GET requests, the form will be generated.

@app.route('/form-example', methods=['GET', 'POST']) #allow both GET and POST requests
def form_example():
    if request.method == 'POST': #this block is only entered when the form is submitted
        return 'Submitted form.'

    return '''<form method="POST">
                  Language: <input type="text" name="language"><br>
                  Framework: <input type="text" name="framework"><br>
                  <input type="submit" value="Submit"><br>
              </form>'''

Inside of the block, we’ll read the incoming values with request.args.get('language') and request.form['framework']. Remember that if we have more inputs, then we can read additional data.

Add the additional code to the form-example route.

@app.route('/form-example', methods=['GET', 'POST']) #allow both GET and POST requests
def form_example():
    if request.method == 'POST':  #this block is only entered when the form is submitted
        language = request.form.get('language')
        framework = request.form['framework']

        return '''<h1>The language value is: {}</h1>
                  <h1>The framework value is: {}</h1>'''.format(language, framework)

    return '''<form method="POST">
                  Language: <input type="text" name="language"><br>
                  Framework: <input type="text" name="framework"><br>
                  <input type="submit" value="Submit"><br>
              </form>'''

Try running the app and submitting the form.

Similiar to the query string example before, we can use request.form.get() instead of referencing the key directly with request.form[]. request.form.get() returns None instead of causing a 400 error when the key isn’t found.

As you can see, handling submitted form data is just as easy as handling query string arguments.

JSON Data

Finally, we have JSON data. Like form data, it’s not so easy to see. JSON data is normally constructed by a process that calls our route. An example JSON object looks like this:

{
    "language" : "Python",
    "framework" : "Flask",
    "website" : "Scotch",
    "version_info" : {
        "python" : 3.4,
        "flask" : 0.12
    },
    "examples" : ["query", "form", "json"],
    "boolean_test" : true
}

As you can see with JSON, you can pass much more complicated data that you could with query strings or form data. In the example, you see nested JSON objects and an array of items. With Flask, reading all of these values is straightforward.

First, to send a JSON object, we’ll need a program capable of sending custom requests to URLs. For this, we can use an app called Postman.

Before we use Postman though, change the method on the route to accept only POST requests.

@app.route('/json-example', methods=['POST']) #GET requests will be blocked
def json_example():
    return 'Todo...'

Then in Postman, let’s do a little set up to enable sending POST requests.

In Postman, add the URL and change the type to POST. On the body tab, change to raw and select JSON (application/json) from the drop down. All this is done so Postman can send JSON data properly and so your Flask app will understand that it’s receiving JSON.

From there, you can copy the example into the text input. It should look like this:

To test, just send the request and you should get ‘Todo…’ as the response because we haven’t modified our function yet.

To read the data, first you must understand how Flask translates JSON data into Python data structures.

Anything that is an object gets converted to a Python dict. {"key" : "value"} in JSON corresponds to somedict['key'], which returns a value in Python.

An array in JSON gets converted to a list in Python. Since the syntax is the same, here’s an example list: [1,2,3,4,5]

Then the values inside of quotes in the JSON object become strings in Python. true and false become True and False in Python. Finally, numbers without quotes around them become numbers in Python.

Now let’s get on to reading the incoming JSON data.

First, let’s assign everything from the JSON object into a variable using request.get_json().

req_data = request.get_json()

request.get_json() converts the JSON object into Python data for us. Let’s assign the incoming request data to variables and return them by making the following changes to our json-example route.

@app.route('/json-example', methods=['POST']) #GET requests will be blocked
def json_example():
    req_data = request.get_json()

    language = req_data['language']
    framework = req_data['framework']
    python_version = req_data['version_info']['python'] #two keys are needed because of the nested object
    example = req_data['examples'][0] #an index is needed because of the array
    boolean_test = req_data['boolean_test']

    return '''
           The language value is: {}
           The framework value is: {}
           The Python version is: {}
           The item at index 0 in the example list is: {}
           The boolean value is: {}'''.format(language, framework, python_version, example, boolean_test)

If we run our app and submit the same request using Postman, we will get this:

Note how you access elements that aren’t at the top level. ['version']['python'] is used because you are entering a nested object. And ['examples'][0] is used to access the 0th index in the examples array.

If the JSON object sent with the request doesn’t have a key that is accessed in your view function, then the request will fail. If you don’t want it to fail when a key doesn’t exist, you’ll have to check if the key exists before trying to access it. Here’s an example:

language = None
if 'language' in req_data:
    language = req_data['language']

Conclusion

You should now understand how to use the request object in Flask to get the most common forms of input data. To recap, we covered:

  • Query Strings
  • Form Data
  • JSON Data

With this knowledge, you’ll have no problem with any data that users throw at your app!

Learn More

If you like this tutorial and want to learn more about Flask from me, check out my Flask for Beginners video course at my site Pretty Printed, which takes you from knowing nothing about Flask to building three apps. If that course isn’t at your level, then I have other courses on my site that may interest you as well.

Source:: scotch.io