Category Archives: Uncategorized

vue-pin-code-input-component

Vue PIN code input component

At the end of this post you’ll learn how to implement a basic vue pin code input component.

One of my projects required an authorization layer for protecting some resources.

I ended up building a quite simple Vue Component that can be integrated in any app and that can be easily extended for any needs.

The template of the Vue Pin Code Component looks like this:

<template>
    <div>
        <div class="input-group">
            <input v-model.number="pin_0"
                   v-on:keyup.right="pin_focus('pin_1')"
                   v-on:keypress="is_valid_pin_value($event, 'pin_0')"
                   ref="pin_0" type="text" placeholder="0">
            <input v-model.number="pin_1"
                   v-on:keyup.left="pin_focus('pin_0')"
                   v-on:keyup.right="pin_focus('pin_2')"
                   v-on:keypress="is_valid_pin_value($event, 'pin_1')"
                   ref="pin_1" type="text" placeholder="0"">
            <input v-model.number="pin_2"
                   v-on:keyup.left="pin_focus('pin_1')"
                   v-on:keyup.right="pin_focus('pin_3')"
                   v-on:keypress="is_valid_pin_value($event, 'pin_2')"
                   ref="pin_2" type="text" placeholder="0">
            <input v-model.number="pin_3"
                   v-on:keyup.left="pin_focus('pin_2')"
                   v-on:keypress="is_valid_pin_value($event, 'pin_3')"
                   ref="pin_3" type="text" placeholder="0">
        </div>
    </div>
</template>

The controller of the component:

export default {
     data: function () {
         return {
             pin_0: null,
             pin_1: null,
             pin_2: null,
             pin_3: null
         }
     },
     computed: {
         pin: function () {
             return ${this.pin_0}${this.pin_1}${this.pin_2}${this.pin_3}
         }
     },
     watch: {
         pin: function () {
             this.$bus.$emit('PIN/change', this.pin)
         },
         pin_0: function (nv) {
             if (nv.toString().length !== 0) {
                 this.$refs.pin_1.focus()
                 this.$refs.pin_1.select()
             }
         },
         pin_1: function (nv) {
             if (nv.toString().length !== 0) {
                 this.$refs.pin_2.focus()
                 this.$refs.pin_2.select()
             }
         },
         pin_2: function (nv) {
             if (nv.toString().length !== 0) {
                 this.$refs.pin_3.focus()
                 this.$refs.pin_3.select()
             }
         }
     },
     methods: {
         pin_focus: function (ref) {
             this.$refs[ref].focus()
             this.$refs[ref].select()
         },
         is_valid_pin_value: function (e, pin_N) {
             const char = String.fromCharCode(e.keyCode)
             const is_value_selected = this[pin_N] !== null && this.$refs[pin_N].selectionStart === 0 && this.$refs[pin_N].selectionEnd === this[pin_N].toString().length
             if ((this[pin_N] === null || this[pin_N].toString().length === 0 || is_value_selected) && parseInt(char, 10) >= 0 && parseInt(char, 10) <= 9) {
                 return true
             }
         e.preventDefault()     } }
 }

What it does:

The data contains properties required for binding the current values of the pin between the template and the controller.

A computed property pin is kept up2date using changes done to any data variable.

We’re using keyup.left, keyup.right and keypress events to switch between each input of the PIN.

Each time the pin computed variable is changed, we $emit an event. See my previous post for learning how to implement Observer Pattern in Vue.

Integrating the PIN Component in our app is as easy as:

<InputPIN />

this.$bus.$on('PIN/change', function (value) {
    console.log('the pin:', value)
})

That’s all. Our Vue PIN Input component is ready.

Docker Swarm Tutorial – Getting Started

  1. Activating Docker Swarm on Manager Node
  2. Attaching Worker Nodes to the Swarm

A great alternative to Kubernetes is Docker Swarm. It allows you to orchestrate services deployed on multiple nodes that are controlled by a node called manager.

First of all you need to have Docker Tools installed on all nodes.

Activating Docker Swarm on Manager Node

docker swarm init --advertise-addr <IP_OF_MANAGER_NODE>

Attaching Nodes to the Docker Swarm

After you activate the Manager Node you will receive a token that can be used to attach. worker nodes to the Manager Node.

docker swarm join --token <TOKEN> <IP_OF_MANAGER_NODE:PORT> (2377 default port)

After you run this command, you should see the message “This node joined a swarm as a worker.

