Skip to content

Commit

Permalink
Merge branch 'main' of github.com:fleetbase/core-api into feature-aut…
Browse files Browse the repository at this point in the history
…hentication
  • Loading branch information
roncodes committed Jan 15, 2024
2 parents b6e7f10 + 5b63074 commit fc0e65c
Show file tree
Hide file tree
Showing 19 changed files with 257 additions and 85 deletions.
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "fleetbase/core-api",
"version": "1.3.3",
"version": "1.3.6",
"description": "Core Framework and Resources for Fleetbase API",
"keywords": [
"fleetbase",
Expand All @@ -24,6 +24,7 @@
"giggsey/libphonenumber-for-php": "^8.13",
"grimzy/laravel-mysql-spatial": "^5.0",
"guzzlehttp/guzzle": "^7.4",
"hammerstone/fast-paginate": "^1.0",
"illuminate/broadcasting": "^7.0|^8.0|^9.0",
"illuminate/contracts": "^7.0|^8.0|^9.0",
"illuminate/database": "^7.0|^8.0|^9.0",
Expand Down
65 changes: 65 additions & 0 deletions config/laravel-mysql-s3-backup.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

use Aws\Credentials\CredentialProvider;

$provider = CredentialProvider::defaultProvider();

$s3Config = [
'version' => 'latest',
'bucket' => env('DB_BACKUP_BUCKET', 'fleetbase-db-backups'),
'region' => env('AWS_DEFAULT_REGION', 'ap-southeast-1'),
'endpoint' => env('AWS_ENDPOINT')
];

if (env('APP_ENV') === 'local' || env('APP_ENV') === 'development') {
$s3Config['key'] = env('AWS_ACCESS_KEY_ID');
$s3Config['secret'] = env('AWS_SECRET_ACCESS_KEY');
} else {
$s3Config['credentials'] = $provider;
}

return [
/*
* Configure with your Amazon S3 credentials
* You should use an IAM user who only has PutObject access
* to a specified bucket
*/
's3' => $s3Config,

/*
* Want to add some custom mysqldump args?
*/
'custom_mysqldump_args' => '--default-character-set=utf8mb4',

/*
* Whether or not to gzip the .sql file
*/
'gzip' => true,

/*
* Time allowed to run backup
*/
'sql_timout' => 7200, // 2 hours

/*
* Backup filename
*/
'filename' => str_replace([' ', '-'], '_', env('APP_ENV', 'local')) . '_%s_backup-%s.sql',

/*
* Where to store the backup file locally
*/
'backup_dir' => '/tmp',

/*
* Do you want to keep a copy of it or delete it
* after it's been uploaded?
*/
'keep_local_copy' => false,

/*
* Do you want to keep a rolling number of
* backups on S3? How many days worth?
*/
'rolling_backup_days' => 30,
];
5 changes: 5 additions & 0 deletions src/Casts/Money.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Fleetbase\Support\Utils;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Support\Str;

class Money implements CastsAttributes
{
Expand All @@ -28,6 +29,10 @@ public function get($model, $key, $value, $attributes)
*/
public function set($model, $key, $value, $attributes)
{
if (is_float($value) || Str::contains($value, '.')) {
$value = number_format($value, 2, '.', '');
}

return Utils::numbersOnly($value);
}
}
30 changes: 30 additions & 0 deletions src/Expansions/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,4 +46,34 @@ public function error()
);
};
}

/**
* Formats a error response for the consumable API.
*
* @return Closure
*/
public function apiError()
{
/*
* Returns an error response.
*
* @param array $params
* @param mixed $default
* @return mixed
*/
return function ($error, int $statusCode = 400, ?array $data = []) {
if ($error instanceof MessageBag) {
$error = $error->all();
}

/* @var \Illuminate\Support\Facades\Response $this */
return static::json(
[
'error' => $error,
...$data,
],
$statusCode
);
};
}
}
47 changes: 47 additions & 0 deletions src/Http/Controllers/Api/v1/OrganizationController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

