TRF Certest first commit

This commit is contained in:
2025-02-26 08:57:46 +01:00
commit 3ce064a108
2524 changed files with 475404 additions and 0 deletions
@@ -0,0 +1,21 @@
<?php
namespace Vanguard\Services\Auth\Social;
use Laravel\Socialite\Contracts\User as SocialUser;
trait ManagesSocialAvatarSize
{
/**
* Get appropriate image size for a specific provider.
*/
protected function getAvatarForProvider(string $provider, SocialUser $socialUser): string
{
return match ($provider) {
'facebook' => str_replace('width=1920', 'width=150', $socialUser->avatar_original),
'google' => $socialUser->avatar_original.'?sz=150',
'twitter' => str_replace('_normal', '_200x200', $socialUser->getAvatar()),
default => $socialUser->getAvatar()
};
}
}
@@ -0,0 +1,68 @@
<?php
namespace Vanguard\Services\Auth\Social;
use Illuminate\Support\Str;
use Laravel\Socialite\Contracts\User as SocialUser;
use Vanguard\Repositories\Role\RoleRepository;
use Vanguard\Repositories\User\UserRepository;
use Vanguard\Role;
use Vanguard\Support\Enum\UserStatus;
use Vanguard\User;
class SocialManager
{
use ManagesSocialAvatarSize;
public function __construct(private readonly UserRepository $users, private readonly RoleRepository $roles)
{
}
/**
* Associate social user with given provider. If user with the same email address
* retrieved from social network exists in our database, we will just associate it
* with provided social account. If not, user will be created.
*/
public function associate(SocialUser $socialUser, string $provider): User
{
$user = $this->users->findByEmail($socialUser->getEmail());
if (! $user) {
// User with email retrieved from social auth provider does not
// exist in our database. That means that we have to create new user here
[$firstName, $lastName] = $this->parseUserFullName($socialUser);
$role = $this->roles->findByName(Role::DEFAULT_USER_ROLE);
$user = $this->users->create([
'email' => $socialUser->getEmail(),
'password' => Str::random(10),
'first_name' => $firstName,
'last_name' => $lastName,
'status' => UserStatus::ACTIVE,
'avatar' => $this->getAvatarForProvider($provider, $socialUser),
'role_id' => $role->id,
'email_verified_at' => now(),
]);
}
// Associate social account with user account inside our application
$this->users->associateSocialAccountForUser($user->id, $provider, $socialUser);
return $user;
}
/**
* Parse User's name from his social network account.
*/
private function parseUserFullName(SocialUser $user): array
{
$name = $user->getName();
if (str_contains($name, ' ')) {
return explode(' ', $name, 2);
}
return [$name, ''];
}
}
+70
View File
@@ -0,0 +1,70 @@
<?php
namespace Vanguard\Services\Auth;
use Illuminate\Foundation\Auth\ThrottlesLogins as ThrottlesLoginsBase;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
trait ThrottlesLogins
{
use ThrottlesLoginsBase;
/**
* Get the login username to be used by the controller.
*/
public function username(): string
{
return 'username';
}
/**
* Determine how many retries are left for the user.
*/
protected function retriesLeft(Request $request): int
{
$attempts = $this->limiter()->attempts(
$this->throttleKey($request)
);
return $this->maxAttempts() - $attempts + 1;
}
/**
* {@inheritDoc}
*/
protected function sendLockoutResponse(Request $request): RedirectResponse
{
$seconds = $this->limiter()->availableIn(
$this->throttleKey($request)
);
return redirect('login')
->withInput($request->only($this->username(), 'remember'))
->withErrors([
$this->username() => $this->getLockoutErrorMessage($seconds),
]);
}
/**
* Get the login lockout error message.
*/
protected function getLockoutErrorMessage($seconds): string
{
return trans('auth.throttle', ['seconds' => $seconds]);
}
/** {@inheritDoc} */
protected function maxAttempts()
{
return setting('throttle_attempts', 5);
}
/** {@inheritDoc} */
protected function decayMinutes(): int
{
$lockout = (int) setting('throttle_lockout_time');
return max($lockout, 1);
}
}
@@ -0,0 +1,65 @@
<?php
namespace Vanguard\Services\Auth\TwoFactor;
trait Authenticatable
{
/**
* Get the e-mail address used for two-factor authentication.
*/
public function getEmailForTwoFactorAuth(): string
{
return $this->email;
}
/**
* Get the country code used for two-factor authentication.
*/
public function getAuthCountryCode(): string
{
return $this->two_factor_country_code;
}
/**
* Get the phone number used for two-factor authentication.
*/
public function getAuthPhoneNumber(): string
{
return $this->two_factor_phone;
}
/**
* Set the country code and phone number used for two-factor authentication.
*/
public function setAuthPhoneInformation(string $countryCode, string $phoneNumber)
{
$this->two_factor_country_code = $countryCode;
$this->two_factor_phone = $phoneNumber;
}
/**
* Get the two-factor provider options in array format.
*/
public function getTwoFactorAuthProviderOptions(): array
{
return json_decode($this->two_factor_options, true) ?: [];
}
/**
* Set the two-factor provider options in array format.
*/
public function setTwoFactorAuthProviderOptions(array $options): void
{
$this->two_factor_options = json_encode($options);
}
/**
* Determine if the user is using two-factor authentication.
*/
public function getUsingTwoFactorAuthAttribute(): bool
{
$options = $this->getTwoFactorAuthProviderOptions();
return isset($options['id']);
}
}
@@ -0,0 +1,38 @@
<?php
namespace Vanguard\Services\Auth\TwoFactor\Contracts;
use Illuminate\Contracts\Auth\Authenticatable as BaseAuthenticatable;
interface Authenticatable extends BaseAuthenticatable
{
/**
* Get the e-mail address used for two-factor authentication.
*/
public function getEmailForTwoFactorAuth(): string;
/**
* Get the country code used for two-factor authentication.
*/
public function getAuthCountryCode(): string;
/**
* Get the phone number used for two-factor authentication.
*/
public function getAuthPhoneNumber(): string;
/**
* Set the country code and phone number used for two-factor authentication.
*/
public function setAuthPhoneInformation(string $countryCode, string $phoneNumber);
/**
* Get the two-factor provider options in array format.
*/
public function getTwoFactorAuthProviderOptions(): array;
/**
* Set the two-factor provider options in array format.
*/
public function setTwoFactorAuthProviderOptions(array $options): void;
}
@@ -0,0 +1,33 @@
<?php
namespace Vanguard\Services\Auth\TwoFactor\Contracts;
use Vanguard\Services\Auth\TwoFactor\Contracts\Authenticatable as TwoFactorAuthenticatable;
interface Provider
{
/**
* Determine if the given user has two-factor authentication enabled.
*/
public function isEnabled(TwoFactorAuthenticatable $user): bool;
/**
* Register the given user with the provider.
*/
public function register(TwoFactorAuthenticatable $user): void;
/**
* Sends an SMS with a phone verification token.
*/
public function sendTwoFactorVerificationToken(TwoFactorAuthenticatable $user): bool;
/**
* Determine if the given token is valid for the given user.
*/
public function tokenIsValid(TwoFactorAuthenticatable $user, $token): bool;
/**
* Delete the given user from the provider.
*/
public function delete(TwoFactorAuthenticatable $user): void;
}
+14
View File
@@ -0,0 +1,14 @@
<?php
namespace Vanguard\Services\Auth\TwoFactor;
class Facade extends \Illuminate\Support\Facades\Facade
{
/**
* Get the registered name of the component.
*/
protected static function getFacadeAccessor(): string
{
return 'authy';
}
}
+109
View File
@@ -0,0 +1,109 @@
<?php
namespace Vanguard\Services\Upload;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Filesystem\FilesystemManager;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
use Intervention\Image\ImageManager;
use Vanguard\User;
class UserAvatarManager
{
public const AVATAR_WIDTH = 160;
public const AVATAR_HEIGHT = 160;
/**
* @var Filesystem
*/
private $fs;
/**
* @var string Storage disk used for keeping photos.
*/
protected string $disk = 'public';
public function __construct(FilesystemManager $fs, private readonly ImageManager $imageManager)
{
$this->fs = $fs->disk($this->disk);
}
/**
* Upload and crop user avatar to predefined width and height.
*/
public function uploadAndCropAvatar(UploadedFile $file, ?array $cropPoints = null): ?string
{
try {
return $this->cropAndResizeImage($file, $cropPoints);
} catch (\Exception $e) {
logger('Cannot upload and crop image. '.$e->getMessage());
return null;
}
}
/**
* Check if user has uploaded avatar photo. If he is using some external url for avatar, then
* it is assumed that avatar is not uploaded manually.
*/
private function userHasUploadedAvatar(User $user): bool
{
return $user->avatar && ! Str::contains($user->avatar, ['http', 'gravatar']);
}
/**
* Get destination directory where avatar should be uploaded.
*/
private function getDestinationDirectory(): string
{
return '/upload/users';
}
public function deleteAvatarIfUploaded(User $user): void
{
if (! $this->userHasUploadedAvatar($user)) {
return;
}
$path = sprintf(
'%s/%s',
$this->getDestinationDirectory(),
$user->avatar
);
$this->fs->delete($path);
}
/**
* Crop image from provided selected points and resize it to predefined width and height.
*/
private function cropAndResizeImage(UploadedFile $file, ?array $points = null): string
{
$image = $this->imageManager->make($file);
if ($points) {
// Calculate delta between two points on X axis. This
// value will be used as width and height for cropped image.
$size = floor($points['x2'] - $points['x1']);
$image->crop($size, $size, (int) $points['x1'], (int) $points['y1'])
->resize(self::AVATAR_WIDTH, self::AVATAR_HEIGHT);
} else {
// If crop points are not provided, we will just crop
// provided image to specified width and height.
$image->crop(self::AVATAR_WIDTH, self::AVATAR_HEIGHT);
}
$fileName = $file->hashName($this->getDestinationDirectory());
$this->fs->put(
$fileName,
$image->stream(null, 100)->__toString(),
'public'
);
return basename($fileName);
}
}