Skip to content

Commit

Permalink
config/main update readme; adding coday to ci workflow; using jwt for…
Browse files Browse the repository at this point in the history
… auth; updating tests; readme for updates on auth not updated as its not final
  • Loading branch information
2amjsouza committed Aug 7, 2023
1 parent 710edcb commit 9ba5ffd
Show file tree
Hide file tree
Showing 16 changed files with 890 additions and 80 deletions.
1 change: 1 addition & 0 deletions .env.testing
Expand Up @@ -32,3 +32,4 @@ REDIS_PASSWORD=null
REDIS_PORT=6379

TOKEN_TIME=60
JWT_SECRET=iDSfvEBNlTUELHBvmJa0QnNuSYrJvK3m2y3KVp89knAG6GVuHAvKwFIqkGCP55US
8 changes: 7 additions & 1 deletion .github/workflows/ci.yml
Expand Up @@ -40,4 +40,10 @@ jobs:
run: php artisan migrate -v

- name: Laravel PHPUnit
run: php artisan test
run: php artisan test --coverage-clover ./coverage.xml

- name: Upload coverage reports to Codacy
uses: codacy/codacy-coverage-reporter-action@v1
with:
project-token: ${{ secrets.CODACY_PROJECT_TOKEN }}
coverage-reports: ./coverage.xml
55 changes: 35 additions & 20 deletions README.md
Expand Up @@ -6,11 +6,11 @@
</a>
</p>

<p align="center">
<a href="https://github.com/2amigos/laravel-mail-api/actions/workflows/ci.yml">
<img src="https://github.com/2amigos/laravel-mail-api/actions/workflows/ci.yml/badge.svg">
</a>
</p>

