Skip to content

Commit

Permalink
Merge branch 'feat/fetch-a-role-in-an-organisation-endpoint' of https…
Browse files Browse the repository at this point in the history
  • Loading branch information
sparkybug committed Aug 16, 2024
2 parents 44f812f + 5427a43 commit c7a872e
Show file tree
Hide file tree
Showing 20 changed files with 294 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ public function store(Request $request)

// Validate request data
$validatedData = $request->validate([
'title' => 'required|string|max:255',
'title' => 'required|string|max:255|unique:email_templates,title',
'template' => 'required|string',
'status' => 'required|boolean'
]);
Expand Down
78 changes: 51 additions & 27 deletions app/Http/Controllers/Api/V1/Auth/AuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreUserRequest;
use App\Http\Resources\UserResource;
use App\Models\EmailTemplate;
use Illuminate\Http\Request;
use App\Traits\HttpResponses;
use Illuminate\Http\Response;
Expand All @@ -13,15 +15,37 @@
use App\Models\User;
use App\Models\Organisation;
use App\Models\OrganisationUser;
use App\Services\OrganisationService;
use Illuminate\Support\Facades\Log;
use App\Models\Validators\AuthValidator;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rules\Password;

class AuthController extends Controller
{
use HttpResponses;

public function __construct(public OrganisationService $organisationService)
{
}
/**
* Display a listing of the resource.
*/
public function index()
{
//
}

/**
* Show the form for creating a new resource.
*/
public function register()
{
//
}

/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
Expand All @@ -33,61 +57,61 @@ public function store(Request $request)
]);

if ($validator->fails()) {
return $this->apiResponse(message: $validator->errors(), status_code: 400);
return $this->validationErrorResponseAlign($validator->errors());
}

try {
DB::beginTransaction();

$user = User::create([
'name' => $request->first_name . ' ' . $request->last_name,
'email' => $request->email,
'password' => Hash::make($request->password),
'role' => 'user'
]);

$profile = $user->profile()->create([
$user->profile()->create([
'first_name' => $request->first_name,
'last_name' => $request->last_name
]);

$organisations = [];
$name = $request->first_name."'s Organisation";
$organisation = $this->organisationService->create($user, $name);

if ($request->invite_token) {
// Handle invite logic here
// For now, we'll create a default org
$organization = $this->createDefaultOrganization($user);
$organisations[] = $this->formatOrganisation($organization, 'admin', true);
} else {
$organization = $this->createDefaultOrganization($user);
$organisations[] = $this->formatOrganisation($organization, 'admin', true);
}
$roles = $user->roles()->create([
'name' => 'admin',
'org_id' => $organisation->org_id
]);
DB::table('users_roles')->insert([
'user_id' => $user->id,
'role_id' => $roles->id
]);

// Generate JWT token
$token = JWTAuth::fromUser($user);

DB::commit();

$email_template_id = null;

$emailTemplate = EmailTemplate::where('title', 'welcome-email')->first();;
if ($emailTemplate) {
$email_template_id = $emailTemplate->id;
}

return response()->json([
'status_code' => 201,
'message' => 'User Created Successfully',
'status_code' => 201,
"message" => "User Created Successfully",
'email_template_id' => $email_template_id,
'access_token' => $token,
'data' => [
'user' => [
'id' => $user->id,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'avatar_url' => $user->profile->avatar_url,
'email' => $user->email,
'is_superadmin' => false,
'role' => $user->role
],
'organisations' => $organisations
'user' => new UserResource($user->load('owned_organisations', 'profile'))
],
], 201);

} catch (\Exception $e) {
DB::rollBack();
return $this->apiResponse('Registration unsuccessful', Response::HTTP_BAD_REQUEST);
Log::error($e);
return $this->ap('Registration unsuccessful', Response::HTTP_BAD_REQUEST);
}
}

Expand Down
41 changes: 13 additions & 28 deletions app/Http/Controllers/Api/V1/Auth/LoginController.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
namespace App\Http\Controllers\Api\V1\Auth;

use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Validator;

Expand All @@ -20,49 +22,32 @@ public function login(Request $request)

if ($validator->fails()) {
return response()->json([
'status_code' => 400,
'message' => 'Validation failed',
'data' => $validator->errors()
], 400);
'status_code' => 401,
'message' => 'Invalid Credentials',
'error' => 'Invalid Email or Password'
], 401);
}

$credentials = $request->only('email', 'password');

