Skip to content

Commit 03c83c0

Browse files
committed
Revert use of cookies, go back to using a JWT
1 parent 871147f commit 03c83c0

File tree

8 files changed

+80
-44
lines changed

8 files changed

+80
-44
lines changed

app/Http/Controllers/Auth/AbstractLoginController.php

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
namespace Pterodactyl\Http\Controllers\Auth;
44

5+
use Cake\Chronos\Chronos;
56
use Lcobucci\JWT\Builder;
67
use Illuminate\Http\Request;
78
use Pterodactyl\Models\User;
@@ -139,19 +140,35 @@ protected function sendLoginResponse(User $user, Request $request): JsonResponse
139140

140141
$this->auth->guard()->login($user, true);
141142

142-
debug($request->cookies->all());
143-
144143
return response()->json([
145144
'complete' => true,
146145
'intended' => $this->redirectPath(),
147-
'cookie' => [
148-
'name' => config('session.cookie'),
149-
'value' => $this->encrypter->encrypt($request->cookie(config('session.cookie'))),
150-
],
151-
'user' => (new AccountTransformer())->transform($user),
146+
'jwt' => $this->createJsonWebToken($user),
152147
]);
153148
}
154149

150+
/**
151+
* Create a new JWT for the request and sign it using the signing key.
152+
*
153+
* @param User $user
154+
* @return string
155+
*/
156+
protected function createJsonWebToken(User $user): string
157+
{
158+
$token = $this->builder
159+
->setIssuer('Pterodactyl Panel')
160+
->setAudience(config('app.url'))
161+
->setId(str_random(16), true)
162+
->setIssuedAt(Chronos::now()->getTimestamp())
163+
->setNotBefore(Chronos::now()->getTimestamp())
164+
->setExpiration(Chronos::now()->addSeconds(config('session.lifetime'))->getTimestamp())
165+
->set('user', (new AccountTransformer())->transform($user))
166+
->sign($this->getJWTSigner(), $this->getJWTSigningKey())
167+
->getToken();
168+
169+
return $token->__toString();
170+
}
171+
155172
/**
156173
* Determine if the user is logging in using an email or username,.
157174
*

app/Http/Kernel.php

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,8 +80,6 @@ class Kernel extends HttpKernel
8080
],
8181
'client-api' => [
8282
'throttle:240,1',
83-
EncryptCookies::class,
84-
StartSession::class,
8583
SubstituteClientApiBindings::class,
8684
SetSessionDriver::class,
8785
'api..key:' . ApiKey::TYPE_ACCOUNT,

app/Http/Middleware/Api/AuthenticateKey.php

Lines changed: 17 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
use Closure;
66
use Lcobucci\JWT\Parser;
77
use Cake\Chronos\Chronos;
8-
use Illuminate\Support\Str;
98
use Illuminate\Http\Request;
109
use Pterodactyl\Models\ApiKey;
1110
use Illuminate\Auth\AuthManager;
@@ -64,24 +63,19 @@ public function __construct(ApiKeyRepositoryInterface $repository, AuthManager $
6463
public function handle(Request $request, Closure $next, int $keyType)
6564
{
6665
if (is_null($request->bearerToken())) {
67-
if (! Str::startsWith($request->route()->getName(), ['api.client']) && ! $request->user()) {
68-
throw new HttpException(401, null, null, ['WWW-Authenticate' => 'Bearer']);
69-
}
66+
throw new HttpException(401, null, null, ['WWW-Authenticate' => 'Bearer']);
7067
}
7168

72-
if (is_null($request->bearerToken())) {
73-
$model = (new ApiKey)->forceFill([
74-
'user_id' => $request->user()->id,
75-
'key_type' => ApiKey::TYPE_ACCOUNT,
76-
]);
77-
}
69+
$raw = $request->bearerToken();
7870

79-
if (! isset($model)) {
80-
$raw = $request->bearerToken();
71+
// This is an internal JWT, treat it differently to get the correct user before passing it along.
72+
if (strlen($raw) > ApiKey::IDENTIFIER_LENGTH + ApiKey::KEY_LENGTH) {
73+
$model = $this->authenticateJWT($raw);
74+
} else {
8175
$model = $this->authenticateApiKey($raw, $keyType);
82-
$this->auth->guard()->loginUsingId($model->user_id);
8376
}
8477

78+
$this->auth->guard()->loginUsingId($model->user_id);
8579
$request->attributes->set('api_key', $model);
8680

8781
return $next($request);
@@ -103,6 +97,16 @@ protected function authenticateJWT(string $token): ApiKey
10397
throw new HttpException(401, null, null, ['WWW-Authenticate' => 'Bearer']);
10498
}
10599

100+
// Run through the token validation and throw an exception if the token is not valid.
101+
if (
102+
$token->getClaim('nbf') > Chronos::now()->getTimestamp()
103+
|| $token->getClaim('iss') !== 'Pterodactyl Panel'
104+
|| $token->getClaim('aud') !== config('app.url')
105+
|| $token->getClaim('exp') <= Chronos::now()->getTimestamp()
106+
) {
107+
throw new AccessDeniedHttpException;
108+
}
109+
106110
return (new ApiKey)->forceFill([
107111
'user_id' => object_get($token->getClaim('user'), 'id', 0),
108112
'key_type' => ApiKey::TYPE_ACCOUNT,

app/Transformers/Api/Client/AccountTransformer.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ public function getResourceName(): string
2525
public function transform(User $model)
2626
{
2727
return [
28+
'id' => $model->id,
2829
'admin' => $model->root_admin,
2930
'username' => $model->username,
3031
'email' => $model->email,

resources/assets/scripts/helpers/axios.js

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import User from './../models/user';
2+
13
/**
24
* We'll load the axios HTTP library which allows us to easily issue requests
35
* to our Laravel back-end. This library automatically handles sending the
@@ -7,6 +9,7 @@
79
let axios = require('axios');
810
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
911
axios.defaults.headers.common['Accept'] = 'application/json';
12+
axios.defaults.headers.common['Authorization'] = `Bearer ${User.getToken()}`;
1013

1114
if (typeof phpdebugbar !== 'undefined') {
1215
axios.interceptors.response.use(function (response) {

resources/assets/scripts/models/user.js

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,37 @@
1-
import axios from './../helpers/axios';
1+
import isString from 'lodash/isString';
2+
import jwtDecode from 'jwt-decode';
23

34
export default class User {
45
/**
5-
* Get a new user model by hitting the Panel API using the authentication token
6-
* provided. If no user can be retrieved null will be returned.
6+
* Get a new user model from the JWT.
77
*
8-
* @return {User|null}
8+
* @return {User | null}
99
*/
10-
static fromCookie() {
11-
axios.get('/api/client/account')
12-
.then(response => {
13-
return new User(response.data.attributes);
14-
})
15-
.catch(err => {
16-
console.error(err);
17-
return null;
18-
});
10+
static fromToken(token) {
11+
if (!isString(token)) {
12+
token = localStorage.getItem('token');
13+
}
14+
15+
if (!isString(token) || token.length < 1) {
16+
return null;
17+
}
18+
19+
const data = jwtDecode(token);
20+
if (data.user) {
21+
return new User(data.user);
22+
}
23+
24+
return null;
25+
}
26+
27+
/**
28+
* Return the JWT for the authenticated user.
29+
*
30+
* @returns {string | null}
31+
*/
32+
static getToken()
33+
{
34+
return localStorage.getItem('token');
1935
}
2036

2137
/**

resources/assets/scripts/store/modules/auth.js

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ const route = require('./../../../../../vendor/tightenco/ziggy/src/js/route').de
44
export default {
55
namespaced: true,
66
state: {
7-
user: null,
7+
user: User.fromToken(),
88
},
99
getters: {
1010
/**
@@ -32,7 +32,7 @@ export default {
3232
}
3333

3434
if (response.data.complete) {
35-
commit('login', {cookie: response.data.cookie, user: response.data.user});
35+
commit('login', {jwt: response.data.jwt});
3636
return resolve({
3737
complete: true,
3838
intended: response.data.intended,
@@ -59,12 +59,9 @@ export default {
5959
},
6060
},
6161
mutations: {
62-
login: function (state, {cookie, user}) {
63-
state.user = new User(user);
64-
localStorage.setItem('token', JSON.stringify({
65-
name: cookie.name,
66-
value: cookie.value,
67-
}));
62+
login: function (state, {jwt}) {
63+
localStorage.setItem('token', jwt);
64+
state.user = User.fromToken(jwt);
6865
},
6966
logout: function (state) {
7067
localStorage.removeItem('token');

webpack.config.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ const productionPlugins = [
6565

6666
module.exports = {
6767
mode: process.env.NODE_ENV,
68-
devtool: process.env.NODE_ENV === 'production' ? false : 'eval-source-map',
68+
devtool: process.env.NODE_ENV === 'production' ? false : 'source-map',
6969
performance: {
7070
hints: false,
7171
},

0 commit comments

Comments
 (0)