first commit

This commit is contained in:
2026-10-09 08:21:06 +02:00
parent db7456df87
commit d259c62304
3761 changed files with 896046 additions and 0 deletions
@@ -0,0 +1,21 @@
<?php
namespace App\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,66 @@
<?php
namespace App\Services\Auth\Social;
use App\Models\Role;
use App\Models\User;
use App\Repositories\Role\RoleRepository;
use App\Repositories\User\UserRepository;
use App\Support\Enum\UserStatus;
use Illuminate\Support\Str;
use Laravel\Socialite\Contracts\User as SocialUser;
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' => setting('approval.enabled') ? UserStatus::WAITING_APPROVAL : 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, ''];
}
}
+132
View File
@@ -0,0 +1,132 @@
<?php
namespace App\Services\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Cache\RateLimiter;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
/**
* Login throttling, keyed on the submitted username and the client IP.
*
* This was laravel/ui's ThrottlesLogins trait plus Vanguard's overrides of it,
* inlined here so the package is no longer a dependency. The limits come from
* application settings rather than from properties, which is why maxAttempts()
* and decayMinutes() are methods.
*/
trait ThrottlesLogins
{
/**
* Get the login username to be used by the controller.
*/
public function username(): string
{
return 'username';
}
/**
* Determine if the user has too many failed login attempts.
*/
protected function hasTooManyLoginAttempts(Request $request): bool
{
return $this->limiter()->tooManyAttempts(
$this->throttleKey($request),
$this->maxAttempts()
);
}
/**
* Increment the login attempts for the user.
*/
protected function incrementLoginAttempts(Request $request): void
{
$this->limiter()->hit(
$this->throttleKey($request),
$this->decayMinutes() * 60
);
}
/**
* Clear the login locks for the given user credentials.
*/
protected function clearLoginAttempts(Request $request): void
{
$this->limiter()->clear($this->throttleKey($request));
}
/**
* Fire an event when a lockout occurs.
*/
protected function fireLockoutEvent(Request $request): void
{
event(new Lockout($request));
}
/**
* 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;
}
/**
* Redirect the user after determining they are locked out.
*
* Redirects rather than throwing a 429 ValidationException, so the lockout
* message lands on the login form like any other error.
*/
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(int $seconds): string
{
return trans('auth.throttle', ['seconds' => $seconds]);
}
/**
* Get the throttle key for the given request.
*/
protected function throttleKey(Request $request): string
{
return Str::transliterate(
Str::lower($request->input($this->username())).'|'.$request->ip()
);
}
protected function limiter(): RateLimiter
{
return app(RateLimiter::class);
}
protected function maxAttempts(): int
{
return (int) setting('throttle_attempts', 5);
}
protected function decayMinutes(): int
{
$lockout = (int) setting('throttle_lockout_time');
return max($lockout, 1);
}
}
@@ -0,0 +1,65 @@
<?php
namespace App\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 App\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 App\Services\Auth\TwoFactor\Contracts;
use App\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 App\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 App\Services\Upload;
use App\Models\User;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Filesystem\FilesystemManager;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Str;
use Intervention\Image\ImageManager;
class UserAvatarManager
{
public const AVATAR_WIDTH = 160;
public const AVATAR_HEIGHT = 160;
/**
* @var Filesystem
*/
private Filesystem|\Illuminate\Contracts\Filesystem\Filesystem $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->read($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->toJpeg(100)->__toString(),
'public'
);
return basename($fileName);
}
}