Strip out JWT usage and use cookies to track the currently logged in user
This commit is contained in:
parent
a7fae86e58
commit
6336e5191f
|
@ -2,8 +2,6 @@
|
|||
|
||||
namespace Pterodactyl\Http\Controllers\Auth;
|
||||
|
||||
use Cake\Chronos\Chronos;
|
||||
use Lcobucci\JWT\Builder;
|
||||
use Illuminate\Http\Request;
|
||||
use Pterodactyl\Models\User;
|
||||
use Illuminate\Auth\AuthManager;
|
||||
|
@ -16,7 +14,6 @@ use Illuminate\Contracts\Auth\Authenticatable;
|
|||
use Illuminate\Contracts\Encryption\Encrypter;
|
||||
use Illuminate\Foundation\Auth\AuthenticatesUsers;
|
||||
use Pterodactyl\Traits\Helpers\ProvidesJWTServices;
|
||||
use Pterodactyl\Transformers\Api\Client\AccountTransformer;
|
||||
use Illuminate\Contracts\Cache\Repository as CacheRepository;
|
||||
use Pterodactyl\Contracts\Repository\UserRepositoryInterface;
|
||||
|
||||
|
@ -29,11 +26,6 @@ abstract class AbstractLoginController extends Controller
|
|||
*/
|
||||
protected $auth;
|
||||
|
||||
/**
|
||||
* @var \Lcobucci\JWT\Builder
|
||||
*/
|
||||
protected $builder;
|
||||
|
||||
/**
|
||||
* @var \Illuminate\Contracts\Cache\Repository
|
||||
*/
|
||||
|
@ -79,7 +71,6 @@ abstract class AbstractLoginController extends Controller
|
|||
* LoginController constructor.
|
||||
*
|
||||
* @param \Illuminate\Auth\AuthManager $auth
|
||||
* @param \Lcobucci\JWT\Builder $builder
|
||||
* @param \Illuminate\Contracts\Cache\Repository $cache
|
||||
* @param \Illuminate\Contracts\Encryption\Encrypter $encrypter
|
||||
* @param \PragmaRX\Google2FA\Google2FA $google2FA
|
||||
|
@ -87,14 +78,12 @@ abstract class AbstractLoginController extends Controller
|
|||
*/
|
||||
public function __construct(
|
||||
AuthManager $auth,
|
||||
Builder $builder,
|
||||
CacheRepository $cache,
|
||||
Encrypter $encrypter,
|
||||
Google2FA $google2FA,
|
||||
UserRepositoryInterface $repository
|
||||
) {
|
||||
$this->auth = $auth;
|
||||
$this->builder = $builder;
|
||||
$this->cache = $cache;
|
||||
$this->encrypter = $encrypter;
|
||||
$this->google2FA = $google2FA;
|
||||
|
@ -143,34 +132,10 @@ abstract class AbstractLoginController extends Controller
|
|||
return response()->json([
|
||||
'complete' => true,
|
||||
'intended' => $this->redirectPath(),
|
||||
'jwt' => $this->createJsonWebToken($user),
|
||||
'user' => $user->toVueObject(),
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new JWT for the request and sign it using the signing key.
|
||||
*
|
||||
* @param User $user
|
||||
* @return string
|
||||
*/
|
||||
protected function createJsonWebToken(User $user): string
|
||||
{
|
||||
$now = Chronos::now('utc');
|
||||
|
||||
$token = $this->builder
|
||||
->setIssuer('Pterodactyl Panel')
|
||||
->setAudience(config('app.url'))
|
||||
->setId(str_random(16), true)
|
||||
->setIssuedAt($now->getTimestamp())
|
||||
->setNotBefore($now->getTimestamp())
|
||||
->setExpiration($now->addSeconds(config('jwt.lifetime'))->getTimestamp())
|
||||
->set('user', (new AccountTransformer())->transform($user))
|
||||
->sign($this->getJWTSigner(), $this->getJWTSigningKey())
|
||||
->getToken();
|
||||
|
||||
return $token->__toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine if the user is logging in using an email or username,.
|
||||
*
|
||||
|
|
|
@ -49,6 +49,7 @@ class Kernel extends HttpKernel
|
|||
*/
|
||||
protected $middleware = [
|
||||
CheckForMaintenanceMode::class,
|
||||
EncryptCookies::class,
|
||||
ValidatePostSize::class,
|
||||
TrimStrings::class,
|
||||
ConvertEmptyStringsToNull::class,
|
||||
|
@ -62,7 +63,6 @@ class Kernel extends HttpKernel
|
|||
*/
|
||||
protected $middlewareGroups = [
|
||||
'web' => [
|
||||
EncryptCookies::class,
|
||||
AddQueuedCookiesToResponse::class,
|
||||
StartSession::class,
|
||||
AuthenticateSession::class,
|
||||
|
@ -82,8 +82,10 @@ class Kernel extends HttpKernel
|
|||
],
|
||||
'client-api' => [
|
||||
'throttle:240,1',
|
||||
SubstituteClientApiBindings::class,
|
||||
StartSession::class,
|
||||
SetSessionDriver::class,
|
||||
AuthenticateSession::class,
|
||||
SubstituteClientApiBindings::class,
|
||||
'api..key:' . ApiKey::TYPE_ACCOUNT,
|
||||
AuthenticateIPAccess::class,
|
||||
],
|
||||
|
|
|
@ -3,9 +3,9 @@
|
|||
namespace Pterodactyl\Http\Middleware\Api;
|
||||
|
||||
use Closure;
|
||||
use Lcobucci\JWT\Parser;
|
||||
use Cake\Chronos\Chronos;
|
||||
use Illuminate\Http\Request;
|
||||
use Pterodactyl\Models\User;
|
||||
use Pterodactyl\Models\ApiKey;
|
||||
use Illuminate\Auth\AuthManager;
|
||||
use Illuminate\Contracts\Encryption\Encrypter;
|
||||
|
@ -62,15 +62,19 @@ class AuthenticateKey
|
|||
*/
|
||||
public function handle(Request $request, Closure $next, int $keyType)
|
||||
{
|
||||
if (is_null($request->bearerToken())) {
|
||||
if (is_null($request->bearerToken()) && is_null($request->user())) {
|
||||
throw new HttpException(401, null, null, ['WWW-Authenticate' => 'Bearer']);
|
||||
}
|
||||
|
||||
$raw = $request->bearerToken();
|
||||
|
||||
// This is an internal JWT, treat it differently to get the correct user before passing it along.
|
||||
if (strlen($raw) > ApiKey::IDENTIFIER_LENGTH + ApiKey::KEY_LENGTH) {
|
||||
$model = $this->authenticateJWT($raw);
|
||||
// This is a request coming through using cookies, we have an authenticated user not using
|
||||
// an API key. Make some fake API key models and continue on through the process.
|
||||
if (empty($raw) && $request->user() instanceof User) {
|
||||
$model = new ApiKey([
|
||||
'user_id' => $request->user()->id,
|
||||
'key_type' => ApiKey::TYPE_ACCOUNT,
|
||||
]);
|
||||
} else {
|
||||
$model = $this->authenticateApiKey($raw, $keyType);
|
||||
}
|
||||
|
@ -81,42 +85,6 @@ class AuthenticateKey
|
|||
return $next($request);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate an API request using a JWT rather than an API key.
|
||||
*
|
||||
* @param string $token
|
||||
* @return \Pterodactyl\Models\ApiKey
|
||||
*/
|
||||
protected function authenticateJWT(string $token): ApiKey
|
||||
{
|
||||
$token = (new Parser)->parse($token);
|
||||
|
||||
// If the key cannot be verified throw an exception to indicate that a bad
|
||||
// authorization header was provided.
|
||||
if (! $token->verify($this->getJWTSigner(), $this->getJWTSigningKey())) {
|
||||
throw new HttpException(401, null, null, ['WWW-Authenticate' => 'Bearer']);
|
||||
}
|
||||
|
||||
// Run through the token validation and throw an exception if the token is not valid.
|
||||
//
|
||||
// The issued_at time is used for verification in order to allow rapid changing of session
|
||||
// length on the Panel without having to wait on existing tokens to first expire.
|
||||
$now = Chronos::now('utc');
|
||||
if (
|
||||
Chronos::createFromTimestampUTC($token->getClaim('nbf'))->gt($now)
|
||||
|| $token->getClaim('iss') !== 'Pterodactyl Panel'
|
||||
|| $token->getClaim('aud') !== config('app.url')
|
||||
|| Chronos::createFromTimestampUTC($token->getClaim('iat'))->addMinutes(config('jwt.lifetime'))->lte($now)
|
||||
) {
|
||||
throw new AccessDeniedHttpException('The authentication parameters provided are not valid for accessing this resource.');
|
||||
}
|
||||
|
||||
return (new ApiKey)->forceFill([
|
||||
'user_id' => object_get($token->getClaim('user'), 'id', 0),
|
||||
'key_type' => ApiKey::TYPE_ACCOUNT,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Authenticate an API key.
|
||||
*
|
||||
|
|
|
@ -5,6 +5,7 @@ namespace Pterodactyl\Models;
|
|||
use Sofa\Eloquence\Eloquence;
|
||||
use Sofa\Eloquence\Validable;
|
||||
use Pterodactyl\Rules\Username;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Validation\Rules\In;
|
||||
use Illuminate\Auth\Authenticatable;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
|
@ -177,6 +178,16 @@ class User extends Model implements
|
|||
return $rules;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the user model in a format that can be passed over to Vue templates.
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
public function toVueObject(): array
|
||||
{
|
||||
return (new Collection($this->toArray()))->except(['id', 'external_id'])->toArray();
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the password reset notification.
|
||||
*
|
||||
|
|
|
@ -1,5 +1,3 @@
|
|||
import User from './../models/user';
|
||||
|
||||
/**
|
||||
* We'll load the axios HTTP library which allows us to easily issue requests
|
||||
* to our Laravel back-end. This library automatically handles sending the
|
||||
|
@ -9,7 +7,6 @@ import User from './../models/user';
|
|||
let axios = require('axios');
|
||||
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
|
||||
axios.defaults.headers.common['Accept'] = 'application/json';
|
||||
axios.defaults.headers.common['Authorization'] = `Bearer ${User.getToken()}`;
|
||||
|
||||
if (typeof phpdebugbar !== 'undefined') {
|
||||
axios.interceptors.response.use(function (response) {
|
||||
|
|
|
@ -1,40 +1,4 @@
|
|||
import isString from 'lodash/isString';
|
||||
import jwtDecode from 'jwt-decode';
|
||||
|
||||
export default class User {
|
||||
/**
|
||||
* Get a new user model from the JWT.
|
||||
*
|
||||
* @return {User | null}
|
||||
*/
|
||||
static fromToken(token) {
|
||||
if (!isString(token)) {
|
||||
token = this.getToken();
|
||||
}
|
||||
|
||||
if (!isString(token) || token.length < 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = jwtDecode(token);
|
||||
if (data.user) {
|
||||
return new User(data.user);
|
||||
}
|
||||
} catch (ex) {}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the JWT for the authenticated user.
|
||||
*
|
||||
* @returns {string | null}
|
||||
*/
|
||||
static getToken() {
|
||||
return localStorage.getItem('token');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a new user model.
|
||||
*
|
||||
|
@ -46,14 +10,14 @@ export default class User {
|
|||
* @param {String} language
|
||||
*/
|
||||
constructor({
|
||||
admin,
|
||||
root_admin,
|
||||
username,
|
||||
email,
|
||||
first_name,
|
||||
last_name,
|
||||
language,
|
||||
}) {
|
||||
this.admin = admin;
|
||||
this.admin = root_admin;
|
||||
this.username = username;
|
||||
this.email = email;
|
||||
this.name = `${first_name} ${last_name}`;
|
||||
|
@ -61,11 +25,4 @@ export default class User {
|
|||
this.last_name = last_name;
|
||||
this.language = language;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the JWT belonging to the current user.
|
||||
*/
|
||||
getJWT() {
|
||||
return jwtDecode(User.getToken());
|
||||
}
|
||||
}
|
||||
|
|
|
@ -10,6 +10,7 @@ import Login from './components/auth/Login';
|
|||
import Dashboard from './components/dashboard/Dashboard';
|
||||
import Account from './components/dashboard/Account';
|
||||
import ResetPassword from './components/auth/ResetPassword';
|
||||
import User from './models/user';
|
||||
|
||||
const routes = [
|
||||
{ name: 'login', path: '/auth/login', component: Login },
|
||||
|
@ -52,17 +53,10 @@ router.beforeEach((to, from, next) => {
|
|||
|
||||
const user = store.getters['auth/getUser'];
|
||||
|
||||
// If user is trying to access any of the non-authentication endpoints ensure that they have
|
||||
// a valid, non-expired JWT.
|
||||
if (!to.path.startsWith('/auth')) {
|
||||
// Check if the JWT has expired. Don't use the exp field, but rather that issued at time
|
||||
// so that we can adjust how long we want to wait for expiration on both server-side and
|
||||
// client side without having to wait for older tokens to pass their expiration time if
|
||||
// we lower it.
|
||||
if (user === null || compareDate(addHours(dateParse(user.getJWT().iat * 1000), 12), new Date()) < 0) {
|
||||
store.commit('auth/logout');
|
||||
return window.location = route('auth.logout');
|
||||
}
|
||||
// Check that if we're accessing a non-auth route that a user exists on the page.
|
||||
if (!to.path.startsWith('/auth') && !(user instanceof User)) {
|
||||
store.commit('auth/logout');
|
||||
return window.location = route('auth.logout');
|
||||
}
|
||||
|
||||
// Continue on through the pipeline.
|
||||
|
|
|
@ -5,7 +5,7 @@ const route = require('./../../../../../vendor/tightenco/ziggy/src/js/route').de
|
|||
export default {
|
||||
namespaced: true,
|
||||
state: {
|
||||
user: User.fromToken(),
|
||||
user: typeof window.PterodactylUser === 'object' ? new User(window.PterodactylUser) : null,
|
||||
},
|
||||
getters: {
|
||||
/**
|
||||
|
@ -41,7 +41,7 @@ export default {
|
|||
}
|
||||
|
||||
if (response.data.complete) {
|
||||
commit('login', {jwt: response.data.jwt});
|
||||
commit('login', response.data.user);
|
||||
return resolve({
|
||||
complete: true,
|
||||
intended: response.data.intended,
|
||||
|
@ -86,12 +86,10 @@ export default {
|
|||
setEmail: function (state, email) {
|
||||
state.user.email = email;
|
||||
},
|
||||
login: function (state, {jwt}) {
|
||||
localStorage.setItem('token', jwt);
|
||||
state.user = User.fromToken(jwt);
|
||||
login: function (state, data) {
|
||||
state.user = new User(data);
|
||||
},
|
||||
logout: function (state) {
|
||||
localStorage.removeItem('token');
|
||||
state.user = null;
|
||||
},
|
||||
},
|
||||
|
|
|
@ -9,6 +9,14 @@
|
|||
<meta name="csrf-token" content="{{ csrf_token() }}">
|
||||
@show
|
||||
|
||||
@section('user-data')
|
||||
@if(!is_null(Auth::user()))
|
||||
<script>
|
||||
window.PterodactylUser = {!! json_encode(Auth::user()->toVueObject()) !!}
|
||||
</script>
|
||||
@endif
|
||||
@show
|
||||
|
||||
@section('assets')
|
||||
{!! $asset->css('main.css') !!}
|
||||
@show
|
||||
|
|
Loading…
Reference in New Issue