Skip to content

feat(api): Implement authentication and user management #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Nov 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .github/workflows/checks.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,5 @@ jobs:
run: php artisan test
- name: Lint code
run: composer pint:test
- name: Generate swagger documentation
run: composer openapi
- name: Ensure OpenAPI documentation is up to date
run: composer openapi:test
25 changes: 25 additions & 0 deletions app/Events/UserRegisteredEvent.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php

namespace App\Events;

use App\Models\User;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class UserRegisteredEvent
{
use Dispatchable, InteractsWithSockets, SerializesModels;

/**
* Create a new event instance.
*
* @return void
*/
public $user;

public function __construct(User $user)
{
$this->user = $user;
}
}
129 changes: 129 additions & 0 deletions app/Http/Controllers/API/v1/Auth/AuthController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
<?php

namespace App\Http\Controllers\API\v1\Auth;

use App\Events\UserRegisteredEvent;
use App\Http\Controllers\API\ApiController;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use OpenApi\Attributes as OA;

class AuthController extends ApiController
{
#[OA\Post(
path: '/register',
tags: ['Authentication'],
summary: 'Register a new user',
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['email', 'first_name', 'password'],
properties: [
new OA\Property(property: 'email', type: 'string', format: 'email'),
new OA\Property(property: 'first_name', type: 'string'),
new OA\Property(property: 'last_name', type: 'string'),
new OA\Property(property: 'username', type: 'string'),
new OA\Property(property: 'phone', type: 'string'),
new OA\Property(property: 'password', type: 'string', format: 'password'),
]
)
),
responses: [
new OA\Response(response: 201, description: 'User registered successfully'),
new OA\Response(response: 422, description: 'Validation error'),
]
)]
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|string|email|max:255|unique:users',
'first_name' => 'required|string|max:255',
'last_name' => 'string|max:255',
'username' => 'string|max:255',
'phone' => 'string|max:255',
'password' => 'required|string|min:8',
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add better constraints

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

last_name, username and phone are optional.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Was thinking of password constraints. We can change that at any time.

]);

if ($validator->fails()) {
return $this->failure('Validation failed.', 422, [$validator->errors()]);
}

$user_data = $request->only(['first_name', 'last_name', 'email', 'password', 'phone', 'username']);
$user_data['password'] = Hash::make($request->password);

$user = User::create($user_data);
UserRegisteredEvent::dispatch($user);

$response = [
'user' => $user,
'token' => $user->createToken('auth-token')->plainTextToken,
];

return $this->success($response, 'User registered successfully', 201);
}

#[OA\Post(
path: '/login',
tags: ['Authentication'],
summary: 'User login',
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['password'],
properties: [
new OA\Property(property: 'email', type: 'string', format: 'email'),
new OA\Property(property: 'phone', type: 'string'),
new OA\Property(property: 'username', type: 'string'),
new OA\Property(property: 'password', type: 'string', format: 'password'),
]
)
),
responses: [
new OA\Response(response: 200, description: 'User successfully logged in'),
new OA\Response(response: 401, description: 'Invalid credentials'),
new OA\Response(response: 500, description: 'Server error'),
]
)]
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required_without_all:phone,username|email',
'phone' => 'required_without_all:email,username|string',
'username' => 'required_without_all:email,phone|string',
'password' => 'required|string|min:6',
]);

if ($validator->fails()) {
return $this->failure('Validation failed.', 422, [$validator->errors()]);
}

$identifier_field = $request->has('email') ? 'email'
: ($request->has('phone') ? 'phone' : 'username');

$credentials = [
$identifier_field => $request->$identifier_field,
'password' => $request->password,
];

try {
$user = User::where($identifier_field, $credentials[$identifier_field])->first();

if (! $user || ! auth()->attempt($credentials)) {
return $this->failure('Invalid credentials', 401);
}

return $this->success([
'token' => $user->createToken('auth-token')->plainTextToken,
'token_type' => 'Bearer',
'user' => auth()->user(),
], 'User successfully logged in', 200);
} catch (\Exception $e) {
Log::error('An error occurred during login: '.$e->getMessage(), ['exception' => $e]);

return $this->failure('An error occurred during login', 500);
}
}
}
170 changes: 170 additions & 0 deletions app/Http/Controllers/API/v1/Auth/PasswordResetController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
<?php

namespace App\Http\Controllers\API\v1\Auth;

use App\Http\Controllers\API\ApiController;
use App\Models\User;
use App\Models\VerificationCode;
use App\Services\NotificationService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use OpenApi\Attributes as OA;

