Vue App with Lumen Passport API (Part II)
Tags: vue, lumen, laravel, php
Published: 2022-08-21 02:42:50

---
title: Vue App with Lumen Passport API (Part II)
published: true
description: 
tags: vue,lumen,laravel,php
cover_image: https://images.pexels.com/photos/60504/security-protection-anti-virus-software-60504.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2
# Use a ratio of 100:42 for best results.
---

## Auth or Auth?
Typically in Software development, there's need for some level of security wherever there is data involved. Authentication is the process of identifying who wants to access the data. Authorization on the other hand involves checking the access level of the person. With Passport we can achieve that.

## What we'll build
As stated in [Part I](https://dev.to/zichis/vue-app-with-lumen-passport-api-part-i-3dpn), the finished app will be a contacts app for users to save their contacts. In this part we will set up the API's with login and registration.

*Without further ado...*

## Setup Auth Controller and Routes
Before creating the controller, let's create a common success response in our base controller.

```php
<?php

namespace App\Http\Controllers;

use Laravel\Lumen\Routing\Controller as BaseController;

class Controller extends BaseController
{
    public function return_success($message, $data = [], $status = 200)
    {
        return [
            "message" => $message,
            "data" => $data,
            "status" => $status
        ];
    }
}
```

Now let's create the controller with the command.
> php artisan make:controller AuthController

We will add a registration and login methods to this controller.

```php
<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $this->validate($request, [
            'email' => 'required',
            'password' => 'required'
        ]);

        $user = User::where('email', $request->email)->first();
        if ($user) {
            if (Hash::check($request->password, $user->password)) {
                $token = $user->createToken('Laravel Password Grant Client')->accessToken;

                return $this->return_success("Login successful", ["token" => $token], Response::HTTP_OK);
            } else {
                $response = ["message" => "Password mismatch"];
                return response($response, 422);
            }
        } else {
            $response = ["message" => 'User does not exist'];
            return response($response, 422);
        }
    }

    public function register(Request $request)
    {
        $this->validate($request, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6|confirmed',
        ]);

        $request['password'] = Hash::make($request['password']);
        $request['remember_token'] = Str::random(10);
        $user = User::create($request->toArray());
        $token = $user->createToken('Laravel Password Grant Client')->accessToken;

        return $this->return_success("User created successfully", ["user" => $user, "token" => $token], Response::HTTP_CREATED);
    }
}

```

We have our login and registration methods in our controller, we can create the corresponding routes in our routes file i.e routes/web.php.

```php
$router->group(['prefix' => 'auth'], function() use ($router) {
    $router->post('login', 'AuthController@login');
    $router->post('register', 'AuthController@register');
});
```

### Test auth routes with postman
We register a user with postman
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/s6gb2zyezmayjxidnodj.png)

Registration is successful!!!

Let's try to login with the email and password we registered with.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m5lohgzn8d9azd0jkihu.png)

Login is successful!!!

Now, with the generated token after login, we can access authorized routes. Next, we will create the Contact model, migration and routes.

## Setup Contacts
We'll use the command to create model, migration and controller for contacts.
> php artisan make:model Contact -mc

Add necessary fields in migration.
```php
Schema::create('contacts', function (Blueprint $table) {
    $table->id();
    $table->foreignId('owner_id');
    $table->string('name');
    $table->string('email')->nullable();
    $table->string('phone_number')->unique();
    $table->date('birthday')->nullable();
    $table->timestamps();
});
```

The model will look like this:
```php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Contact extends Model
{
    protected $fillable = [
        'name',
        'email',
        'phone_number',
        'birthday',
        'owner_id'
    ];

    public function owner(): BelongsTo
    {
        return $this->belongsTo(User::class, 'owner_id');
    }
}
```

For the controller, we will add the crud methods needed.
```php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ContactController extends Controller
{
    public function index()
    {
        return $this->return_success("My contacts", auth('api')->user()->contacts, 200);
    }

    public function show($id)
    {
        /** @var User $user */
        $user = auth('api')->user();

        return $this->return_success("My contact", $user->contacts()->where('id', $id)->first(), 200);
    }

    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'phone_number' => 'required'
        ]);

        /** @var User $user */
        $user = auth('api')->user();

        $user->contacts()->create([
            'name' => $request->get('name'),
            'phone_number' => $request->get('phone_number'),
            'birthday' => $request->get('birthday'),
            'email' => $request->get('email')
        ]);

        return $this->return_success("My contacts", $user->contacts()->latest()->get(), 200);
    }

    public function update(Request $request, $id)
    {
        $this->validate($request, [
            'name' => 'required',
            'phone_number' => 'required'
        ]);

        /** @var User $user */
        $user = auth('api')->user();
        $contact = $user->contacts()->find($id);

        $contact->update([
            'name' => $request->get('name'),
            'phone_number' => $request->get('phone_number'),
            'birthday' => $request->get('birthday'),
            'email' => $request->get('email')
        ]);

        return $this->return_success("Contact updated", $contact, 200);
    }

    public function destroy($id)
    {
        /** @var User $user */
        $user = auth('api')->user();
        $contact = $user->contacts()->find($id);

        $contact->delete();

        return $this->return_success("Contact deleted", NULL, 200);
    }
}

```

Let's run our migration.
> php artisan migrate

Add contacts relationship in User model.
```php
public function contacts(): HasMany
{
    return $this->hasMany(Contact::class, 'owner_id');
}
```

Finally, we add the routes.
```php
$router->group(['middleware' => 'auth:api'], function() use ($router) {
    $router->get('contacts', 'ContactController@index');
    $router->get('contacts/{id}', 'ContactController@show');
    $router->post('contacts', 'ContactController@store');
    $router->patch('contacts/{id}', 'ContactController@update');
    $router->delete('contacts/{id}', 'ContactController@destroy');
});
```

## Test with Postman
First, you have to login. Copy the token generated and we will use it to create a contact.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6zkkli58fmmg9bp0qovn.png)

Provide necessary fields for creating a contact.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v3zb7rgpbbek9zith7ul.png)

Congratulations, you have created a contact for a logged user. 

In the next tutorial, we'll finish up the app and push it to Github.