Friday, November 13, 2015

Multipule table authentication using laravel 5.1

 Multipule table authentication using laravel 5.1:

1. Install laravel 5.1
2.Open terminal and go to laravel instalation folder.
3.Run the following command.
composer require sarav/laravel-mltiauth dev-master
4.Open config/app.php
Replace Illuminate\Auth\AuthServiceProvider:: class with Sarav\Multiauth\MultiauthServiceProvider

5.Modify auth.php
'multi' => [
    'user' => [
        'driver' => 'eloquent',
        'model'  => App\User::class,
        'table'  => 'users'
    ],
    'admin' => [
        'driver' => 'eloquent',
        'model'  => App\Admin::class,
        'table'  => 'admins'
    ]
],
6. Create admins table
7.login using follwing details.
\Auth::attempt("user", ['email' => 'johndoe@gmail.com', 'password' => 'password']);

// Attempts to login admin with email id johndoe@gmail.com
\Auth::attempt("admin", ['email' => 'johndoe@gmail.com', 'password' => 'password']);

Friday, November 6, 2015

Login after admin approval in Laravel 5.1

Login after admin approval in Laravel 5.1:

In Laravel 5.1, here is a system that when we register any user then it's by default logged in. If we want to make a system in which we are in need of admin approval then we have to make it like the following code:

Login after admin approval in Laravel

We have to override two method for this:

1. postLogin
2. postRegister


Open your this file app/Http/Controllers/Auth/AuthController.php

and add these functions.

Login after admin approval in Laravel


    public function postRegister(Request $request)
    {
        $validator = $this->validator($request->all());
        if ($validator->fails()) {
            $this->throwValidationException(
                $request, $validator
            );
        }
        $this->create($request->all());
        return redirect('/auth/login')->with('status', 'Successfully Registered! You can login after the approval of admin.');
    }



Login after admin approval in Laravel

    public function postLogin(Request $request)
    {
        $this->validate($request, [
            $this->loginUsername() => 'required', 'password' => 'required',
        ]);

        $throttles = $this->isUsingThrottlesLoginsTrait();

        if ($throttles && $this->hasTooManyLoginAttempts($request)) {
            return $this->sendLockoutResponse($request);
        }

        $credentials = $this->getCredentials($request);
        $credentials['status'] = 'active';

        if (Auth::attempt($credentials, $request->has('remember'))) {
            return $this->handleUserWasAuthenticated($request, $throttles);
        }

        if ($throttles) {
            $this->incrementLoginAttempts($request);
        }

        return redirect($this->loginPath())
            ->withInput($request->only($this->loginUsername(), 'remember'))
            ->withErrors([
                $this->loginUsername() => $this->getFailedLoginMessage(),
            ]);
    }


Login after admin approval in Laravel



In postRegister() function there will only registration is possible & in postLogin() we will firstly check its status.


Here in this function $credentials['status'] = 'active' will check if its approved by admin or not.

Here status is my field name in users table and active is its value.

This will work.

Thanks

Friday, October 30, 2015

How to create name based subdomain in apache2 conf.

Create name based subdomain in apache2 conf.:

Some or many time we need to set the same document root for all or almost
each sub domains to a same document root, we can simply do it with apache virtual host  setting as following.

For say if we want that all sub domains of example.com should be hosted on same server and share the same document root then we can use apache web server's ServerAlias Directive as follows

Open this file: /etc/apache2/sites-enabled/000-default.conf

and set this code:


<VirtualHost *:80>
ServerName example.com
ServerAlias server server2.domain.com server2
ServerAlias *.example.com
</VirtualHost>
 

Thanks

Friday, October 23, 2015

How to deploy an ionic app on heroku?

Deploy an ionic app on Heroku:

For deploy your project on heroku as a serving host we can do the following

steps:

1:- At first create a heroku account and install Heroku Toolbelt on your ubuntu system as  directed in following link

https://toolbelt.heroku.com/debian

2. Now initialize a git repository and commit all code to it

as following

git init



3. add heroku remote as following

heroku login

heroku create appname

it gives you back a git and heroku serve url on successful creation.


4. Now go to your terminal and reach to project root you want to deploy on

heroku install any dependencies needed to deploy for example if it a ionic app

as per my case we need to do as follows

npm install express --save

and create the following files

a app.json and write the following code

{

    "name": "app name",

    "description": "App description",

    "repository": "heroku serve url",

    "keywords": ["Keyword1", "Keyword2", "Keyword3"]

}


and a server.js and write the following code to serve node application

var express = require('express'),

    app = express();

app.use(express.static('www'));

app.set('port', process.env.PORT || 5000);

app.listen(app.get('port'), function () {

    console.log('Express server listening on port ' + app.get('port'));

});

and some other dependencies as well should be installed first.

5. Now do the following

