Build a React Native App and Authenticate with OAuth 2.0

By Matt Raible

Open in Expo

With Okta and OpenID Connect (OIDC) you can easily integrate authentication into a React Native application and never have to build it yourself again. OIDC allows you to authenticate directly against the Okta API, and this article shows you how to do just that in a React Native application. I’ll demonstrate you how to log in with OIDC redirect, using AppAuth.

React Native is a pretty slick framework. Unlike Ionic and other hybrid mobile frameworks, it allows you to use web technologies (React and JavaScript) to build native mobile apps. There is no browser or WebView involved, so developing a mobile app with React Native is similar to using the native SDK, in that you’ll do all your testing on an emulator or device. There is no way to test it in your browser like there is with Ionic. This can be a benefit in that you don’t have to write code that works in-browser and on-device separately.

Today I’m going to show you how to develop a React Native app with the latest and greatest releases. At the time of this writing, that’s React 16.2.0 and React Native 0.52.2. You’ll create a new app, add AppAuth for authentication, authenticate with Okta, and see it running on both iOS and Android.

AppAuth is a client SDK for native apps to authenticate and authorize end-users using OAuth 2.0 and OpenID Connect. Available for iOS, macOS, Android and Native JS environments, it implements modern security and usability best practices for native app authentication and authorization.

Create Your React Native Application

React has a create-react-app command-line tool (CLI) that you can use to create new React apps. React Native has a similar tool called Create React Native App. Before you install it, make sure you have Node v6 or later installed.

Install create-react-native-app and create a new project called okta-rn:

npm install -g create-react-native-app
create-react-native-app okta-rn
cd okta-rn
npm start

This will result your terminal prompting you with some options:

To view your app with live reloading, point the Expo app to this QR code.
You'll find the QR scanner on the Projects tab of the app.

[QR Code]

Or enter this address in the Expo app's search bar:

 exp://172.31.98.12:19000

Your phone will need to be on the same local network as this computer.
For links to install the Expo app, please visit https://expo.io.

Logs from serving your app will appear here. Press Ctrl+C at any time to stop.

› Press a to open Android device or emulator, or i to open iOS emulator.
› Press q to display QR code.
› Press r to restart packager, or R to restart packager and clear cache.
› Press d to toggle development mode. (current mode: development)

If you’re on a Mac, press i to open iOS emulator. You will be prompted to install/open with Expo, then presented with the rendered App.js.

Rendered App.js

If you’re on Windows or Linux, I’d suggest trying the Android emulator or your Android device (if you have one). If it doesn’t work, don’t worry, I’ll show you how to make that work later on.

TIP: You can use TypeScript instead of JavaScript in your React Native app using Microsoft’s TypeScript React Native Starter. If you decide to go this route, I’d recommend following the steps to convert your app after you’ve completed this tutorial.

React Native and OAuth 2.0

In this example, I’ll use React Native App Auth, a library created by Formidable. The reason I’m using this library is three-fold: 1) they provide a nice example that I was able to make work in just a few minutes, 2) it uses AppAuth (a mature OAuth client implementation), and 3) I was unable to get anything else working.

  • I tried react-native-oauth, but discovered it required using an existing provider before adding a new one. I only wanted to have Okta as a provider. Also, it’s high number of issues and pull requests served as a warning sign.
  • I tried react-native-simple-auth, but had issues getting the deprecated Navigator component to work with the latest React Native release.
  • I tried doing this OAuth 2 with React Native tutorial, but also had problems redirecting back to my app.

Create Native Application in Okta

Before you add AppAuth to your React Native application, you’ll need an application to authorize against. If you don’t have a free-forever Okta Developer account, get one today!

Log in to your Okta Developer account and navigate to Applications > Add Application. Click Native and click Next. Give the app a name you’ll remember (e.g., React Native), select Refresh Token as a grant type, in addition to the default Authorization Code. Copy the Login redirect URI (e.g., com.oktapreview.dev-158606:/callback) and save it somewhere. You’ll need this value when configuring your app.

Click Done and you should see a client ID on the next screen. Copy and save this value as well.

Add React Native AppAuth for Authentication

You’ll need to “eject” the native configuration for your app, which is normally hidden by create-react-native-app.

npm run eject

When prompted to answer questions, use the following answers:

Question Answer
What should your app appear as on a user’s home screen? Okta RN
What should your Android Studio and Xcode projects be called? OktaRN

To install App Auth for React Native, run the following commands:

npm i react-native-app-auth@1.0.1 --save
react-native link

TIP: If you see a “Command link unrecognized” error, run npm i && react-native link.

After running these commands, you have to configure the native iOS and Android projects. I’ve copied the steps below for your convenience.

iOS Setup

React Native App Auth depends on AppAuth-ios, so you have to configure it as a dependency. The easiest way to do that is to use CocoaPods. To install CocoaPods, run the following command:

sudo gem install cocoapods

Create a Podfile in the ios directory of your project that specifies AppAuth-ios as a dependency. Make sure that OktaRN matches the app name you specified when running npm run eject.

platform :ios, '11.0'

target 'OktaRN' do
 pod 'AppAuth', '>= 0.91'
end

Then run pod install from the ios directory. This can take a while the first time, even on a fast connection. Now is a good time to grab a coffee, or a scotch!

Open your project in Xcode by running open OktaRN.xcworkspace from the ios directory.

If you intend to support iOS 10 and older, you need to define the supported redirect URL schemes in ios/OktaRN/Info.plist as follows:

<key>CFBundleURLTypes</key>
<array>
 <dict>
   <key>CFBundleURLName</key>
   <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
   <key>CFBundleURLSchemes</key>
   <array>
     <string>{yourReversedOktaDomain}</string>
   </array>
 </dict>
</array>

Below is what mine looks like after I changed my app identifier and added this key.

<key>CFBundleIdentifier</key>
<string>com.okta.developer.reactnative.$(PRODUCT_NAME:rfc1034identifier)</string>
<key>CFBundleURLTypes</key>
<array>
 <dict>
   <key>CFBundleURLName</key>
   <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
   <key>CFBundleURLSchemes</key>
   <array>
     <string>com.oktapreview.dev-158606</string>
   </array>
 </dict>
