Tuesday, 10 April 2018

Social login in Angular 5 with Laravel Api

Hi Everybody,

Nowdays everyone want single signon instead of treditional login. In this blog we will focus on how to do social login in Angular 5 and using backend as Laravel

Install via npm

npm install --save angular5-social-login

Import the module

In app.module.ts,
...
import {
    SocialLoginModule,
    AuthServiceConfig,
    GoogleLoginProvider,
    FacebookLoginProvider,
} from "angular5-social-login";
// Configs 
export function getAuthServiceConfigs() {
  let config = new AuthServiceConfig(
      [
        {
          id: FacebookLoginProvider.PROVIDER_ID,
          provider: new FacebookLoginProvider("Your-Facebook-app-id")
        },
        {
          id: GoogleLoginProvider.PROVIDER_ID,
          provider: new GoogleLoginProvid("Your-Google-Client-Id")
        },
      ];
  );
  return config;
}
@NgModule({
  imports: [
    ...
    SocialLoginModule
  ],
  providers: [
    ...
    {
      provide: AuthServiceConfig,
      useFactory: getAuthServiceConfigs
    }
  ],
  bootstrap: [...]
})
export class AppModule { }

Usage :

In signin.component.ts,
import {Component, OnInit} from '@angular/core';
import {
    AuthService,
    FacebookLoginProvider,
    GoogleLoginProvider
} from 'angular5-social-login';
@Component({
  selector: 'app-signin',
  templateUrl: './signin.component.html',
  styleUrls: ['./signin.component.css']
})
export class SigninComponent implements OnInit {
  constructor( private socialAuthService: AuthService ) {}
  
  public socialSignIn(socialPlatform : string) {
    let socialPlatformProvider;
    if(socialPlatform == "facebook"){
      socialPlatformProvider = FacebookLoginProvider.PROVIDER_ID;
    }else if(socialPlatform == "google"){
      socialPlatformProvider = GoogleLoginProvider.PROVIDER_ID;
    }
    
    this.socialAuthService.signIn(socialPlatformProvider).then(
      (userData) => {
        console.log(socialPlatform+" sign in data : " , userData);
        // Now sign-in with userData
        ...
            
      }
    );
  }
  
}
In signin.component.html,
<h1>
     Sign in
</h1>
<button (click)="socialSignIn('facebook')">Sign in with Facebook</button>
<button (click)="socialSignIn('google')">Signin in with Google</button>              

Facebook App Id :

You need to create your own app by going to Facebook Developers page. Add Facebook loginunder products and configure Valid OAuth redirect URIs.

Google Client Id :

Follow this official documentation on how to Create a Google API Console project and client ID.

Sunday, 25 February 2018

Alexa skill introduction

Hi Everybody,


After a long time, i am writing this blog. In nowadays Artificial Intelligence is more popular. So i found Amazon Alexa is an example of AI.
So in this blog i am writing introduction of Alexa skill


Alexa introduction




What is Alexa?


You may have heard of Amazon Echo, the voice-enabled speaker from Amazon that allows you to get things done, by using your voice. The brain behind Echo and other Amazon voice-enabled devices like Echo Show, Echo Dot, and Amazon Tap is Alexa — the cloud based service that handles all the speech recognition, machine learning, and Natural Language Understanding for all Alexa enabled devices. Alexa provides a set of built-in capabilities, referred to as skills, that define how you can interact with the device. For example, Alexa’s built-in skills include playing music, reading the news, getting a weather forecast, and querying Wikipedia. So, you could say things like: Alexa, play Michael Jackson Alexa, what's the weather in New York In addition to these built-in skills, you can program custom skills by using the Alexa Skills Kit (ASK). An Alexa user can then access these new abilities by asking Alexa questions or making requests.
The brain behind Echo and other Amazon voice-enabled devices like Echo Show, Echo Dot, and Amazon Tap is Alexa — the cloud based service that handles all the speech recognition, machine learning, and Natural Language Understanding for all Alexa enabled devices. Alexa provides a set of built-in capabilities, referred to as skills, that define how you can interact with the device. For example, Alexa’s built-in skills include playing music, reading the news, getting a weather forecast, and querying Wikipedia. So, you could say things like: Alexa, play Michael Jackson Alexa, what's the weather in New York In addition to these built-in skills, you can program custom skills by using the Alexa Skills Kit (ASK). An Alexa user can then access these new abilities by asking Alexa questions or making requests.

Building an Alexa Skill

All skills, like web or mobile applications, contain two parts: Interaction Model (the frontend) and the Hosted Service (the backend).

Interaction Model (frontend)

Much like the graphical user interface (appearance) of a mobile app, Alexa skills need a Voice User Interface (VUI). We'll refer to the VUI as the interaction model — it defines what functionalities or behaviors the skill is able to handle.

Hosted Service (backend)

The programming logic, hosted on the internet, that responds to a user's requests. Interaction with an Alexa skill To begin a conversation with Alexa-Enabled devices, like the Amazon Echo, you say the word "Alexa", followed by the request, like: E.g Alexa, ask History Buff what happened on December seventh

Wake word

Here, "Alexa" is the default wake word. It wakes up the device and tells it that the user wants to talk to Alexa. "Alexa" is the wake word for all voice-enabled Amazon devices.

Starting phrase