namespace Fleetbase\Http\Controllers\Api\v1;

use Fleetbase\Http\Controllers\Controller;
use Fleetbase\Http\Resources\Organization;
use Fleetbase\Models\ApiCredential;
use Fleetbase\Models\Company;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class OrganizationController extends Controller
{
public function getCurrent(Request $request)
{
$token = $request->bearerToken();
$isSecretKey = Str::startsWith($token, '$');

// Depending on API key format set the connection to find credential on
$connection = Str::startsWith($token, 'flb_test_') ? 'sandbox' : 'mysql';

// Find the API Credential record
$findApKey = ApiCredential::on($connection)
->where(function ($query) use ($isSecretKey, $token) {
if ($isSecretKey) {
$query->where('secret', $token);
} else {
$query->where('key', $token);
}
})
->with(['company.owner'])
->withoutGlobalScopes();

// Get the api credential model record
$apiCredential = $findApKey->first();

// Handle no api credential found
if (!$apiCredential) {
return response()->error('No API key found to fetch company details with.');
}

// Get the organization owning the API key
$organization = Company::where('uuid', $apiCredential->company_uuid)->first();

return new Organization($organization);
}
}
5 changes: 4 additions & 1 deletion src/Http/Controllers/Internal/v1/SettingController.php
Original file line number Diff line number Diff line change
Expand Up @@ -413,7 +413,6 @@ public function testNotificationChannelsConfig(Request $request)
$responseMessage = $e->getMessage();
$status = 'error';
} catch (\Throwable $e) {
dd($e);
$responseMessage = $e->getMessage();
$status = 'error';
}
Expand Down Expand Up @@ -450,10 +449,14 @@ public function saveBrandingSettings(Request $request)

if ($iconUuid) {
Setting::configure('branding.icon_uuid', $iconUuid);
} else {
Setting::configure('branding.icon_uuid', null);
}

if ($logoUuid) {
Setting::configure('branding.logo_uuid', $logoUuid);
} else {
Setting::configure('branding.logo_uuid', null);
}

$brandingSettings = Setting::getBranding();
Expand Down
5 changes: 4 additions & 1 deletion src/Http/Resources/Organization.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

namespace Fleetbase\Http\Resources;

use Fleetbase\Models\Setting;
use Fleetbase\Support\Http;

class Organization extends FleetbaseResource
Expand All @@ -25,10 +26,12 @@ public function toArray($request)
'timezone' => $this->timezone,
'logo_url' => $this->logo_url,
'backdrop_url' => $this->backdrop_url,
'branding' => Setting::getBranding(),
'options' => $this->options,
'slug' => $this->slug,
'created_at' => $this->created_at,
'status' => $this->status,
'updated_at' => $this->updated_at,
'created_at' => $this->created_at,
];
}
}
3 changes: 1 addition & 2 deletions src/Mail/TestEmail.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
namespace Fleetbase\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Queue\SerializesModels;