</array>

Open AppDelegate.h in your Xcode project (OktaRN > OktaRN > AppDelegate.h) and add the lines with the + next to them below.

+ @protocol OIDAuthorizationFlowSession;

 @interface AppDelegate : UIResponder <UIApplicationDelegate>
+ @property(nonatomic, strong, nullable) id<OIDAuthorizationFlowSession> currentAuthorizationFlow;
 @property (nonatomic, strong) UIWindow *window;
 @end

This property holds the authorization flow information that started before you redirect to Okta. After Okta authorizes you, it redirects to the redirect_uri that’s passed in.

The authorization flow starts from an openURL() app delegate method. To add it, open AppDelegate.m and import AppAuth.h.

#import "AppAuth.h"

Then at the bottom of the class (before @end), add the openURL() method.

- (BOOL)application:(UIApplication *)app
           openURL:(NSURL *)url
           options:(NSDictionary<NSString *, id> *)options {
 if ([_currentAuthorizationFlow resumeAuthorizationFlowWithURL:url]) {
   _currentAuthorizationFlow = nil;
   return YES;
 }
 return NO;
}

Android Setup

Setting up Android is quite a bit easier. React Native App Auth for Android depends on AppAuth-android, but you need to add the correct Android Support library version to your project.

Add the Google Maven repository to your android/build.gradle and upgrade the Android Tools dependency:

buildscript {
   repositories {
       jcenter()
       google()
   }
   dependencies {
       classpath 'com.android.tools.build:gradle:3.0.1'
   }
}

Upgrade the appcompat dependency in android/app/build.gradle to 25.3.1 to match the one expected by AppAuth.

dependencies {
 compile "com.android.support:appcompat-v7:25.3.1"
}

Remove buildToolsVersion "23.0.1" as its no longer necessary.

Update the compileSdkVersion:

android {
 compileSdkVersion 25
}

Add the appAuthRedirectScheme property the defaultConfig in android/app/build.gradle:

android {
 defaultConfig {
   ...
   manifestPlaceholders = [
     appAuthRedirectScheme: '{yourReversedOktaDomain}'
   ]
 }
}

After making this change, my defaultConfig looks as follows.

defaultConfig {
   applicationId "com.oktarn"
   minSdkVersion 16
   targetSdkVersion 22
   versionCode 1
   versionName "1.0"
   ndk {
       abiFilters "armeabi-v7a", "x86"
   }
   manifestPlaceholders = [
       appAuthRedirectScheme: 'com.oktapreview.dev-158606'
   ]
}

Build Your React Native App

Replace the code in App.js with the following JavaScript. This code allows you to authorize, refresh your access token, and revoke it.

import React, { Component } from 'react';
import { UIManager, LayoutAnimation } from 'react-native';
import AppAuth from 'react-native-app-auth';
import { Page, Button, ButtonContainer, Form, Heading } from './components';

UIManager.setLayoutAnimationEnabledExperimental &&
UIManager.setLayoutAnimationEnabledExperimental(true);

const scopes = ['openid', 'profile', 'email', 'offline_access'];

type State = {
 hasLoggedInOnce: boolean,
 accessToken: ?string,
 accessTokenExpirationDate: ?string,
 refreshToken: ?string
};

export default class App extends Component<{}, State> {
 auth = new AppAuth({
   issuer: 'https://{yourOktaDomain}.com/oauth2/default',
   clientId: '{clientId}',
   redirectUrl: 'com.{yourReversedOktaDomain}:/callback'
 });

 state = {
   hasLoggedInOnce: false,
   accessToken: '',
   accessTokenExpirationDate: '',
   refreshToken: ''
 };

 animateState(nextState: $Shape<State>, delay: number = 0) {
   setTimeout(() => {
     this.setState(() => {
       LayoutAnimation.easeInEaseOut();
       return nextState;
     });
   }, delay);
 }

 authorize = async () => {
   try {
     const authState = await this.auth.authorize(scopes);
     this.animateState(
       {
         hasLoggedInOnce: true,
         accessToken: authState.accessToken,
         accessTokenExpirationDate: authState.accessTokenExpirationDate,
         refreshToken: authState.refreshToken
       },
       500
     );
   } catch (error) {
     console.error(error);
   }
 };

 refresh = async () => {
   try {
     const authState = await this.auth.refresh(this.state.refreshToken, scopes);
     this.animateState({
       accessToken: authState.accessToken || this.state.accessToken,
       accessTokenExpirationDate:
       authState.accessTokenExpirationDate || this.state.accessTokenExpirationDate,
       refreshToken: authState.refreshToken || this.state.refreshToken
     });
   } catch (error) {
     console.error(error);
   }
 };

 revoke = async () => {
   try {
     await this.auth.revokeToken(this.state.accessToken);
     this.animateState({
       accessToken: '',
       accessTokenExpirationDate: '',
       refreshToken: ''
     });
   } catch (error) {
     console.error(error);
   }
 };

 render() {
   const {state} = this;
   return (
     <Page>
       {!!state.accessToken ? (
         <Form>
           <Form.Label>accessToken</Form.Label>
           <Form.Value>{state.accessToken}</Form.Value>
           <Form.Label>accessTokenExpirationDate</Form.Label>
           <Form.Value>{state.accessTokenExpirationDate}</Form.Value>
           <Form.Label>refreshToken</Form.Label>
           <Form.Value>{state.refreshToken}</Form.Value>
         </Form>
       ) : (
         <Heading>{state.hasLoggedInOnce ? 'Goodbye.' : 'Hello, stranger.'}</Heading>
       )}

       <ButtonContainer>
         {!state.accessToken && (
           <Button onPress={this.authorize} text="Authorize" color="#017CC0"/>
         )}
         {!!state.refreshToken && <Button onPress={this.refresh} text="Refresh" color="#24C2CB"/>}
         {!!state.accessToken && <Button onPress={this.revoke} text="Revoke" color="#EF525B"/>}
       </ButtonContainer>
     </Page>
   );
 }
}

Make sure to adjust the initialization of AppAuth with your settings.