[![Build](https://github.com/2amigos/laravel-mail-api/actions/workflows/ci.yml/badge.svg)](https://github.com/2amigos/laravel-mail-api/actions/workflows/ci.yml)
[![Software License](https://img.shields.io/badge/license-BSD-brightgreen.svg?style=flat-square)](LICENSE.md)
[![code coverage - change](https://github.com/2amigos/laravel-mail-api/actions/workflows/ci.yml/badge.svg)](https://github.com/2amigos/laravel-mail-api/actions/workflows/ci.yml)
[![code qualit - change](https://github.com/2amigos/laravel-mail-api/actions/workflows/ci.yml/badge.svg)](https://github.com/2amigos/laravel-mail-api/actions/workflows/ci.yml)

## About Mail API Service

Expand Down Expand Up @@ -42,10 +42,10 @@ To start up/stop the docker container, use the following commands:

```SH
// to start up the container
./vendor/bin/sail up -d
$ ./vendor/bin/sail up -d

# to stop the container
./vendor/bin/sail stop
$ ./vendor/bin/sail stop
```

If you're using Laravel Sail, refer to **.env.sail** for mysql and redis connection setup.
Expand All @@ -57,22 +57,22 @@ The **.env.example** file gives the basic structure your project must have in or
After configuring your database connection on your **.env** file, you're ready to migrate the necessary tables through the command bellow:

```SH
php artisan migrate
$ php artisan migrate
```

or, if you are using Sail

```SH
./vendor/bin/sail php artisan migrate
$ ./vendor/bin/sail php artisan migrate
```

Now, with the database set, the user can be created by running the next command, and following a couple of simple steps.

```SH
php artisan app:create-user
$ php artisan app:create-user

# or on sail
./vendor/bin/sail php artisan app:create-user
$ ./vendor/bin/sail php artisan app:create-user
```

### Email Transport Configuration
Expand All @@ -91,18 +91,18 @@ MAIL_ENCRYPTION=tls
```

The project has [Laravel Pint](https://laravel.com/docs/10.x/pint) configured, you can run the command bellow to assure the code style is being followed:
```
./vendor/bin/pint --config pint.json
```SH
$ ./vendor/bin/pint
```

## Usage

To serve the application, Laravel provides the handy built in command **serve**
```SH
php artisan serve
$ php artisan serve

# or on Sail
./vendor/bin/sail php artisan serve
$ ./vendor/bin/sail php artisan serve
```

This command serve your application at [http://127.0.0.1:8000](http://127.0.0.1:8000).
Expand All @@ -123,7 +123,7 @@ The `basic-token` can be obtained by `echo -n email:password | base64`
Here is a `/token` request example:

```SH
curl --location --request POST 'http://localhost/api/token'
$ curl --location --request POST 'http://localhost/api/token'
\ --header 'Authorization: Basic {basic_token}'
```

Expand All @@ -147,7 +147,7 @@ Then you can send `multipart/form-data` request with the following parameters:
Here is a sample request:

```SH
curl --location 'http://localhost/api/send-message' \
$ curl --location 'http://localhost/api/send-message' \
--header 'Authorization: Bearer {token}' \
--form 'from="{email-sender@domain}"' \
--form 'sender="Mark"' \
Expand All @@ -164,9 +164,10 @@ Done. Now your new message is on the queue, ready to be dispatched. To achieve t
you just need to run this command:

```SH
php artisan queue:work
// or on sail
./vendor/bin/sail php artisan queue:work
$ php artisan queue:work

# or on sail
$ ./vendor/bin/sail php artisan queue:work
```

#### Email Attachments
Expand Down Expand Up @@ -217,3 +218,17 @@ Although the queue work command is handy and makes it really easy to consume the
but it's extremely recommended to use [Supervisor](http://supervisord.org/) when deploying to production.

Laravel has a nice guide to properly [configure](https://laravel.com/docs/10.x/queues#supervisor-configuration) the Supervisor.

## Contributing

Please, see [CONTRIBUTING](./contributing.md) for details.

## License
The BSD License (BSD). Please see [License File](./license.md) for more information/

> <img src="">
Web development has never been so fun!

[https://2am.tech/](https://2am.tech/)

77 changes: 77 additions & 0 deletions app/Http/Controllers/Api/AuthController.php
@@ -0,0 +1,77 @@
<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;

class AuthController extends Controller
{
/**
* Create a new AuthController instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('auth:api', ['except' => ['login']]);
}

/**
* Get a JWT via given credentials.
*
* @return \Illuminate\Http\JsonResponse
*/
public function login(Request $request)
{
$credentials = [
'email' => $request->getUser(),
'password' => $request->getPassword(),
];

if (! $token = auth()->attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}

return $this->respondWithToken($token);
}

/**
* Log the user out (Invalidate the token).
*
* @return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();

return response()->json(['message' => 'Successfully logged out']);
}

/**
* Refresh a token.
*
* @return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh(true));
}

/**
* Get the token array structure.
*
* @param string $token
*
* @return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
}
2 changes: 1 addition & 1 deletion app/Http/Controllers/Api/SendEmail.php
Expand Up @@ -11,7 +11,7 @@

class SendEmail extends Controller
{
public function __invoke(Request $request)
public function send(Request $request)
{
$this->validateRequest($request);

Expand Down
15 changes: 8 additions & 7 deletions app/Http/Middleware/CheckAuth.php
Expand Up @@ -19,15 +19,16 @@ public function handle(Request $request, Closure $next)
{
Log::info('Check user authentication');

if (! (Auth::guard('user')->check() || Auth::check())) {
$exception = new UnauthorizedException('Unauthorized.');
if ($request->path() !== 'api/token/login') {
if (! Auth::check()) {
$exception = new UnauthorizedException('Unauthorized.');

Log::error($exception->getMessage());
throw $exception;
}

Log::info('Authenticated');
Log::error($exception->getMessage());
throw $exception;
}

Log::info('Authenticated');
}
return $next($request);
}
}
13 changes: 12 additions & 1 deletion app/Models/User.php
Expand Up @@ -7,13 +7,14 @@
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Tymon\JWTAuth\Contracts\JWTSubject;

/**
* @property string $name
* @property string $email
* @property string password
*/
class User extends Authenticatable
class User extends Authenticatable implements JWTSubject
{
use HasApiTokens;
use HasFactory;
Expand Down Expand Up @@ -49,4 +50,14 @@ class User extends Authenticatable
protected $casts = [
'email_verified_at' => 'datetime',
];

public function getJWTIdentifier()
{
return $this->getKey();
}

public function getJWTCustomClaims()
{
return [];
}
}
3 changes: 2 additions & 1 deletion composer.json
Expand Up @@ -26,7 +26,8 @@
"laravel/framework": "^10.0",
"laravel/sanctum": "^3.2",
"laravel/tinker": "^2.8",
"predis/predis": "^2.2"
"predis/predis": "^2.2",
"tymon/jwt-auth": "^2.0"
},
"require-dev": {
"fakerphp/faker": "^1.9.1",
Expand Down

0 comments on commit 9ba5ffd

Please sign in to comment.