class TestEmail extends Mailable implements ShouldQueue
class TestEmail extends Mailable
{
use Queueable;
use SerializesModels;
Expand Down
3 changes: 1 addition & 2 deletions src/Mail/VerifyEmail.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@

use Fleetbase\Models\VerificationCode;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\HtmlString;

class VerifyEmail extends Mailable implements ShouldQueue
class VerifyEmail extends Mailable
{
use Queueable;
use SerializesModels;
Expand Down
2 changes: 1 addition & 1 deletion src/Models/Company.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ class Company extends Model
'owner_uuid',
'logo_uuid',
'backdrop_uuid',
'address_uuid',
'place_uuid',
'website_url',
'description',
'options',
Expand Down
4 changes: 2 additions & 2 deletions src/Models/Setting.php
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ public static function lookup(string $key, $defaultValue = null)

public static function getBranding()
{
$brandingSettings = ['id' => 1, 'uuid' => 1];
$brandingSettings = ['id' => 1, 'uuid' => 1, 'icon_url' => null, 'logo_url' => null];
$iconUuid = static::where('key', 'branding.icon_uuid')->value('value');
$logoUuid = static::where('key', 'branding.logo_uuid')->value('value');
$defaultTheme = static::where('key', 'branding.default_theme')->value('value');
Expand All @@ -191,7 +191,7 @@ public static function getBranding()

// set branding settings
$brandingSettings['icon_uuid'] = $iconUuid;
$brandingSettings['logo_uuid'] = $iconUuid;
$brandingSettings['logo_uuid'] = $logoUuid;
$brandingSettings['default_theme'] = $defaultTheme ?? 'dark';

return $brandingSettings;
Expand Down
1 change: 1 addition & 0 deletions src/Providers/CoreServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ public function boot()
$this->mergeConfigFrom(__DIR__ . '/../../config/activitylog.php', 'activitylog');
$this->mergeConfigFrom(__DIR__ . '/../../config/excel.php', 'excel');
$this->mergeConfigFrom(__DIR__ . '/../../config/sentry.php', 'sentry');
$this->mergeConfigFrom(__DIR__ . '/../../config/laravel-mysql-s3-backup.php', 'laravel-mysql-s3-backup');
$this->mergeConfigFromSettings();
$this->addServerIpAsAllowedOrigin();
}
Expand Down
1 change: 1 addition & 0 deletions src/Support/Find.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,7 @@ public static function httpFilterForModel(Model $model, string $namespace = null
} else {
$internal = Http::isInternalRequest();

$baseNamespace = $filterNs;
if ($internal) {
$baseNamespace = $filterNs . 'Internal\\';
}
Expand Down
2 changes: 1 addition & 1 deletion src/Support/NotificationRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ private static function getNotificationClassProperty(string $notificationClass,
*
* @return array an array of associative arrays, each containing details about a parameter required by the constructor
*/
private function getNotificationClassParameters(string $notificationClass): array
private static function getNotificationClassParameters(string $notificationClass): array
{
// Make sure class exists
if (!class_exists($notificationClass)) {
Expand Down
12 changes: 7 additions & 5 deletions src/Support/Utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -633,13 +633,14 @@ public static function randomNumber($length = 4)
/**
* Converts the param to an integer with numbers only.
*
* @param string|mixed $string
*
* @return int
*/
public static function numbersOnly($string)
public static function numbersOnly($value)
{
return intval(preg_replace('/[^0-9]/', '', $string));
$string = strval($value);
$string = preg_replace('/[^0-9]/', '', $string);

return intval($string);
}

/**
Expand Down Expand Up @@ -2158,10 +2159,11 @@ public static function getDefaultMailFromAddress(?string $default = 'hello@fleet
*
* This function checks if the given URL starts with 'http://' or 'https://'.
* If it does, it parses the URL and adds 'www.' to the host part if it's not already there.
* If the URL does not start with 'http://' or 'https://', it simply checks if 'www.' is
* If the URL does not start with 'http://' or 'https://', it simply checks if 'www.' is
* already present at the start of the URL. If not, it adds 'www.'.
*
* @param string $url The URL to which 'www.' should be added if it's not already present.
*
* @return string The modified URL with 'www.' added if it was absent.
*
* Example usage:
Expand Down
1 change: 0 additions & 1 deletion src/Traits/Expandable.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
namespace Fleetbase\Traits;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

trait Expandable
{
Expand Down
4 changes: 2 additions & 2 deletions src/Traits/HasApiModelBehavior.php
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ public function queryFromRequest(Request $request, \Closure $queryCallback = nul
$limit = 999999999;
}

return $builder->paginate($limit, $columns);
return $builder->fastPaginate($limit, $columns);
}

// get the results
Expand Down Expand Up @@ -630,7 +630,7 @@ public function searchRecordFromRequest(Request $request)
$limit = $request->integer('limit', 30);
$builder = $this->searchBuilder($request);

return $builder->paginate($limit);
return $builder->fastPaginate($limit);
}

/**
Expand Down
Loading

0 comments on commit fc0e65c

Please sign in to comment.