A Health Kick

Starting this Monday, for a duration of three months – until January 7, 2020, I plan on starting to exercise five days a week. A health kick. My goal is to increase overall wellness. To improve circulation, to gain strength, and decrease fat.

My exercise routines are to be organized such as: Monday: Cardio, Tuesday: Abs, Wednesday: Chest / Back, Thursday: Arms, and Friday: Legs.

The exercises I am planning on doing will be mostly bodyweight though I might include weighted workouts. Cardio exercise will be jogging, though distance is not a goal. I will probably keep it under a mile each jogging session. Besides cardio, I will do three sets of each exercise with however many repetitions as is comfortable.

Diet and supplement-wise I will work on muscle recovery through protein drinks, BCAAs, and ZMA. I also am going to work on eating healthy, especially to include vegetables in my diet and limiting processed sugars.

The exercises need not be advanced. Just one or two simple exercises a day.

I feel that taking these steps could be a great benefit to health and wellness.

Authentication Simplified with AWS Cognito

It took a while for me to find info on how to practically implement web application authentication. Turns out it is really simple to do with AWS Cognito. What Cognito does is authenticates to a pool of (email or SMS confirmed) users and sends back a JWT (Javascript Web Token) once authenticated.

This post will function as an “essential” guide to Cognito. I’ll include the least amount of code as possible for authentication to occur in a web application with just an email address and password. You could find more detailed info at this AWS tutorial (The tutorial is what the following code is vanilla-fied from.).

First off download and include the AWS SDK and NPM SDK in an HTML page.

Then log into AWS Cognito and create a user pool. Use the defaults. Check: “Also allow sign in with verified email address”. Add an app client. Uncheck: “Generate client secret”. Start up your JS and include relevant fields.

_Cognito = {
    cognito: {
        userPoolId: '',// e.g. us-west-2_abcde3fghij
        userPoolClientId: '', // e.g. 12abcde3fgh4ijklmn5
        region: '' // e.g. us-west-2
    }
};

var Cognito = {};

var poolData = {
    UserPoolId: _Cognito.cognito.userPoolId,
    ClientId: _Cognito.cognito.userPoolClientId
};

var userPool; 

userPool = new AmazonCognitoIdentity.CognitoUserPool(poolData);

Now the SDK is available to use. Let’s register a user.

function register(email, password, onSuccess, onFailure) {
    var dataEmail = {
        Name: 'email',
        Value: email
    };
    var attributeEmail = new AmazonCognitoIdentity.CognitoUserAttribute(dataEmail);

    userPool.signUp(email, password, [attributeEmail], null,
        function signUpCallback(err, result) {
            if (!err) {
                onSuccess(result);
            } else {
                onFailure(err);
            }
        }
    );
}

 if (document.readyState == 'loading'){
   document.addEventListener("DOMContentLoaded", function(){ 
     document.querySelector('#registrationForm').addEventListener('submit', handleRegister); 
   });
}

function handleRegister(event) {
    var email = document.querySelector('#emailInputRegister').value;
    var password = document.querySelector('#passwordInputRegister').value;

    var onSuccess = function registerSuccess(result) {
        var cognitoUser = result.user;
        console.log('user name is ' + cognitoUser.getUsername());
        var confirmation = ('Registration successful. Please check your email inbox or spam folder for your verification code.');
        if (confirmation) {
            //Go to verification page;
        }
    };
    var onFailure = function registerFailure(err) {
        alert(err);
    };
    event.preventDefault(); 
    register(email, password, onSuccess, onFailure); 
}

An email will be sent to the user that includes a verification code. With that you’ll verify the user.

function verify(email, code, onSuccess, onFailure) {
    createCognitoUser(email).confirmRegistration(code, true, function confirmCallback(err, result) {
        if (!err) {
            onSuccess(result);
        } else {
            onFailure(err);
        }
    });
}

if (document.readyState == 'loading'){
   document.addEventListener("DOMContentLoaded", function(){ 
     document.querySelector('#verifyForm').addEventListener('submit', handleVerify);
   });
}

function handleVerify(event) {
    var email = document.querySelector('#emailInputVerify').value;
    var code = document.querySelector('#codeInputVerify').value;
    event.preventDefault();
    verify(email, code,
        function verifySuccess(result) {
            console.log('call result: ' + result);
            console.log('Successfully verified');
            alert('Verification successful.');
        },
        function verifyError(err) {
            alert(err);
        }
    );
}

To sign in:

if (document.readyState == 'loading'){
   document.addEventListener("DOMContentLoaded", function(){
     document.querySelector('#signinForm').addEventListener('submit', handleSignin); 
   });

}

function signin(email, password, onSuccess, onFailure) {
    var authenticationDetails = new AmazonCognitoIdentity.AuthenticationDetails({
        Username: email,
        Password: password
    });

    var cognitoUser = createCognitoUser(email);
    cognitoUser.authenticateUser(authenticationDetails, {
        onSuccess: onSuccess,
        onFailure: onFailure
    });
}

