2727use Carbon \Carbon ;
2828use Pterodactyl \Models \User ;
2929use Pterodactyl \Models \Server ;
30+ use Pterodactyl \Exceptions \Repository \RecordNotFoundException ;
3031use Pterodactyl \Contracts \Repository \DaemonKeyRepositoryInterface ;
3132
3233class DaemonKeyProviderService
3334{
35+ /**
36+ * @var \Pterodactyl\Services\DaemonKeys\DaemonKeyCreationService
37+ */
38+ private $ keyCreationService ;
39+
3440 /**
3541 * @var \Pterodactyl\Services\DaemonKeys\DaemonKeyUpdateService
3642 */
@@ -44,11 +50,16 @@ class DaemonKeyProviderService
4450 /**
4551 * GetDaemonKeyService constructor.
4652 *
47- * @param \Pterodactyl\Services\DaemonKeys\DaemonKeyUpdateService $keyUpdateService
53+ * @param \Pterodactyl\Services\DaemonKeys\DaemonKeyCreationService $keyCreationService
4854 * @param \Pterodactyl\Contracts\Repository\DaemonKeyRepositoryInterface $repository
55+ * @param \Pterodactyl\Services\DaemonKeys\DaemonKeyUpdateService $keyUpdateService
4956 */
50- public function __construct (DaemonKeyUpdateService $ keyUpdateService , DaemonKeyRepositoryInterface $ repository )
51- {
57+ public function __construct (
58+ DaemonKeyCreationService $ keyCreationService ,
59+ DaemonKeyRepositoryInterface $ repository ,
60+ DaemonKeyUpdateService $ keyUpdateService
61+ ) {
62+ $ this ->keyCreationService = $ keyCreationService ;
5263 $ this ->keyUpdateService = $ keyUpdateService ;
5364 $ this ->repository = $ repository ;
5465 }
@@ -66,12 +77,23 @@ public function __construct(DaemonKeyUpdateService $keyUpdateService, DaemonKeyR
6677 */
6778 public function handle (Server $ server , User $ user , $ updateIfExpired = true ): string
6879 {
69- $ userId = $ user ->root_admin ? $ server ->owner_id : $ user ->id ;
80+ try {
81+ $ key = $ this ->repository ->findFirstWhere ([
82+ ['user_id ' , '= ' , $ user ->id ],
83+ ['server_id ' , '= ' , $ server ->id ],
84+ ]);
85+ } catch (RecordNotFoundException $ exception ) {
86+ // If key doesn't exist but we are an admin or the server owner,
87+ // create it.
88+ if ($ user ->root_admin || $ user ->id === $ server ->owner_id ) {
89+ return $ this ->keyCreationService ->handle ($ server ->id , $ user ->id );
90+ }
7091
71- $ key = $ this ->repository ->findFirstWhere ([
72- ['user_id ' , '= ' , $ userId ],
73- ['server_id ' , '= ' , $ server ->id ],
74- ]);
92+ // If they aren't the admin or owner of the server, they shouldn't get access.
93+ // Subusers should always have an entry created when they are, so if there is
94+ // no record, it should fail.
95+ throw $ exception ;
96+ }
7597
7698 if (! $ updateIfExpired || Carbon::now ()->diffInSeconds ($ key ->expires_at , false ) > 0 ) {
7799 return $ key ->secret ;
0 commit comments