class PasswordResetController extends ApiController
{
public function __construct(private NotificationService $notificationService) {}

#[OA\Post(
path: '/password/reset-code',
tags: ['Authentication'],
summary: 'Send password reset code',
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['email'],
properties: [
new OA\Property(
property: 'email',
type: 'string',
format: 'email',
description: 'The email address of the user'
),
]
)
),
responses: [
new OA\Response(
response: 200,
description: 'Password reset code sent successfully',
content: new OA\JsonContent(
properties: [
new OA\Property(
property: 'message',
type: 'string',
example: 'Password reset code sent successfully.'
),
]
)
),
new OA\Response(
response: 422,
description: 'Validation error'
),
]
)]
public function sendPasswordResetCode(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|exists:users,email',
]);

if ($validator->fails()) {
return $this->failure('Validation failed.', 422, [$validator->errors()]);
}

$email = $request->email;
$verificationCode = random_int(100000, 999999);
$expiresAt = now()->addMinutes(15);

VerificationCode::updateOrCreate(
['contact' => $email, 'purpose' => 'password_reset'],
['code' => $verificationCode, 'expires_at' => $expiresAt]
);

$this->notificationService->sendEmailNotification([
'to' => $email,
'subject' => __('Password Reset Code'),
'body' => __('Your password reset code for Trakli is: ').$verificationCode,
]);

return $this->success([], 'Password reset code sent successfully.');
}

#[OA\Post(
path: '/password/reset',
tags: ['Authentication'],
summary: 'Reset password using verification code',
requestBody: new OA\RequestBody(
required: true,
content: new OA\JsonContent(
required: ['email', 'code', 'new_password'],
properties: [
new OA\Property(
property: 'email',
type: 'string',
format: 'email',
description: 'The email address of the user'
),
new OA\Property(
property: 'code',
type: 'integer',
description: 'The verification code sent to the user'
),
new OA\Property(
property: 'new_password',
type: 'string',
description: 'The new password for the user'
),
]
)
),
responses: [
new OA\Response(
response: 200,
description: 'Password reset successful',
content: new OA\JsonContent(
properties: [
new OA\Property(
property: 'message',
type: 'string',
example: 'Password has been reset successfully.'
),
]
)
),
new OA\Response(
response: 422,
description: 'Validation error'
),
new OA\Response(
response: 400,
description: 'Invalid or expired code'
),
]
)]
public function resetPasswordWithCode(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email|exists:users,email',
'code' => 'required|integer',
'new_password' => 'required|string|min:8',
]);

if ($validator->fails()) {
return $this->failure('Validation failed.', 422, [$validator->errors()]);
}

$codeEntry = VerificationCode::where('contact', $request->email)
->where('purpose', 'password_reset')
->first();

if (! $codeEntry || $codeEntry->code != $request->code || $codeEntry->isExpired()) {
return $this->failure('Invalid or expired code.', 400);
}

$user = User::where('email', $request->email)->first();
$user->password = Hash::make($request->new_password);
$user->save();

$this->notificationService->sendEmailNotification([
'to' => $request->email,
'subject' => __('Your password was changed'),
'body' => __('Password has been reset successfully. If you did nt make this change, please contact us.'),
]);

$codeEntry->delete();

return $this->success([], 'Password has been reset successfully.');
}
}
10 changes: 5 additions & 5 deletions app/Http/Controllers/API/v1/PartyController.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
class PartyController extends ApiController
{
#[OA\Get(
path: '/api/parties',
path: '/parties',
summary: 'List all parties',
tags: ['Party'],
responses: [
Expand Down Expand Up @@ -44,7 +44,7 @@ public function index(): JsonResponse
}

#[OA\Post(
path: '/api/parties',
path: '/parties',
summary: 'Create a new party',
tags: ['Party'],
requestBody: new OA\RequestBody(
Expand Down Expand Up @@ -90,7 +90,7 @@ public function store(Request $request): JsonResponse
}

#[OA\Get(
path: '/api/parties/{id}',
path: '/parties/{id}',
summary: 'Get a specific party',
tags: ['Party'],
parameters: [
Expand Down Expand Up @@ -133,7 +133,7 @@ public function show(int $id): JsonResponse
}

#[OA\Put(
path: '/api/parties/{id}',
path: '/parties/{id}',
summary: 'Update a specific party',
tags: ['Party'],
parameters: [
Expand Down Expand Up @@ -196,7 +196,7 @@ public function update(Request $request, int $id): JsonResponse
}

#[OA\Delete(
path: '/api/parties/{id}',
path: '/parties/{id}',
summary: 'Delete a specific party',
tags: ['Party'],
parameters: [
Expand Down
14 changes: 14 additions & 0 deletions app/Http/Controllers/API/v1/UserController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php

namespace App\Http\Controllers\API\v1;

use App\Http\Controllers\API\ApiController;
use Illuminate\Http\Request;

class UserController extends ApiController
{
public function show(Request $request)
{
return $this->success($request->user());
}
}
Loading