What is X-WSSE Token Authentication and how does it work

Learn the basics of X-WSSE Token Authentication and how to authorize requests using X-WSSE header authentication.

X-WSSE Token Authentication can be used to authenticate backend-to-backend integrations using client_id and client_secret properties. The main benefit of this type of authentication is that the client_secret value never leaves the backend of the integrating client, and that each token, even if lost, is only valid for 5 minutes.

The X-WSSE Token is a string with the following format, usually a single HTTP header line which is broke down into multiple lines for easier readability:

X-WSSE: UsernameToken
Username="USERNAME",PasswordDigest="ASDFbasEHAPRo395MBANgoaiERJGJHSOSLGUsernameToken Username="68037425-fa69-49da-8715-fa393dc55471", PasswordDigest="OWRkZGRjMjk3ZjhiOGFhZmMzNGIzMjAwMWIyNmNjY2JkMTM2M2E5OGFlMGM2ZDI3OGIzZmQ5ZDAwY2RiODMzZg==", Nonce="ee2e8c783398782fd63af15141a1cb62", Created="2019-03-14T16:17:24.211Z"==",Nonce="b35f7341829e35d89851497a82894f",Created="2019-03-20T12:10:20Z"

I’ll briefly describe each component of the X-WSSE Token:

X-WSSE

The name of the HTTP header that must be present in order to authorize the request.

UsernameToken

Value represents the authentication method of the use X-WSSE Token. Currently X-WSSE only supports UsernameToken type of authentication.

Username

The client_id property that you should generate for each integration of X-WSSE Token.

PasswordDigest

Field specifies the hashed token that will authorize the reuqest. For each request a new hash must be generated. Check my other posts and learn how to generate the X-WSSE Token using different server-side programming languages

Computing the Password Digest

Computing the password digest involves 5 simple steps:

  1. Generate random 16 byte Nonce formatted as 32 hexadecimal characters.
  2. Retrieve the current timestamp in ISO8601 format.
  3. The properties nonce, timestamp, secret should be concatenated in this order.
  4. Compute the SHA256 hash value of the string from #3 and convert it to hexadecimal format
  5. Encode the value from #5 in BASE64 and obtain the PasswordDigest

Nonce

Random value with the purpose to make your request unique so it cannot be replicated by unknown parties. This string is always 16 bytes long and should be represented as a 32 characters long hexadecimal value.

Created

This field contains the current UTC, GMT, ZULU timestamp (YYYY-MM-DDTHH:MM:SS) according to the ISO8601 format. e.g. 2018-05-20T12:51:45+01:00

Now you know what is a X-WSSE Token and the purpose of each of its components so let’s go to the Implementation. Check my other X-WSSE articles and learn more.


LibGDX send HTTP request

Check out Lines Galaxy Android game to view the results in action.

Most common ways to communicate between your mobile app to your backend servers are HTTP Requests and Websockets.

In this article I’ll describe how you can create, send and process a HTTP Request to backend servers from your LibGDX application. In this example I will demonstrate how to send a basic POST request.

First step is to prepare the request payload:

Map<String, String> parameters = new HashMap<String, String>();

parameters.put("token", "<TOKEN>");
parameters.put("some_value", 1234);

final Json json = new Json();
json.setTypeName(null);
json.setOutputType(JsonWriter.OutputType.json);
json.setUsePrototypes(false);
String requestJson = json.toJson(parameters);

Second step is to create an instance of the HTTP Agent:

Net.HttpRequest request = new Net.HttpRequest(Net.HttpMethods.POST);
request.setUrl("http://example.com/");
request.setContent(requestJson);

And finally, after we set the desired server url and prepared the payload, we can send the request and attach the callback listeners

Gdx.net.sendHttpRequest(request, new Net.HttpResponseListener() {
    public void handleHttpResponse(Net.HttpResponse httpResponse) {
        HttpStatus status = httpResponse.getStatus();
        if(status.getStatusCode() == 200) {
            String responseJson = httpResponse.getResultAsString();
        } else {
            // error :(
        }
    }
    public void failed(Throwable t) {
        String error = t.getMessage();
    }
    public void cancelled() {
        // request aborded
    }
});

And that’s it. ou can just copy the above code and send LibGDX HTTP Request. You can dig further by reading the official docs: HttpResponseListener, HttpRequest.

Check out Lines Galaxy Android game to view the results in action.