if (!$token = JWTAuth::attempt($credentials)) {
if (!$token = JWTAuth::attempt($request->only('email', 'password'))) {
$key = 'login_attempts_'.request()->ip();
RateLimiter::hit($key,3600);
return response()->json([
'status_code' => 401,
'message' => 'Invalid credentials',
'data' => []
'error' => 'Invalid Email or Password'
], 401);
}

$user = Auth::user();
$profile = $user->profile;

$organisations = $user->organisations->map(function ($org) use ($user) {
return [
'organisation_id' => $org->org_id,
'name' => $org->name,
'role' => $org->pivot->role ?? null,
'is_owner' => $org->pivot->user_id === $user->id
];
});
$user->last_login_at = now();
$user->save();

return response()->json([
'status_code' => 200,
'message' => 'Login successful',
'access_token' => $token,
'data' => [
'user' => [
'id' => $user->id,
'first_name' => $profile->first_name ?? null,
'last_name' => $profile->last_name ?? null,
'email' => $user->email,
'avatar_url' => $profile->avatar_url ?? null,
'is_superadmin' => $user->role === 'superadmin',
'role' => $user->role
],
'organisations' => $organisations
'user' => new UserResource($user->load('profile', 'owned_organisations'))
]
], 200);
}
Expand Down
113 changes: 96 additions & 17 deletions app/Http/Controllers/Api/V1/User/UserController.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,25 @@ public function stats()
*/
public function index()
{
$users = User::paginate();

return response()->json(
[
"status_code" => 200,
"message" => "Users returned successfully",
"data" => $users
$users = User::paginate(15);

return response()->json([
'status_code' => 200,
'message' => 'Users retrieved successfully',
'status' => 'success',
'data' => [
'users' => $users->items(),
'pagination' => [
'current_page' => $users->currentPage(),
'per_page' => $users->perPage(),
'total' => $users->total(),
'last_page' => $users->lastPage(),
],
200
);
]
]);
}




/**
Expand All @@ -56,14 +64,69 @@ public function store(Request $request)
{
//
}

/**
* Display the specified resource.
*/
public function show(User $user)
{
return $user->load('profile', 'products', 'organisations');
// Load the necessary relationships
$user->load('profile', 'products', 'organisations');

// Format the response data
$response = [
'status_code' => 200,
'user' => [
'id' => $user->id,
'created_at' => $user->created_at,
'updated_at' => $user->updated_at,
'first_name' => $user->profile->first_name ?? '',
'last_name' => $user->profile->last_name ?? '',
'email' => $user->email,
'status' => null,
'phone' => $user->phone,
'is_active' => $user->is_active,
'backup_codes' => null,
'attempts_left' => null,
'time_left' => null,
'secret' => null,
'is_2fa_enabled' => false,
'deletedAt' => $user->deleted_at,
'profile' => [
'id' => $user->profile->id ?? null,
'created_at' => $user->profile->created_at ?? null,
'updated_at' => $user->profile->updated_at ?? null,
'username' => '',
'jobTitle' => $user->profile->job_title ?? null,
'pronouns' => $user->profile->pronoun ?? null,
'department' => null,
'email' => $user->email,
'bio' => $user->profile->bio ?? null,
'social_links' => null,
'language' => null,
'region' => null,
'timezones' => null,
'profile_pic_url' => $user->profile->avatar_url ?? null,
'deletedAt' => $user->profile->deleted_at ?? null
],
'owned_organisations' => $user->organisations->map(function ($organisation) {
return [
'id' => $organisation->id,
'created_at' => $organisation->created_at,
'updated_at' => $organisation->updated_at,
'name' => $organisation->name,
'description' => $organisation->description,
'email' => $organisation->email,
'industry' => $organisation->industry,
'type' => $organisation->type,
'country' => $organisation->country,
'address' => $organisation->address,
'state' => $organisation->state,
'isDeleted' => $organisation->deleted_at ? true : false
];
})
]
];

return response()->json($response);
}


/**
* Update the specified resource in storage.
Expand Down Expand Up @@ -133,16 +196,32 @@ public function update(Request $request, string $id)
public function destroy(string $id)
{
$user = User::find($id);

if (!$user) {
return response()->json([
'status_code' => 404,
'message' => 'User not found'
], 404);
}


$authUser = auth()->user();

if ($authUser->id !== $user->id) {
if (!in_array($authUser->role, ['superAdmin', 'admin'])) {
return response()->json([
'status_code' => 403,
'message' => 'Unauthorized to delete this user'
], 403);
}
}

$user->delete();
return response()->noContent();

return response()->json([
'status_code' => 200,
'message' => 'User deleted successfully'
], 200);
}


}
5 changes: 3 additions & 2 deletions app/Http/Resources/OrganisationResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,18 @@ class OrganisationResource extends JsonResource
public function toArray(Request $request): array
{
return [
'org_id' => $this->org_id,
'organisation_id' => $this->org_id,
'name' => $this->name,
'email' => $this->email,
'description' => $this->description,
'is_owner' => true,
'role' => 'Admin',
'industry' => $this->industry,
'type' => $this->type,
'country' => $this->country,
'address' => $this->address,
'state' => $this->state,
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
}
Loading

0 comments on commit c7a872e

Please sign in to comment.