auth = new AppAuth({
   issuer: 'https://{yourOktaDomain}.com/oauth2/default',
   clientId: '{clientId}',
   redirectUrl: 'com.{yourReversedOktaDomain}:/callback '
});

Change index.js to use OktaRN as the name of your app.

AppRegistry.registerComponent('OktaRN', () => App);

This code uses styled-components, so you’ll need to install that as a dependency.

npm i styled-components --save

Then copy the components directory into your project’s root directory from Formidable’s example.

svn export https://github.com/FormidableLabs/react-native-app-auth/trunk/Example/components

Grab the background image that’s referenced in the Page.js component too.

svn export https://github.com/FormidableLabs/react-native-app-auth/trunk/Example/assets

Run on iOS Simulator

Run your app with npm run ios.

You should see a screen that says “Hello, stranger.” Click on Authorize and you’ll be prompted to continue or cancel.

Hello, stranger Cancel or Continue

Click Continue and you should see an Okta sign-in form. Enter your credentials and you’ll be redirected back to the application.

Okta Sign-In Access Token Info

You can click Refresh to watch the values for the access token and expire date change.

TIP: If animations happen slowly in iOS Simulator, toggle Debug > Slow Animations.

Run on Android

To try it on an Android emulator, run npm run android. If you don’t have a phone plugged in or an Android Virtual Device (AVD) created, you’ll see an error:

* What went wrong:
Execution failed for task ':app:installDebug'.
> com.android.builder.testing.api.DeviceException: No connected devices!

To fix this, open Android Studio, choose open existing project, and select the android directory in your project. If you’re prompted to update anything, approve it.

If you get an error Could not find method google(), edit build.gradle to remove this line, then reload the project.

To create a new AVD, navigate to Tools > Android > AVD Manager. Create a new Virtual Device and click Play. I chose a Pixel 2 as you can see from my settings below.

AVD Pixel 2

Modify android/build.gradle to add google() back in, then run npm run android again. You should see a welcome screen and be able to authorize successfully.

Hello, stranger Okta Sign-In Access Token on Android

Upgrade to the Latest Release of React Native

The react-native-git-upgrade tool is a handy way to upgrade your project to use the latest versions. Install it and run it.

npm i -g react-native-git-upgrade
react-native-git-upgrade
npm i

Or, you can just change your package.json to have react-native": "0.52.2 and then run npm i.

Get and View an ID Token

If you’d like to get an ID token in addition to an access token, add idToken as a property of type State and the state variable in App.js.

type State = {
 ...
 idToken: ?string
};

