3

With the laravel 5.3 and above the concept of filters is gone and middleware is used instead. I have migrated my project with laravel 4 to 5.4.

I want to modify the DeviceLoginController that is when I am not logged in it must refresh to the login page. Other details can be seen in the controller page.

Problem: The controller page is useless as even when I am not logged in anyone can access this page and and anyone can fill anything. I have been trying to resolve this issue from 2 days still I am no where.

DeviceLoginController page looks like this:

    <?php

    namespace App\Http\Controllers;
    use App\Http\Controllers\BaseController;
    use Auth;
    use Format;
    use Input;
    use DB;
    use Session;
    use Validator;
    use Hash;
    use Redirect;
    use User;
    use App\Models\License;
    use App\Models\LicenseCount;
    use App\Models\Manufacturer;
    use App\Models\DeviceModel as Model;
    use App\Models\Device;
    use App\Models\Application;

    class DeviceLoginController extends BaseController {

     /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
       $this->middleware('auth');
    }


    public function attempt() 
    {
        $username = Format::ltr(Input::get("username"));
        $device_key = Input::get("device_key");
        $imei = Format::ltr(Input::get('imei'));
        $model = Format::utr(Input::get('model'));
        $manufacturer = Format::utr(Input::get('manufacturer'));
        $app_code = Format::ltr(Input::get('app_code'));

        $user = User::where('username', $username)->first();
        if(!Hash::check($device_key, $user->device_key)) {
            Event::fire('auth.login.fail', array($username, Request::getClientIp(), time()));
            die("1");
        }
        Auth::loginUsingId($user->id);

        // check if device is already registered under given user for given app
        $license = License::where('device_imei', $imei)->where('app_code', $app_code)->where('user_username', $username);

        // if device isn't registered, first check if device is registered by different user. If not, check if licenses are available or not with the user to register new device
        if(!$license->count()) {

            // checking if licenses are available or not
            $license_count = LicenseCount::where('user_username', $username)->where('app_code', $app_code)->first();
            // if licenses are left, register the device
            if((int) $license_count['left']) {
                $manufacturer = Manufacturer::firstOrCreate(array('name' => $manufacturer));
                $model = Model::firstOrCreate(array('name' => $model, 'manufacturer_code' => $manufacturer->code));
                $device = Device::where('imei', $imei)->first();
                if(!$device) {
                    $device = Device::firstOrCreate(array('imei' => $imei, 'model_code' => $model->code));
                }
                License::create(array('device_imei' => $imei, 'app_code' => $app_code, "user_username" => $username, "expiry_date" => date("Y-m-d H:i:s", strtotime("+1 year"))));

                $license_count->left = Format::itr($license_count->left) - 1;
                $license_count->save();
            } else {
                // Prints 3, if the device is not registered and user has no more licenses left for the given app
                die("3");
            }
            // Prints 2, if the device was not previously registered and it is now registered under given user for given app
            Session::put('login_response', '2');
        } else {
            // Prints 0, if device is already registered under given user for given app
            Session::put('login_response', '0');
        }

    }
}

My authenticate.php file looks like this

<?php

namespace Illuminate\Auth\Middleware;

use Closure;
use Illuminate\Auth\AuthenticationException;
use Illuminate\Contracts\Auth\Factory as Auth;

class Authenticate
{
    /**
     * The authentication factory instance.
     *
     * @var \Illuminate\Contracts\Auth\Factory
     */
    protected $auth;

    /**
     * Create a new middleware instance.
     *
     * @param  \Illuminate\Contracts\Auth\Factory  $auth
     * @return void
     */
    public function __construct(Auth $auth)
    {
        $this->auth = $auth;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string[]  ...$guards
     * @return mixed
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    public function handle($request, Closure $next, $guards=null)
    {
        if($this->auth ->guest())
        {
            if($request->ajax())
            {
                return response('unauthorized',401);
            }
            else
            {
                return redirect()->guest('login');
            }
        }
        //$this->authenticate($guards);

        return $next($request);
    }

    /**
     * Determine if the user is logged in to any of the given guards.
     *
     * @param  array  $guards
     * @return void
     *
     * @throws \Illuminate\Auth\AuthenticationException
     */
    protected function authenticate(array $guards)
    {
        if (empty($guards)) {
            return $this->auth->authenticate();
        }

        foreach ($guards as $guard) {
            if ($this->auth->guard($guard)->check()) {
                return $this->auth->shouldUse($guard);
            }
        }

        throw new AuthenticationException('Unauthenticated.', $guards);
    }
}

I am new to Laravel please forgive me if I have asked some silly question. I am clueless what to do at this point. Please help and let me know if I need to add some other file.

1 Answer 1

3

It's great you have done the migration to Laravel 5.4. However, I suggest you go through the documentation first or watch the Laravel 5.4 from Scratch series.

For your question, you need the put the route that calls the controller function under the 'auth' middleware. Laravel provides this middleware out of the box. You can change the route to where the user will be redirected if he is not logged and calls the route.

Please go through the documentation for this.

Suppose your route is 'admin/profile' and you have defined this in the web.php routes file, you can add a middleware to it as shown (picked this example from the DOC.)

Route::get('admin/profile', function () {
    //
})->middleware('auth');

To place multiple routes under the same middleware, you can use Route groups.

Sign up to request clarification or add additional context in comments.

5 Comments

Please remove the middleware from the controller constructor. Where are you using the authenticate.php file ? It's not needed imo.
sir I have added the route already Route::get('login','DeviceLoginController@attempt')->middlew‌​are('auth');
yeah done that before adding middleware('auth') in the route file . have added one more route in web.php Route::post('device',array('uses' => 'DeviceLoginController@attempt', 'as' => 'pages.device.'));
Also, are you sure this should be a GET route ? Change it to POST. Try running composer dump-autoload in the terminal.
Thanks sir for your answer .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.