Following the "Alexa" wake word, users must use a starting phrase — in this case "ask" — to specify the type of request they are using. Visit the Alexa developer documentation for a list of other starting phrases.


Invocation name

In the example above, "History Buff" is the invocation name. The user says "History Buff" to instruct Alexa to invoke the History Buff skill, a skill that retrieves historical events. Every skill, custom or built-in, has a unique invocation name.

Intents & Utterances

Let's say we want to create a Codecademy skill that will do just one thing — respond with a "Hello, Codecademy" message.

Intents

Before we get into designing the frontend and the backend, it's a good practice to think of the features or behaviors your skill will have. We call these behaviors intents. Our Codecademy skill is pretty basic. It will have only one intent — a "HelloIntent" that responds with a greeting. As we will see in later exercises, a typical skill will have multiple intents. Each intent defines a specific behaviour, like buttons on a web page. An intent takes user input and executes some code based on it.

Utterance

Speaking of user input, let's now think through some phrases our users might say which our skill should be able to respond to with a greeting. For example, our skill should give a response to the following greetings — e.g. hello how are you howdy what's up These are what we call sample utterances. They help Alexa connect the intents to phrases spoken by the user. In this case, these sample utterances will help Alexa map the spoken user input to our "HelloIntent".

Tuesday, 17 October 2017

Encryption user data in Laravel

Hi Everybody,

As you know, if you want user data(email, name etc) security in db, then you must encrypt data.
So at the time of adding data you need to encrypt data and at the time of retrieve data you need to decrypt data.
Below is the implementation of encryption and decryption of user data in Laravel

in Model(User.php)

<?php

namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
use App\Traits\EncryptableTrait;

class User extends Authenticatable {
{
    use EncryptableTrait;

    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['role_id', 'user_type', 'first_name', 'last_name', 'email', 'password', 'is_verified', 'status'];


    protected $encryptable = [
        'first_name', 'last_name', 'email'
    ]; 

}


Here i have written encrypt and decrypt code in trait EncryptableTrait.php

<?php
namespace App\Traits;

use Illuminate\Support\Facades\Crypt;

trait EncryptableTrait {

    protected $encryptKey;

    public function getAttribute($key)
    {
        $value = parent::getAttribute($key);

        if (in_array($key, $this->encryptable) && ( ! is_null($value)))
        {
            $value = $this->deCryptData($value);
        }

        return $value;
    }

    public function setAttribute($key, $value)
    {
        if (in_array($key, $this->encryptable))
        {
            $value = $this->encryptData($value);
        }
        return parent::setAttribute($key, $value);
    }

    private function encryptData($value)
    {
        $encryptValue = '';
        $cbSrc = strlen($value);
        $encryptKey = \Config::get('app.encryption_key');
        $encryptKeySize =  strlen($encryptKey);   
        for($NdxKey = 0, $i = 0; $i < $cbSrc; $i++)
        {
            $encryptValue .= sprintf("%02X", (ord($value[$i]) ^ ord($encryptKey[$NdxKey++])) & 0xFF);
                        
            if ($NdxKey >= $encryptKeySize)
                $NdxKey = 0;
        }
        return $encryptValue;   
    }

    private function deCryptData($value)
    {
        $decryptValue = '';
        $cbSrc = strlen($value);
        $encryptKey = \Config::get('app.encryption_key');
        $encryptKeySize =  strlen($encryptKey);   
        $deVal = null;
        
        for($NdxKey = 0, $i = 0; $i < $cbSrc; $i += 2)
        {
            sscanf($value[$i] . $value[$i + 1], "%x", $deVal);
            $decryptValue .= sprintf("%c", ($deVal ^ ord($encryptKey[$NdxKey++])) & 0xFF);
            
            if ($NdxKey >= $encryptKeySize) 
                $NdxKey = 0;
        }
        return $decryptValue;   
    }

?>

Note:-You can use laravel predefined encrypt method here, but this method give you different encrypt string for same string, but the method i have used provide same encrypted value all time

in config/app.php

    'encryption_key' => env('APP_KEY'),

This APP_KEY should never change.

Thanks.

Browser back button after logout Laravel

Hi Everybody,

After a long time i am posting this.

It is normal issue, after logout when user click on browser back button, it display dashboard or after login pages some time.
So fix this issue in laravel we can use middleware.

Create middleware

php artisan make:middleware RevalidateBackHistory
Within RevalidateBackHistory middleware, we set the header to no-cache and revalidate.
<?php
 
namespace App\Http\Middleware;
 
use Closure;
 
class RevalidateBackHistory
{
 /**
 * Handle an incoming request.
 *
 * @param \Illuminate\Http\Request $request
 * @param \Closure $next
 * @return mixed
 */
 public function handle($request, Closure $next)
 {
 $response = $next($request);
  
 return $response->header('Cache-Control','nocache, no-store, max-age=0, must-revalidate')
 ->header('Pragma','no-cache')
 ->header('Expires','Fri, 01 Jan 1990 00:00:00 GMT');
 }
}
Update the application’s route middleware in Kernel.php
protected $routeMiddleware = [
    .
    .
    'revalidate' => \App\Http\Middleware\RevalidateBackHistory::class,
    .
    .
    ];
And that’s all! So basically you just need to call revalidate middleware for routes which require user authentication.

Thanks...