export default class App extends Component<{}, State> {
 ...
 state = {
   ...
   idToken: ''
 };

Then update the authorize() method to set the property from authState. You’ll want to do add similar logic in the refresh() and revoke() methods.

authorize = async () => {
 try {
   const authState = await this.auth.authorize(scopes);
   this.animateState(
     {
       hasLoggedInOnce: true,
       accessToken: authState.accessToken,
       accessTokenExpirationDate: authState.accessTokenExpirationDate,
       refreshToken: authState.refreshToken,
       idToken: authState.idToken
     },
     500
   );
 } catch (error) {
   console.error(error);
 }
};

To see what’s in your ID token, install buffer.

npm i buffer --save

Import it at the top of App.js.

import { Buffer } from 'buffer';

Then change the render() method to decode it.

render() {
 const {state} = this;
 if (state.idToken) {
   const jwtBody = state.idToken.split('.')[1];
   const base64 = jwtBody.replace('-', '+').replace('_', '/');
   const decodedJwt = Buffer.from(base64, 'base64');
   state.idTokenJSON = JSON.parse(decodedJwt);
 }
 ...

Finally, add a

and row after the one that displays the access token.

<Form.Label>ID Token</Form.Label>
<Form.Value>{JSON.stringify(state.idTokenJSON)}</Form.Value>

NOTE: There’s a bug in react-native-app-auth that prevents this from working on Android.

Run npm run ios and you should see the claims in the ID token after authorizing with Okta.

ID Token on iOS

Call an API with Your Access Token

Now that you have an access token, what can you do with it? You can call an Okta-protected API with it in an Authorization header!

I wrote about how to create a “Good Beers” API in Bootiful Development with Spring Boot and React. You can use the backend of that application to prove it works.

Clone the project from GitHub and checkout the okta branch.

git clone https://github.com/oktadeveloper/spring-boot-react-example.git
git checkout okta

Modify spring-boot-react-example/server/src/main/resources/application.properties to set the issuer and clientId.

okta.oauth2.issuer=https://{yourOktaDomain}.com/oauth2/default
okta.oauth2.clientId={clientId}

NOTE: You’ll need to have Java 8 installed to run this Spring Boot application.

Start the app by running ./mvnw from the server directory.

Back to the React Native client. In App.js, add beers as a property of state.

state = {
 ...
 beers: []
};

Set it to this same value in the revoke() method. Add a fetchGoodBeers() method that uses the access token to call the backend.

fetchGoodBeers = async () => {
 if (this.state.beers.length) {
   // reset to id token if beers is already populated
   this.animateState({beers: []})
 } else {
   fetch('http://localhost:8080/good-beers', {
     headers: {
       'Authorization': `Bearer ${this.state.accessToken}`
     }
   }).then(response => response.json())
     .then(data => {
       this.animateState({beers: data})
     })
     .catch(error => console.error(error));
 }
};

TIP: For this to work in the Android emulator (and on a real phone), you’ll need to change localhost to your IP address.

In the at the bottom, add a “Good Beers” button that allows you to call the API, as well as press it again to view the ID Token.

{!!state.accessToken && <Button onPress={this.fetchGoodBeers} text={!this.state.beers.length ? 'Good Beers' : 'ID Token'} color="#008000" />}

Modify the row where you display the ID token to show the JSON from the API.

<Form.Label>{state.beers.length ? 'Good Beers' : 'ID Token'}</Form.Label>
<Form.Value>{JSON.stringify(state.beers.length ? state.beers : state.idTokenJSON)}</Form.Value>

In iOS Simulator, press Command + R (on Mac, CTRL + R on others)to reload everything and you should see the JSON when you click on the Good Beers button. You can reload in Android using Command + M (on Mac, CTRL + M on other operating systems).

Good Beers on iOS Good Beers on Android

Learn More about React Native and React

I hope you’ve enjoyed this whirlwind tour of how to do authentication with Okta and React Native. You can learn more about React Native on its official site. You can also add to its ~60K stars on GitHub.

You can find the source code for this application at https://github.com/oktadeveloper/okta-react-native-app-auth-example.

If you’re interested in seeing how to do regular React development with Okta, I encourage you to check out the following resources:

If you have any questions about this article, please hit me up on Twitter @mraible.

Source:: scotch.io

Object Oriented Programming in JavaScript

By Zell Liew

Object-Oriented Programming is a popular style of programming that has taken root in JavaScript since the beginning.

It’s so deeply rooted in JavaScript that many of JavaScript’s native functions and methods are written in the Object Oriented style; you’ll also find many popular libraries written in the Object Oriented style as well.

If you already have prior experience with Object Oriented Programming in another language, please put aside the knowledge you know, and read through the entire module with a beginner’s mind.

This is because Object Oriented Programming in JavaScript is very different from Object-Oriented Programming in other languages. If you hold on to your current ideas, you might make Object Oriented Programming in JavaScript exponentially more difficult than it is.

Now, let’s begin by finding out what Object Oriented Programming is about.

Object-Oriented Programming is about two things:

  1. Creating individual objects from a common object
  2. Inheritance

For this article, we’ll only cover the first part. We’ll look at inheritance in another article.

Creating Objects From A Common Object

You know that objects in JavaScript have properties and methods. These objects can resemble real-life things (even people!).

Let’s say you’re trying to construct a Human object in JavaScript. A human has a firstName, lastName and an age. You could add these attributes as properties in JavaScript.

In addition to having names and ages, humans can also say their name. You can write a sayName function as a method in the human object as well.

const human = {
  firstName: 'Zell'
  lastName: 'Liew',
  age: 29,
  sayName () {
    console.log(`I am Zell Liew`)
  }
}

human.sayName() // I am Zell Liew

Since humans are very similar to each other, you can also create another human object with the same properties (firstName, lastName, age ) and methods (sayName).

Unfortunately, you can’t call it human anymore because the human variable is taken up.

const human2 = {
  firstName: 'Vincy',
  lastName: 'Zhang',
  age: 28,
  sayName () {
    console.log(`I am Vincy Zhang`)
  }
}

Assuming you know Vincy, it’s kinda weird to call her human2, right? You’ll probably call her Vincy instead.

So, instead of naming our human objects human and human2, it makes more sense to call them Zell and Vincy.

const Zell = {
  firstName: 'Zell'
  lastName: 'Liew',
  age: 29,
  sayName () {
    console.log(`I am Zell Liew`)
  }
}

const Vincy = {
  firstName: 'Vincy',
  lastName: 'Zhang',
  age: 28,
  sayName () {
    console.log(`I am Vincy Zhang`)
  }
}

There we go, much better.

Now, what if you need to create another human? You’ll have to write the entire object from scratch, but that’s a chore, right? You’re copy-pasting so much code!

// Ugh, creating another human by writing a new object
const Nicolas = {
  firstName: 'Nicolas',
  lastName: 'Tze',
  age: 30,
  sayName () {
    console.log(`I am Nicolas Tze`)
  }
}

At this point, you’ll notice that human are slightly different from each other—we have different names, and we’re of different ages.

But we do have a common point—we can say our name.

Wouldn’t it be nice if you could create a function (or something similar) that makes individuals?

Turns out, you can! All you need to do is to construct a function that has a this keyword, and you can create individuals with a new keyword.

Here’s what it looks like:

function Human (firstName, lastName, age) {
  // Note: Don't worry about 'this' yet. You'll understand it later. Follow along for now.
  this.firstName = firstName
  this.lastName = lastName
  this.age = age

  this.sayName = function () {
    console.log(`I am ${firstName} ${lastName}`)
  }
}
// Creating a new person with the `new` keyword
const zell = new Human('Zell', 'Liew', 29)

If you console.log(zell), you’ll see that he’s a human with a firstName, a lastName, an age and he has the ability to sayName.

The created human has firstName, lastName and age properties. It also has a sayName method.

From this point onwards, you can create any number of humans you want with the same syntax. Each person you create will retain their individuality, and they will all be able to say their name!

const vincy = new Human('Vincy', 'Zhang', 28)
const nicolas = new Human('Nicolas', 'Tze', 30)

vincy.sayName() // I am Vincy Zhang
nicolas.sayName() // I am Nicolas Tze

Cool, isn’t it?

And that’s what the object-construction part of Object Oriented Programming is in a nutshell—you construct a function (Human) that can create instances (people like zell, vincy and nicolas). Each instance you create needs to be able to contain individual data that are different from other instances.

The function you use to construct instances is called the constructor.

Naming constructors and instances

In Object Oriented Programming, the first letter of the constructor is capitalized (Human), while each instance is written like a normal variable (zell, vincy, nicolas).

This small differentiation instantly shows you the difference between constructors and instances in your code.

What’s “this”?

this is a keyword in JavaScript. When it is used in a constructor, it refers to the instance that is created with the constructor.

If you tried to console.log(this) in a constructor, you’d notice its the same as logging the instance itself.

function Human (firstName, lastName, age) {
  // Other properties and methods
  console.log(this)
}

const zell = new Human('Zell', 'Liew', 29)


this in a constructor points to the instance

this is a very important concept in Object Oriented Programming. So you need to be familiar with it. Here’s an article that explains this in detail.

Wrapping up

One of the main parts of Object Oriented Programming is about creating instances from constructors. Each instance you create should retain its individuality, so they’re different from other instances.

When you create a constructor, you should capitalize the first letter of its name (like Human) to differentiate it from instances (like zell).

If you loved this article, you’d love Learn JavaScript—a course that helps you learn to build real components from scratch with Javascript.

Source:: scotch.io

Event sourcing vs CRUD

By Golo Roden

Event sourcing vs CRUD

Event sourcing is gaining more and more attention. This is partly due to the increasing interest in domain-driven design (DDD) and CQRS, to which event sourcing fits well in conceptual terms. But what else is it suitable for? And where does it not fit? In order to be able to answer the question of when event sourcing or CRUD is the more appropriate approach, it is advisable to clarify first of all what exactly event sourcing is – and what it is not.

In many cases event sourcing is combined with domain-driven design (DDD) and the design pattern CQRS, but it is only partly related to the two concepts. Event sourcing is a specific procedure for storing data. Unlike the traditional approach with a relational database, event sourcing does not persist the current state of a record, but instead stores the individual changes as a series of deltas that led to the current state over time.

Determining the current state

The procedure is similar to the way a bank manages an account, for example. The bank does not save the current balance. Instead, it records the deposits and withdrawals that occur over time. The current balance can then be calculated from this data: if the account was first opened with a deposit of 500 EUR, then another 200 EUR were added, and then 300 EUR were debited, the following calculation takes place:

  500 (deposit)
+ 200 (deposit)
- 300 (payment)
  ---
= 400 (balance)

The current account balance is 400 EUR. The procedure can be continued over an arbitrary period of time, only the number of summands grows gradually. If domain-related facts that contain certain semantics (the so-called events) are stored instead of simple numbers, any process can be mapped.

Restoring the current state by playing back the individual events is called replay. As a special feature of event sourcing, it is not only possible to determine the current state, but also any state from the past. To do this, it is only necessary to stop the replay at the desired time in the past and not to play back the events completely. It is also possible to determine the historical development of the state, which provides an easy way for time series analysis and other evaluations of historical data.

Optimizing performance

Unfortunately, a replay becomes more and more complex as the number of events that need to be replayed increases. At first glance, the use of event sourcing seems to lead to read accesses becoming increasingly slow. However, it is easy to find a way out of the problem.

Since events are always only added at the end of the existing list and existing events are never changed, a replay calculated once will always produce the very same result for a certain point in time. If you try to follow the analogy with account management, this is obvious: the account balance at a given point in time is always the same, regardless of whether there were any deposits or withdrawals afterwards.

You can take advantage of this situation by saving the currently calculated state as a so-called snapshot. The entire history does not always have to be played back all along the way. Usually it is sufficient to start from the last snapshot and only look at the events that have been saved since then. As a snapshot only supplements history, and does not replace it, the older events are still available if they are required for an evaluation.

Learning from the past

A similar mechanism can also be used to precalculate special tables for reading data, similar to materialized views. In this case, there is no longer any need to replay, as there is already a table with the required data. However, this requires that they are always updated when a new event is saved.

It is particularly convenient that these read tables can also be completely recalculated if a different interpretation of the data is required. This means that not all evaluations that may be relevant need to be known from the very start: instead, they can also be calculated retrospectively if necessary. This reinterpretation of the data is possible for arbitrary queries as long as the original events provide the required semantics.

Event sourcing makes it possible to learn from the past in this way because, for example, the events of business processes can be analysed and interpreted on the basis of new findings or questions. However, this is only possible because events are enriched by semantics and intention, and they can only provide the necessary data in this way.

Implementing event sourcing

From a technical point of view, event sourcing is relatively simple: a storage for events is required, which only has to support adding and reading events. It is therefore a so-called append-only data store.

Of course, you can use a traditional relational database and limit its statements to INSERT and SELECT. Alternatively, there are also numerous other data storage options, such as NoSQL databases, XML files or simple text files that are stored directly in the file system.

Since compared to CRUD the statements UPDATE and DELETE are omitted, the access is easy to implement and allows a very good efficiency. The reason why the two actions UPDATE and DELETE are ignored is simply that the storage for events is intended to be a non-destructive data storage. Since the previous data is lost with every update and especially when removing records, these actions must not be used.

A data store that works according to this principle and is suitable for event sourcing is called an event store.

Using events as relational data

Incidentally, the data structure of an event store is actually relational. This seems to be a contradiction at first, since the concrete useful data of domain events hardly all use the same format. The point is, however, that this data is not relevant for the event store: all the event store needs for its work is the record ID, the order of the events and, if necessary, a timestamp. Which data is contained in an event is irrelevant for the event store.

The open source module sparbuch for Node.js implements such an event store and supports MongoDB and PostgreSQL as databases out of the box. PostgreSQL is the better and more powerful choice. If you take a look at the schema definition of the events table, you will notice that all events can be processed using a single schema:

CREATE TABLE IF NOT EXISTS "${this.namespace}_events" (
  "position" bigserial NOT NULL,
  "aggregateId" uuid NOT NULL,
  "revision" integer NOT NULL,
  "event" jsonb NOT NULL,
  "hasBeenPublished" boolean NOT NULL,
  CONSTRAINT "${this.namespace}_events_pk" PRIMARY KEY("position"),
  CONSTRAINT "${this.namespace}_aggregateId_revision" UNIQUE ("aggregateId", "revision")
);

The actual user data of the domain events are stored in the field event, which is of the type jsonb. This type is used in PostgreSQL to efficiently store arbitrary JSON data.

Similarly flexible is the schema definition of the snapshots table, which also uses the data type jsonb:

CREATE TABLE IF NOT EXISTS "${this.namespace}_snapshots" (
  "aggregateId" uuid NOT NULL,
  "revision" integer NOT NULL,
  "state" jsonb NOT NULL,
  CONSTRAINT "${this.namespace}_snapshots_pk" PRIMARY KEY("aggregateId", "revision")
);

What should be used when?

If you put it all together, this basically provides the criteria for deciding when to use event sourcing and when to use CRUD.

It is obvious that event sourcing is particularly suitable for those use cases where the traceability of changes is relevant. This may already be relevant for regular business data, but it is relevant for security-critical or sensitive data at least.

Rule 1: Event sourcing enables traceability of changes.

Instead of keeping a separate audit log, the individually stored events can be used to determine who could access which data at what point in time. Potentially, you can even go so far as to consider changes in the authorization of data as events, which also become part of the data set on the way. Since the domain and the security data merge in this way, this results in very powerful and reliable possibilities.

Rule 2: Event sourcing enables audit logs without any additional effort.

Event sourcing can also be extremely practical for debugging, as the legendary developer John Carmack already noted in 1998:

“The key point: Journaling of time along with other inputs turns a realtime
application into a batch process, with all the attendant benefits for quality
control and debugging. These problems, and many more, just go away. With a full input trace, you can accurately restart the session and play back to any point (conditional breakpoint on a frame number), or let a session play back at an arbitrarily degraded speed, but cover exactly the same code paths.”

An extremely interesting option of event sourcing is to be able to depict not only a reality, but also alternative realities. Since the calculated state depends on the interpretation of the individual events, events can be evaluated differently in retrospect. This also makes it possible to work with undo and redo steps, which you can get free of charge when using event sourcing without any further action.

Rule 3: Event sourcing makes it possible to reinterpret the past.

Since domain events do not always refer to all data in a record, event sourcing also supports partial updates. There are certainly two or even more events that are not in conflict with each other and can therefore all be applied at the same time. This way the conflict potential with simultaneous changes decreases dramatically, which in turn makes the use of the software with many users easier.

Rule 4: Event sourcing reduces the conflict potential of simultaneously occurring changes.

In addition, schema changes are much easier to implement because old versions of events can be updated during loading in case of doubt. The application only needs to be able to distinguish between two versions of an event type and contain additional code that transforms one version into the other. Complex and error-prone updates of entire tables such as ALTER TABLE are completely omitted in event sourcing.

Rule 5: Event sourcing enables easy versioning of business logic.

Since the events can be used as data for a pub-sub-system in addition to pure data storage, event sourcing can also be used for integration with other systems that represent a different bounded context or even another domain.

Rule 6: Event sourcing is also suitable for integration with other systems.

When to use CRUD

Ultimately, only two aspects speak for CRUD. On the one hand, CRUD is useful if the data to be stored does not contain any semantics because it is only raw data. For example, this can be the case on the internet of things (IoT), where you have to capture and persist large amounts of sensor data. In this case, it makes sense to store data with the help of CRUD, evaluate them later, and then delete them if necessary. Event sourcing can hardly bring any advantages here.

Rule 7: CRUD is used to efficiently store raw data that does not contain semantics.

The second aspect that speaks for CRUD is the ability to check for duplicates via indices, for example. Since only the individual deltas are stored in event sourcing, it is much more difficult to determine whether two records contain the same values at a given point in time or not. A precalculated read table can help here, but this can be solved much more easily in CRUD. However, it is questionable whether the problem of uniqueness should be solved at the database level, or whether this is not rather a question of the business logic above it.

Rule 8: CRUD simplifies the search for duplicates.

The biggest criticism of CRUD, however, is the arbitrary restriction of one’s own language to just four verbs (create, read, update, delete), which can hardly do justice to a domain language. Steve Yegge already described in 2006 in his very worth reading blog entry Execution in the Kingdom of Nouns that it is precisely the verbs that are relevant for a living language.

These 9: Event sourcing focuses on professionalism and semantics, while CRUD focuses on technology.

Leaving the comfort zone

If one makes a comparison on the criteria and aspects mentioned above, CRUD scores alarmingly poorly. The ninth and final thesis sums up the problem in a nutshell: CRUD is about technology – but very few applications are created to solve technological problems. Instead, software is usually written to solve real-world domain problems. The complexity inherent in the respective domain lies in its matter of subject, which can hardly be comprehensively described with a handful of verbs. Here, CRUD simply falls short of the mark.

In addition, there is the loss of the entire history and the regular destruction of data through UPDATE and DELETE statements. Both are devastating for a later evaluation of business processes, since important findings can no longer be gained, as the way in which data is generated can no longer be traced.

However, the really biggest drawback of event sourcing has not yet been mentioned: Very few developers are familiar with event sourcing. CRUD has been known to practically everyone forever, which is why the use of event sourcing means that you have to leave your beloved comfort zone. You will win massively, but you first have to experience this gain to realize that it is worth the effort (which isn’t really that much, in fact).

If you use event sourcing for a while, for example in connection with CQRS and domain-driven design (DDD), the use of UPDATE and DELETE suddenly seems to be completely wrong, and you wonder how you could ever work with CRUD, and believe that you have a suitable data model in front of you.

Source:: risingstack.com

Laravel 5.6 is Out! What's New?

By Christopher Vundi

Laravel has come a long way becoming better with each new release. During the recent Laracon Online, Taylor Otwell announced the official release of Laravel 5.6. Just like Laravel 5.5, this new version will require PHP 7.0+.

Without further ado, let’s see what this new version of Laravel has to offer:

Two New Blade Directives

Laravel 5.6 will include two new form blade directives for cross-site request forgery (CSRF) and HTTP method input.

In previous Laravel versions, we had to do this at the top of forms to create hidden inputs for the CSRF token and the spoofed HTTP method:

<form>
  {{ csrf_field() }}
  {{ method_field('PUT') }}
  <!-- ... -->
</form>

With the new release, it’s now possible to do this instead:

<form>
    @method('put')
    @csrf
    <!-- ... -->
</form>

Note: HTML forms can’t make PUT, PATCH, or DELETE requests you need to add a hidden method input to spoof these HTTP verbs. Laravel uses the method input to route the request to the appropriate controller action correctly.

I find these directives looking neater and easier to remember. However, the old helper functions are still available for use if that’s what you prefer.

The Artisan Optimize Command Has Been Removed

The Artisan optimize command was deprecated as of 5.5 and has been removed officially from 5.6. Quoting Laravel 5.5’s upgrade guide:

With recent improvements to PHP op-code caching, the optimize Artisan command is no longer needed. You should remove any references to this command from your deployment scripts as it will be removed in a future release of Laravel.

In the case you want to upgrade to this new version, be sure to remove the command from your composer.json post-install-cmd and post-update-cmd scripts.

Eloquent Date Casting

It’s now possible to customize the format of Eloquent date and datetime casting:

protected $casts = [
    'sign_up_date' => 'date:Y-m-d',
    'last_activity_at' => 'datetime:Y-m-d H:00',
];

Casting comes in handy when we want to serialize model attributes to a specific format.

Argon2i Password Hashing Algorithm Support

The Argon2i password hashing support will be supported by Laravel 5.6. Argon2 is a password-based key derivation function winner of the Password Hashing Competition in July 2015 and an evolution of the popular bcrypt and scrypt hashing algorithms.

There are two main versions of the Argon2 algorithm: Argon2i and Argon2d. Argon2i is the safest against side-channel attacks, while Argon2d provides the highest resistance against GPU cracking attacks. Note however that Argon2d is not suitable for password hashing and should not be used. You can control which hashing driver is used by default in the new config/hashing.php configuration file.

The old style of bcrypt will continue to be supported and will remain the default, but for those starting a new Laravel 5.6 project and are already running PHP 7.2+, I’d recommend using the Argon2i driver.

Collision Package for CLI Error Reporting

The new Laravel release now ships with the Collision package pre-installed as a dev composer dependency. Collision is an error handler package for PHP command line applications. With the package, we get beautiful error reporting when interacting with your Laravel applications through the command line. Below is a screenshot of the package in action:

Collision is built on top of the Whoops error handler, which we saw return in Laravel 5.5 and supports artisan and phpunit commands.

Bootstrap 4

Laravel 5.6 ships with Bootstrap 4 meaning, all front-end scaffolding such as the authentication boilerplate and example Vue component have been upgraded to Bootstrap 4.

API Resource Controller Generation

When generating a resource controller for an API in Laravel 5.6, we can pass in the --api flag to exclude the create and edit methods which only apply to resource controllers returning HTML:

php artisan make:controller API/SomethingController --api

Blade component aliases

Laravel 5.6 adds the ability to register alias directives for Blade components. Blade components were introduced in Laravel 5.4. In not familiar with the concept of Blade components, a blade component is a directive to include views inspired by “components” in JavaScript frameworks like Vue.

Let’s say we have a component stored at resources/views/components/alert.blade.php. Normally, we access the component using:

@component('components.alert')
    Here be dragons!
@endcomponent

In Laravel 5.6, it’s now possible to simplify the component syntax to a single directive with the new Blade::component function.

Back to our alert example:

Blade::component('components.alert', 'alert');

Once the component has been aliased, you may render it using its alias:

@component('components.alert')
    Here be dragons!
@endcomponent

And if the component does not have additional slots, we can just use the component’s name as a Blade directive:

@alert
    Here be dragons!
@endalert

Single Server Scheduling

Scheduled tasks normally run on all servers for Laravel applications running on multiple servers. Let’s say we have a scheduled task and our Laravel application has been deployed to two web servers and two worker servers. The task will execute on every server our application is running on. In this case, all four servers. Not cool!

It’s now possible to limit a scheduled job to only execute on a single server in Laravel 5.6 using the onOneServer when defining the task:

$schedule->command('sync:plans')
            ->hourly()
            ->onOneServer();

Having specified the onOneServer method within our task definition, the first server to obtain the task will secure an atomic lock on the job to prevent other servers from running the same task at the same time.

Note, however, when using this feature, you will need to use the Redis or Memcached cache drivers. These drivers provide the atomicity needed to secure the locks that power this feature.

Dynamic Rate Limiting

In previous Laravel versions, when limiting the number of requests to a route group, we had to hardcode the value within the route group. Like so:

Route::middleware('auth:api', 'throttle:60,1')->group(function () {
    Route::get('/user', function () {
        //
    });
});

With the new release, we can just create a rate_limit attribute in the AppUser model where we set the number of requests allowed in the given time limit.

. We then pass the name of the attribute to the throttle middleware so that it is used to calculate the maximum request count:

Route::middleware('auth:api', 'throttle:rate_limit,1')->group(function () {
    Route::get('/user', function () {
        //
    });
});

Logging Improvements

This is the biggest feature in this new release. Logging has been moved from the config/app.php file to a new config/logging.php file.

It’s also now possible to define stacks that send different log messages to different handlers. The stack driver allows you to combine multiple channels into a single log channel:

'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['syslog', 'slack'],
    ],