function handleSignin(event) {
    var email = document.querySelector('#emailInputSignin').value;
    var password = document.querySelector('#passwordInputSignin').value;
    event.preventDefault();
    signin(email, password,
        function signinSuccess() {
            console.log('Successfully Logged In'); 
        },
        function signinError(err) {
            alert(err);
        }
    );
}

Here we will get the token. You could see what the token consists of at JWT.io.

let user = userPool.getCurrentUser();

if (user){
    user.getSession(function sessionCallback(err, session){
        if (err) {
           //Nada session info.
        } else {
           //JWT
           console.log(session.getIdToken().getJwtToken());
        }
});
}

To sign out:

Cognito.signOut = function signOut() {
    userPool.getCurrentUser().signOut();
};

if (document.readyState == 'loading'){
      document.addEventListener("DOMContentLoaded", function(){ 
        document.querySelector('#signOut').addEventListener('click', function() {
            Cognito.signOut();
            alert("You have been signed out.");
          })
        })
      }

That’s the gist of authentication with Cognito. I’ve included a working example.

Net Zero Carbon Emissions

After hearing about the global protest against inaction on climate change, I decided to look into the topic of net zero carbon emissions.

Essentially, the goal of net zero carbon emissions would be met through using only renewable energy production such as solar and wind power.

It just makes sense, clean energy is the future.

In my opinion, a smart start to implementation of net zero carbon emissions might include a push towards a residential solar energy plan throughout the nation and world. This plan might make residential *grid-connected* solar systems extra-affordable through incentives and credits.

Commercial incentives or tax breaks might be an extra reason to switch to renewable energy. Amazon’s pledge to go renewable or Walmart’s sustainability goal could serve as a model for other commercial entities.

Net zero carbon emissions for the individual household or commercial entity is possible, so it is reasonable to take the steps to make a cleaner earth and air. Our future has spoken.

An Apprenticeship

I’ve tried it before: the electrician’s apprenticeship. I had to travel and it was too much travel for me so I chose not to continue. Now it’s different. I’m going to give it another try. I’m going to ask if it’s possible to stay in town during, at least the beginning of, the apprenticeship. To me it makes sense: decent pay and learning on the job. The work is, sort of awesome, and there is a lot to learn. Let’s see how it goes.

An ES6 Web Application

Overview

Most, it seems, of the code for my most recent web application has been written. There surely is room for improvement with this project, and it is (mostly) functioning how it should be. In this post I’ll be writing about the code techniques I used, provide an overview of the application, and I will also go over areas in which I could improve the application.

It is a simple input and output program with a database on the backend. The program is all written on the frontend, which I found to be very convenient. (All JS.) It’s a simple architecture while using the NoSQL database.

The NoSQL database is called Couch and I used a JS library called Pouch. My only question, while using this architecture is “Why aren’t more people designing their programs with these frameworks!?”

I used ES6 (or newer – and some older) coding techniques. My overall program is structured like this:

//Global and helper functions

class Model{
//Templates go here.
}

class View{
//User interface code goes here.
}

class Auth{
//Authentication goes here.
}

let auth = new Auth();
let model = new Model();
let view = new View();

There is an authentication layer which accesses the database with a login and logout feature. Couchdb is cookie authenticated so the user could stay logged in even during page reloads and navigation.

The view class was composed of mostly methods that managed the logic of the view.

class View {
    constructor(){
    }
    newItem(){
       //Adds a new item.
    }
    editItem(){
       //Edits the item.
    }
    deleteItem(){
       //Deletes item.
    }
}

Techniques

For the HTML templates I used ES6 template strings. They really open up a lot of possibilities with their usage.

class Model(){
    constructor(){}
    template = (data) => {
      return `
          <ul><li>${data}</li></ul>
      `;
    }
}

A feature that became especially useful is Array.map. Before discovering this function, I was using an if…then to “iterate” through the data.

if (data.item[0]){
    doThis(data.item[0]);
} else if (data.item[0] && data.item[1]){
    doThis(data.item[1]);
}// ... etc.

Needless to say that there are more efficient ways of iterating through an array. Array.map to the rescue! It is similar to Array.forEach except returns a duplicate of the modified array instead of modifying the original array. And remember to use the .join to connect each iteration with an empty space instead of including the array’s commas.

class Model{
    constructor(){
    }
    template = (data) => {
      return data.map(function(value, index){
        return `<li>${value.item[index]}</li>`
      }).join('');
    }
}

Areas of Improvement

There could be many areas of improvement to this application though the most notable area is probably having to do with reloading the window location. There are times where location.reload seemed like the perfect solution, yet it wasn’t. It was a question of seemlessness and having to do more with UX (user experience). For example, after editing an item, I would have to manually reload for the items to display. How would one accomplish this without a manual reload? Use location.reload – or code in a “view items” function?

Conclusion

This was a fun project and I learned some new techniques to develop with. While I still have much to learn, this project turned into a functioning program, all with good ‘ole vanilla JS, a code library, and a JS friendly database! If you are creating a project with similar frameworks (or non-frameworks), I’d be happy to share knowledge! Thanks for taking the time to read this.