git commit -am"comment for version"

git push heroku master

as heroku is the remote name by default created by heroku on app creation

and master is the default git branch.

Got to tour app serve url and check for it.

Thanks

Friday, October 16, 2015

Route Model Binding using laravel 5.1

Route Model binding using Laravel 5.1:

What is Route Model Binding in laravel?
Ans: Laravel model binding provides a convenient way to inject class instances into  routes. For example, instead of injecting a user's ID, you can inject the entire User class instance that matches the given ID.

1. Open route.php and write following code .

Route::model('users', 'User');
Route::bind('users', function($value, $route) {
    return App\Task::whereSlug($value)->first();
)};
Route::resource('users', 'UsersController');

 Note: where User is Model name 

2. use users/{slug} as url instead of users/{id}

3. use controller method update({slug}) instead of update({id})

Thanks

Friday, October 9, 2015

How to send email through terminal in ubuntu?

Send email through terminal in ubuntu:

Hi everybody,

In this blog we will cover email sending through terminal in ubuntu.

1. For send a email through terminal firstly install the postfix using this

sudo apt-get install postfix
 
2. Now go to this file

sudo nano /etc/postfix/main.cf

and change

myhostname = example.com

3. Put in name of your domain into myhostname.

4. If you want to have mail forwarded to other domains, replace alias_maps with virtual_alias_maps and point it to /etc/postfix/virtual.

virtual_alias_maps = hash:/etc/postfix/virtual

5. The rest of the lines are set by default. Save, exit, and reload the configuration file to put your changes into effect:

sudo /etc/init.d/postfix reload

6. Now run this for checking through terminal

sendmail sample-email@example.org

Wednesday, September 23, 2015

Use Web Socket for Chat in Laravel 5 (Using Ratchet for particular user )

Use Web Socket for Chat in Laravel 5 step by step:

If you want to create a chat server for particular user in Laravel 5, then this blog will help you. Its a very easy and fast way to use web socket.

For this firstly you have to install Ratchet package in your application.

Step1:
For this open your composer.json and write this code in "require" key:

"cboden/ratchet": "0.3.*"

Now open open your terminal and go to your root path and run this command

composer update

It will install this package in your application.

Use Web Socket for Chat in Laravel 5


Step2:

Now create a controller and write functions on it , also include the package files.
For this , just go to your terminal and write this command:

php artisan make:controller ChatController


Now go to this file and write the following code on it:

<?php
namespace App\Http\Controllers;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class ChatController implements MessageComponentInterface
{
    protected $clients;
    private $subscriptions;
    private $users;

    public function __construct()
    {
        $this->clients = new \SplObjectStorage;
        $this->subscriptions = [];
        $this->users = [];
    }

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        $this->users[$conn->resourceId] = $conn;
    }

    public function onMessage(ConnectionInterface $conn, $msg)
    {
        $data = json_decode($msg);
        switch ($data->command) {
            case "subscribe":
                $this->subscriptions[$conn->resourceId] = $data->channel;
                break;
            case "message":
                if (isset($this->subscriptions[$conn->resourceId])) {
                    $target = $this->subscriptions[$conn->resourceId];
                    foreach ($this->subscriptions as $id=>$channel) {
                        if ($channel == $target && $id != $conn->resourceId) {
                            $this->users[$id]->send($data->message);
                        }
                    }
                }
        }
    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
        unset($this->users[$conn->resourceId]);
        unset($this->subscriptions[$conn->resourceId]);
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }
}
?>

Use Web Socket for Chat in Laravel 5

Now you have done all the functionality. Now you'll be in need of create a chat server .

Step3:

For create a chat server , go to your root path and create a file with named php_chat_server.php


write the following code in this file:

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use App\Http\Controllers\ChatController;

require  'vendor/autoload.php';


$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            new ChatController()
        )
    ),
    8080
);

$server->run();
?>



Use Web Socket for Chat in Laravel 5

Now you have to create a chat server.
You are done now.

Step4:

Now go to your root path and run this command:

php php_chat_server.php

This will start your chat server .

Step5:

For checking your working code, you have to go to your browser and open your localhost

For test you have to open two browser for this:

Now open your console in both browser and write this:

var conn = new WebSocket('ws://127.0.0.1:8080');

and then press enter

Use Web Socket for Chat in Laravel 5


same like this write the following lines and enter in both browser:

conn.onopen = function(e) {
  console.log("Connection established!");
};



conn.onmessage = function(e) {
  console.log(e.data);
};



conn.send(JSON.stringify({command: "subscribe", channel: "mychannel"}));

Now in only one browser's console write this code

conn.send(JSON.stringify({command: "message", message: "this is message"}));

You'll see this message at 2nd browser.

Use Web Socket for Chat in Laravel 5


You are done.

Thanks