    'syslog' => [
        'driver' => 'syslog',
        'level' => 'debug',
    ],

    'slack' => [
        'driver' => 'slack',
        'url' => env('LOG_SLACK_WEBHOOK_URL'),
        'username' => 'Laravel Log',
        'emoji' => ':boom:',
        'level' => 'critical',
    ],
],

Looking at the above snippet, our stack channel aggregates two other channels via its channels option: syslog and slack. So, when logging messages, both of these channels will have the opportunity to log the message. Also, all debug messages will go to a system log while error logs go to slack. You can read more about this here.

Broadcast Channel Classes

Laravel 5.6 comes with a new artisan make:channel command:

php artisan make:channel OrderChannel

The generated channel will be placed inside the App/Broadcasting folder.

Having separate channel classes comes in handy especially when we have a Laravel application that consumes many different channels. There is a high probability the routes/channels.php file will get bulky. So, instead of using Closures to authorize channels, we can now leverage channel classes.

We then register this channel inside the routes/channels.php file:

use AppBroadcastingOrderChannel;

Broadcast::channel('order.{order}', OrderChannel::class);

Authorization logic for the channel goes inside the join method for this channel as opposed to having the logic go inside the channel authorization closure.

Conclusion

As you can see, Laravel is becoming better with each new release. I only highlighted the most notable improvements in the framework; more thorough changelogs are available here. Leave your thoughts and suggestions in the comments section below and don’t forget to share with your fellow Laravel enthusiasts!

