|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Services; |
| 4 | + |
| 5 | +use Illuminate\Support\Facades\File; |
| 6 | +use RuntimeException; |
| 7 | + |
| 8 | +class BootstrapService |
| 9 | +{ |
| 10 | + public static function ensureBoottimeEnvironment(): void |
| 11 | + { |
| 12 | + self::checkOAuthKeyPermissions(); |
| 13 | + self::ensureAvatarTempDirectory(); |
| 14 | + } |
| 15 | + |
| 16 | + protected static function ensureAvatarTempDirectory(): void |
| 17 | + { |
| 18 | + $path = storage_path('app/avatar-temp'); |
| 19 | + |
| 20 | + if (! File::isDirectory($path)) { |
| 21 | + File::makeDirectory($path, 0755, true); |
| 22 | + |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + $perms = fileperms($path) & 0777; |
| 27 | + |
| 28 | + if ($perms === 0755) { |
| 29 | + return; |
| 30 | + } |
| 31 | + |
| 32 | + if (@chmod($path, 0755)) { |
| 33 | + return; |
| 34 | + } |
| 35 | + |
| 36 | + throw new RuntimeException( |
| 37 | + "Avatar temp directory \"{$path}\" has incorrect permissions (".self::formatPerms($perms).'). '. |
| 38 | + "Expected 0755. Please run: chmod 755 {$path}" |
| 39 | + ); |
| 40 | + } |
| 41 | + |
| 42 | + protected static function checkOAuthKeyPermissions(): void |
| 43 | + { |
| 44 | + $privateKeyPath = storage_path('oauth-private.key'); |
| 45 | + $publicKeyPath = storage_path('oauth-public.key'); |
| 46 | + |
| 47 | + self::checkOAuthFile($privateKeyPath); |
| 48 | + self::checkOAuthFile($publicKeyPath); |
| 49 | + } |
| 50 | + |
| 51 | + protected static function checkOAuthFile(string $filePath): void |
| 52 | + { |
| 53 | + if (app()->environment('production') && ! file_exists($filePath)) { |
| 54 | + throw new RuntimeException( |
| 55 | + "OAuth key file {$filePath} is missing. Please generate OAuth keys." |
| 56 | + ); |
| 57 | + } |
| 58 | + |
| 59 | + $permissions = self::getPermissions($filePath); |
| 60 | + |
| 61 | + $isSafe = ($permissions === '600' || $permissions === '660'); |
| 62 | + |
| 63 | + if ($isSafe) { |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + $fixed = @chmod($filePath, 0660); |
| 68 | + |
| 69 | + if ($fixed) { |
| 70 | + return; |
| 71 | + } |
| 72 | + |
| 73 | + throw new RuntimeException( |
| 74 | + "File {$filePath} has bad permissions ({$permissions}). "."Should be 600 or 660. Run this command: chmod 660 {$filePath}" |
| 75 | + ); |
| 76 | + } |
| 77 | + |
| 78 | + protected static function getPermissions(string $filePath): string |
| 79 | + { |
| 80 | + $permissionNumber = fileperms($filePath) & 0777; |
| 81 | + |
| 82 | + return decoct($permissionNumber); |
| 83 | + } |
| 84 | + |
| 85 | + protected static function formatPerms(int $perms): string |
| 86 | + { |
| 87 | + return sprintf('%04o', $perms); |
| 88 | + } |
| 89 | +} |
0 commit comments