Source:: scotch.io

Build a CSS Grid Calculator (Solution to Code Challenge #2)

By Chris Sevilleja

Last Friday, we put out our second ever code challenge. It was a good way to get a little coding practice in over the weekend with a concept that is fairly new, CSS Grid Layout.

Before CSS Grid, we’d have to focus on using floats, display: inline-block and all manner of moving elements around. Thanks to new properties like grid-template, grid-gap, and grid-column/grid-row, we can write this calculator in very few lines of code.

Let’s walk through the solution and see how we can build this layout quickly and easily thanks to CSS Grid. If you want a primer on CSS Grid, check out our other article: Getting Started with CSS Grid Layout

The Code Challenge

The challenge was to build this calculator using CSS Grid!

The Solution

I’ll be working within a CodePen for this tutorial. I’ve also made a video for those that like the video format.

We’ll start out this solution by focusing on the HTML. We’ll wrap everything in a calculator class:

<div class="calculator">

  <!-- the input -->
  <input type="number">

  <!-- the buttons -->
  <div class="calculator-buttons">
    <!-- buttons go here -->
  </div>

</div>

Adding the Calculator Buttons

Now we have the foundation for our calculator. Let’s start adding the buttons. We’ll need:

  • 10 Numbers: 0 through 9
  • A clear button
  • An equals button
  • 4 Operators: ÷, ×, −, &plus;

We can add them in the order they’ll appear:

...

<!-- the buttons -->
<div class="calculator-buttons">
  <button class="calc-button">C</button>
  <button class="calc-button">÷</button>

  <button class="calc-button">7</button>
  <button class="calc-button">8</button>
  <button class="calc-button">9</button>
  <button class="calc-button">×</button>

  <button class="calc-button">4</button>
  <button class="calc-button">5</button>
  <button class="calc-button">6</button>
  <button class="calc-button">−</button>

  <button class="calc-button">1</button>
  <button class="calc-button">2</button>
  <button class="calc-button">3</button>
  <button class="calc-button">&plus;</button>

  <button class="calc-button">0</button>
  <button class="calc-button">&equals;</button>
</div>

...

Notice I’ve added some line-breaks/spacing for clarity. We have put line breaks where we visualize our grid rows will take place.

Quick Calculator Styling

Our calculator will look nothing like a calculator at this point:

Let’s add some quick styling so that we’re not working with some really unstyled and ugly buttons. First, the overall calculator styles:

/* quick reset so all our padding is the right size */
* {
  box-sizing: border-box;
}

/* add some spacing */
body          {
  background: #F6F6F6;
  padding-bottom: 30px;
  padding-top: 30px;
}

/* limit the width and center */
.calculator   {
  max-width: 400px;
  margin: 0 auto;
  border: 2px solid #111;
  border-radius: 5px;
}

Slowly but surely, we are moving along!

Styling the Buttons

We’ll quickly style the buttons before we get onto the CSS Grid fun. We’ll be adding CSS for the individual buttons but we won’t deal with the .calculator-buttons container yet. That’s where all the CSS Grid magic will happen. This will just be for quick styling.

.calc-button  {
  background: rgba(0, 0, 0, 0.5); /* light background with opacity 50% */
  border: 1px solid #111; /* black border */
  padding: 20px;
  color: #EEE; /* white text */
  border-radius: 5px; /* rounded corners */
  font-size: 22px; /* larger fonts */
  cursor: pointer; /* make it look clickable */
}

Styling the Input

The input will take a few styles to get it to match our calculator now:

.calculator input   {
  /* reset basic form styles */
  background: none;
  border: none;
  box-shadow: none;
  outline: none;

  padding: 10px;
  width: 100%;
  border-bottom: 2px solid #111;
  color: #333;
  text-align: right;
  font-size: 40px;
  border-radius: 0;
}

Now we have our input and buttons looking good!

Using CSS Grid to Position Buttons

The last part of our calculator may just be the easiest part. We’ll use the CSS Grid to position our buttons. To use CSS Grid Layout, we just have to define the layout we would like on our parent element; in this case, the .calculator-buttons div.

Feel free to play around with these numbers, but we’ll start by creating our four columns.

.calculator-buttons {
  /* small spacing within our container */
  padding: 20px;

  /* the grid stuff! */
  display: grid;

  /* create 4 columns */
  grid-template-columns: 1fr 1fr 1fr 1fr;
}

We have declared display: grid to make sure this container is a grid. Next we define the four columns we want using the fr (fractional unit).

This means that CSS will create the columns with equal widths. This means each of our four columns will be 25% width.

We don’t even have to define the number of rows here. The elements will keep moving to new rows until they are all placed.

Shorthand

One thing to note is that CSS Grid comes with the repeat() function that allows us to not have to write out all columns/rows. The above can be refactored to:

grid-template-columns: repeat(4, 1fr);

This is very helpful when you want to create many columns.

Adding Spacing with Grid Gap

Our buttons are sitting right next to each other, but we need to add some spacing to them to make it look like an actual calculator.

To add a gap, we can use the following:

.calculator-buttons {
  ...

  /* add the grid gap */
  grid-gap: 15px;
}

Now our calculator buttons have spacing!

Large Width Buttons

For our larger C (clear) and 0 buttons, we can easily make them span across multiple columns by targeting them specifically. Let’s target each individually because we also want to change their colors out. This could be done with one CSS class, if you wanted and it could be called span-3 or something along those lines.

Here we’ll create an is-clear and is-zero class for each button. Go ahead and add those to your HTML. Then we can add these CSS classes:

/* span across 3 columns */
.is-zero,
.is-clear   {
  grid-column: span 3;
}

/* go blue */
.is-clear   {
  background: #3572DB;
}

Colored Equals Button

Add a class to your equals button and call it is-equals. Here is the CSS for that:

.is-equals {
  background: #28D060;
}

The Calculator Font

The last sprinkle of styling we’ll add that gives this calculator that extra bit of pizazz is the font. Head on over to fonts.google.com and browse around for a good Monospace font you like. I’ve settled on Space Mono for my calculator.

Add the @import to the top of your CSS and add font-face to the .calculator input and the .calc-buttons

@import url('https://fonts.googleapis.com/css?family=Space+Mono');

.calculator input,
.calc-button   {
  font-family: 'Space Mono';
}

Our calculator is done!

Conclusion

I hope you enjoyed that quick lesson on CSS Grid and the Code Challenge. Let me know in the comments if you’d like us to continue doing these Weekend Code Challenges and posting the solutions on Mondays. Happy coding!

Source:: scotch.io